Index exceeds the number of array elements (1264).

3 views (last 30 days)
I have been trying to work on a function however it continues to get stuck on this section. I have made sure that the matrix/vector isn't starting on zero, but I dont understand why I continue to get this error.
i=1;
for f=1:length(x)
s(i)=x(i)+x(i+1);
i=i+1;
end

Accepted Answer

Geoff Hayes
Geoff Hayes on 5 Mar 2019
Karlie - f iterates from 1 to the length of your x array. This is fine except for
s(i)=x(i)+x(i+1);
because when i (and you could use f here) is the length of your array, then i+1 is one larger than the length and so x(i+1) is invalid giving you the above error message. Instead, try something like
for k=1:length(x)-1
s(k)=x(k)+x(k+1);
end
where we limit k to the interval [1, N-1] where N is the length your x array.

More Answers (1)

madhan ravi
madhan ravi on 5 Mar 2019
s=zeros(size(x)); % pre-allocate
for i = 1:numel(x) % assuming x a vector
% remove i=i+1

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!