How can I make a loop the changes for the specified values?

I am trying to set time increment n such that it always corresponds to a 2 degree increment in TH2 based on current omega2. However, I do not believe my loop is set up to evaluate at a 2 degree increment. I do not know what steps to take to make my code run properly.
w2=2*pi;
TH2=0;
t=2
a2=0.5*t;
L2=50;
L3=150;
for n=1:2:length(w2)
TH3(n)=acosd((L2*cosd(TH2))/L3)
d(n)=((L2*sind(TH2(n)))-(L3*sind(TH3(n))))
w3(n)=(L2*w2*sind(TH2(n)))/L3*sind(TH3(n))
d2(n)=(L2*w2*cosd(TH2(n)))-L3*w3*cosd(TH3(n))
a3(n)=((-L3*w3^2*cosd(TH3(n)))+(L2*a2*sind(TH2(n))))+(L2*w2^2*cosd(TH2(n)))/L3*sind(TH3(n))
d3(n)=(L2*a2*cosd(TH2(n)))-(L2*w2^2*sind(TH2(n)))-(L3*a3*cosd(TH3(n)))+(L3*w3^2*sind(TH3(n)))
end

 Accepted Answer

The problem is that your ‘w2’ is a scalar of size (1 x 1), so the loop is already satisfied at the first iteration.
This might be closer to what you want to do:
for n=1:2:w2
although ‘n’ will increment in radians, not degrees. To have it increment in degrees, change your loop index to:
for n=1:2:w2*180/pi
or just:
for n=1:2:360
EDIT Also, ‘TH2’ and ‘TH3’ never change, so all calculations derived from them never change.

4 Comments

Thank you for your help! I believe I want my TH2 and TH3 values to change, though. If I want the "2 degree increment in TH2 based on current omega2" will I need a second loop to include the change in TH2 and TH3 values?
My pleasure!
I would create a vector for ‘TH2’, then use MATLAB’s vectorisation capabilities, and avoid the loop entirely. See Array vs. Matrix Operations for details.
See if this does what you want:
w2=2*pi;
TH2=0;
t=2;
a2=0.5*t;
L2=50;
L3=150;
TH2 = 0:2:360;
TH3=acosd((L2.*cosd(TH2))./L3);
d=((L2.*sind(TH2))-(L3.*sind(TH3)));
w3=(L2*w2*sind(TH2))./L3.*sind(TH3);
d2=(L2.*w2.*cosd(TH2))-L3.*w3.*cosd(TH3);
a3=((-L3.*w3.^2.*cosd(TH3))+(L2.*a2.*sind(TH2)))+(L2.*w2.^2.*cosd(TH2))./L3.*sind(TH3);
d3=(L2.*a2.*cosd(TH2))-(L2.*w2.^2*sind(TH2))-(L3.*a3.*cosd(TH3))+(L3.*w3.^2.*sind(TH3));
One caution
This statement:
w3=(L2*w2*sind(TH2))./L3.*sind(TH3);
is equivalent to:
w3=(L2*w2*sind(TH2)).*sind(TH3)./L3;
If you want the two terms in the denominator to be multiplied together before you do the division, you have to enclose the terms in paretheses:
w3=(L2*w2*sind(TH2))./(L3.*sind(TH3));
and for the others as well.
works perfectly! Thank you for explaining the error! I appreciate your help!

Sign in to comment.

More Answers (0)

Categories

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

Tags

Community Treasure Hunt

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

Start Hunting!