"Index out of bounds" error

8 vues (au cours des 30 derniers jours)
Andrew Catherall
Andrew Catherall le 14 Déc 2015
Commenté : Stephen23 le 17 Déc 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

Réponse acceptée

Stephen23
Stephen23 le 14 Déc 2015
Modifié(e) : Stephen23 le 14 Déc 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 commentaires
Andrew Catherall
Andrew Catherall le 17 Déc 2015
Ah OK I finally understand now. Apologies for being so dense.
Stephen23
Stephen23 le 17 Déc 2015
You should never apologize for learning something!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by