index must be a positive integer or logical problem

Hi I can't see the problem in this code, would someone please help
R=3.5;
th = 0;
for i = 1:0.01:180;
SP(i) = (pi/2)*sin(th)*(1+((cos(th))/(R^2-(sin(th))^2)^0.5));
th = th+0.01;
end
plot(th,SP)
If I change i to be 1:180 and th to be th=th+1 it works, however as soon as I put in the incremental change it gives me this error
Also the plot is wrong, giving me a straight line at one point instead of for the full range when it should be a curve with all positive values.
Could someone please explain/help
Thank you very much Tom

Answers (1)

When you are looping with i=1:0.01:180, the second run through the loop has i=1.01. You are then trying to write into the "1.01"th element of the vector SP. That is what is causing the error.
EDIT:
You can do this without a for loop, by the way. (Also incorporated Paulo's correction for using degrees instead of radians for the input arguments.)
th = 0:0.01:180;
SP = (pi/2).*sind(th).*(1+((cosd(th))./(R^2-(sind(th)).^2).^0.5));
plot(th,SP)

4 Comments

Just a guess, you want to work with degrees not radians so the code might be
R=3.5;
th = 0;
n=1;
for i = 1:0.01:180;
SP(n) = (pi/2)*sind(th)*(1+((cosd(th))/(R^2-(sind(th))^2)^0.5));
th = th+0.01;
n=n+1;
end
plot(0:0.01:th,SP)
The reason that your plotting gave a straight line is that in your plotting command, you are plotting only the FINAL value of th (180), against all the values of SP, rather than 0:180 against SP.
+1 to Paulo's comment. sin() and cos() assume radian inputs.
+1 to you for the explanations and for removing the loop, I was away too many weeks, my MATLAB skills are returning slowly :)

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 5 Dec 2011

Community Treasure Hunt

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

Start Hunting!