"Index exceeds the number of array elements (2)" when it shouldn't?

1 view (last 30 days)
So Matlab shows an error in line 11 even though both vectors are defined and should have the exact same length of 45000.
Does anyone know where the problem lies?
I would be beyond grateful for your help!
function seq = problem_phone_2( y )
y = y.';
y = y - mean(y);
l = length(y);
%n = 2^nextpow2(l);
j = 1;
seq = zeros(1, 5);
for p = 1:5
a = zeros(l, 1);
for k = (((j - 1)*5000) + 1):(j*5000)
a(k) = y(k);
end
f = fft(a, l);
f = abs(f)/5000;
j = j + 2;
f1 = f(1:45000/2);
ind = f1 > 0.15;
f1 = ind.*f1;
[m,n] = findpeaks(f1);
y = n.*50/45;
if (y(1) + y(2)) - 1906 < 3
seq(p) = 1;
elseif (y(1) + y(2)) - 2033 < 3
seq(p) = 2;
elseif (y(1) + y(2)) - 2174 < 3
seq(p) = 3;
elseif (y(1) + y(2)) - 1979 < 3
seq(p) = 4;
elseif (y(1) + y(2)) - 2106 < 3
seq(p) = 5;
elseif (y(1) + y(2)) - 2247 < 3
seq(p) = 6;
elseif (y(1) + y(2)) - 2061 < 3
seq(p) = 7;
elseif (y(1) + y(2)) - 2188 < 3
seq(p) = 8;
elseif (y(1) + y(2)) - 2329 < 3
seq(p) = 9;
elseif (y(1) + y(2)) - 2277 < 3
seq(p) = 0;
end
end
end

Accepted Answer

Adam Danz
Adam Danz on 15 Nov 2021
It looks like this
for k = (((j - 1)*5000) + 1):(j*5000)
a(k) = y(k);
end
could be replaced with
k = (((j - 1)*5000) + 1):(j*5000);
a = y(k);
And since this function assumes y has 45000 elements, you should add a test to the top of the function,
assert(numel(y)==45000, 'Y should have 45000 elements.')

More Answers (0)

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!