MATLAB: Index exceeds the number of array elements (1264).

elementsindexMATLAB

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

Best Answer

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.