"Index out of bounds" error
조회 수: 8 (최근 30일)
이전 댓글 표시
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
댓글 수: 0
채택된 답변
Stephen23
2015년 12월 14일
편집: Stephen23
2015년 12월 14일
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
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!