MATLAB: “Index out of bounds” error

errorMATLAB and Simulink Student Suite

I am very new to Matlab, and have been trying to create function to do something quite specific. I have two functions, one which finds an approximation of e^x for n iterations using the Taylor series expansion, and another which then uses this function to find the smallest value of n for which the error is less than 1. The code for the taylorexp function is:
function taylorexp(order,iterations)
y=0;
for i=0:iterations
a=(order.^i)./factorial(i);
y=y+a;
end
disp(y)
And the code for the error function is:
function taylorexperror(erroracceptability,order)
answer=exp(order);
iterations=1;
y=0;
taylorexp(order,iterations)=y;
while abs(answer-y)>erroracceptability
y=taylorexp(order,iterations);
iterations=iterations+1;
end
disp(iterations)
end
When I run this say as taylorexp(1,10) I get this error message:
Attempted to access taylorexp(10,2); index out of bounds because size(taylorexp)=[10,1].
Error in taylorexperror (line 7)
y=taylorexp(order,iterations);
I am unsure how to proceed and would appreciate your help.
Thanks, Andrew

Best Answer

You are trying to access an array element that does not exist. Basically you have something like this:
>> X = [1,2,3]
>> X(4)
Index exceeds matrix dimensions.
Of course this causes an error, because there is no fourth element in X.
However it could be that there is some confusion with the variable taylorexp: although you define it as a variable on this line
taylorexp(order,iterations)=y;
perhaps you thought that that calls your taylorexp function?
I would recommend that you do not give functions and variables the same name (or use the names of any MATLAB functions). If it is supposed to be a function call, what do you imagine that
taylorexp(order,iterations)=y;
should do?
Related Question