Info

This question is closed. Reopen it to edit or answer.

"Index exceeds matrix dimensions"

2 views (last 30 days)
Lee Thompson IV
Lee Thompson IV on 28 Sep 2015
Closed: MATLAB Answer Bot on 20 Aug 2021
When I use the function r() in a for loop I get the error "Index exceeds matrix dimensions."
is a function defined in it's own .m file as:
function [dist] = r(a,e,theta)
%function [dist] = r(a,e,theta)
%Computes the distance from the center of the planet to the spacecraft
dist = a.*(1-e.^2)./(1+e.*cos(theta));
end
Main file starts here
a=5;
theta = [0:pi/100:2*pi];
e = [.1 .3 .5 .7 .9];
figure (2)
plot(Xearth,Yearth,'g')
hold on
axis equal
for i = e
%r = a.*(1-i.^2)./(1+i.*cos(theta)); %works properly with this instead but want to use fucntion
r = r(a,i,theta); %error points to this line
x = r.*cos(theta);
y = r.*sin(theta);
plot(x,y)
end

Answers (1)

Walter Roberson
Walter Roberson on 28 Sep 2015
Your line
r = r(a,i,theta); %error points to this line
says that the knowledge that r is a function is to be overridden to make r a numeric variable, the result of calling the function the first time. Then in the second time through the loop you try to access the numeric variable as if it it were a function.
Do not name your variables the same thing as any function that you might use. (Also do not name your variables the same thing as any of the common MATLAB functions such as "sum" or "image", as you will make this kind of mistake when you do, and you will confuse other people who have to read your code.)

Products

Community Treasure Hunt

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

Start Hunting!