"Index out of bounds" error

8 visualizzazioni (ultimi 30 giorni)
Andrew Catherall
Andrew Catherall il 14 Dic 2015
Commentato: Stephen23 il 17 Dic 2015
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

Risposta accettata

Stephen23
Stephen23 il 14 Dic 2015
Modificato: Stephen23 il 14 Dic 2015
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?
  6 Commenti
Andrew Catherall
Andrew Catherall il 17 Dic 2015
Ah OK I finally understand now. Apologies for being so dense.
Stephen23
Stephen23 il 17 Dic 2015
You should never apologize for learning something!

Accedi per commentare.

Più risposte (0)

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by