Attempted to access f(97); index out of bounds because numel(f)=96.

I have this equation to solve the P(f). But the problem is that f is a matrix of 1x96 the zred and d18ored are both matrix 82x1. and i need to create a matrix with the dimension 82x96. with the equation p(f). i tried with the "." and without it and the error is the same
f=1:0.2:20;
for i=length(f);
ti=zred';
yi=d18ored;
T=(1/(4*pi*f(i)))*(atan(sum(sin(4*pi*f(i)*ti)))/(sum(cos(4*pi*f(i)*ti))));
P(i+1)=((sum(yi*sin(2*pi*f(i+1).*(ti-T)))).^2)/sum(sin(2*pi*f(i+1).*(ti-T)).^2))+...
((sum(yi*cos(2*pi*f(i+1).*(ti-T)))).^2)/sum(cos(2*pi*f(i+1).*(ti-T)).^2));
end

 Accepted Answer

You are trying to access an array element that does not exist.
Consider:
>> X = [1,2,3] % only three elements
X =
1 2 3
>> X(4) % try to access the fourth element
Index exceeds matrix dimensions.
The error message even tells the line of code that causes the error. Lets have a look at why this occurs. You define f to be:
>> f = 1:0.2:20;
>> numel(f)
ans =
96
and then later you try to access f(i+1), where i is the loop variable, and is equal to length(f), so you are trying to access f(96+1) which is f(97). There is no element 97, because f only has 96 elements.

More Answers (1)

for i=length(f)
The above is simply
i=length(f);
there will be only one iteration performed. Since i==length(f), clearly in
P(i+1)=((sum(yi*sin(2*pi*f(i+1) ...
the expression f(i+1) will be an out of bounds reference to f(length(f)+1). Set the upper limit to length(f)-1 to refer only to inbounds locations.

Asked:

on 7 Nov 2015

Answered:

dpb
on 7 Nov 2015

Community Treasure Hunt

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

Start Hunting!