Problem with iterating loop again if output is less than some fixed value
Infos
Cette question est clôturée. Rouvrir pour modifier ou répondre.
Afficher commentaires plus anciens
Hi,
I am trying to calculate theta1, theta2 and r using following equations.
N=100;
for j=2:N
t(j)=t(j-1)+dt; %theta1, theta2 and r do not depend on time explicitly.
k=0.95;% input parameter
theta1(j)=theta1(j-1)+dt*k*(sin(theta2(j-1)-theta1(j-1))));
theta2(j)=theta2(j-1)+dt*k*(sin(theta1(j-1)-theta2(j-1))));
r(j)=Equation that depends on theta1 and theta2
At the middle of iteration if the value of r goes below some value say 0.5 then I want to use higher value of k(>0.95) and recalculate from the beginning using same equations given above.
I will be thankful for your help. Dharma
Réponses (1)
Walter Roberson
le 7 Mar 2018
k = 0.95;
N = 100;
while true
did_all = true;
for j = 2 : N
t(j)=t(j-1)+dt; %theta1, theta2 and r do not depend on time explicitly.
theta1(j)=theta1(j-1)+dt*k*(sin(theta2(j-1)-theta1(j-1))));
theta2(j)=theta2(j-1)+dt*k*(sin(theta1(j-1)-theta2(j-1))));
r(j)=Equation that depends on theta1 and theta2
if r(j) < 0.5;
did_all = false;
break;
end
end
if did_all; break; end
k = k + 0.05;
end
8 commentaires
Dharma
le 10 Mar 2018
Walter Roberson
le 11 Mar 2018
" Is it feasible to iterate r (j) with higher value of k sometimes (if r (j)<0.4) and then using previously used lower value of k in above code?"
No, you defined that k had to be increased if r(j) < 0.5, which contradicts using a lower value for k for r(j) > 0.4 over the range 0.4 to 0.5 . You cannot have a range over which k both needs to be increased but also needs to not be increased.
Dharma
le 13 Mar 2018
Walter Roberson
le 13 Mar 2018
k = 0.95;
N = 100;
while true
mama_bear = false;
papa_bear = false;
for j = 2 : N
t(j)=t(j-1)+dt; %theta1, theta2 and r do not depend on time explicitly.
theta1(j)=theta1(j-1)+dt*k*(sin(theta2(j-1)-theta1(j-1))));
theta2(j)=theta2(j-1)+dt*k*(sin(theta1(j-1)-theta2(j-1))));
r(j)=Equation that depends on theta1 and theta2
if r(j) < 0.4;
mama_bear = true;
break;
end
if r(j) > 0.8
papa_bear = true;
break;
end
end
if mama_bear
k = k + 0.05; %it was too soft
elseif papa_bear
k = k - 0.05; %it was too hard
else
break; %it was just right
end
end
Dharma
le 15 Mar 2018
Walter Roberson
le 15 Mar 2018
"Are they closing same 'for loop' independently?"
Yes.
You could also code
mama_bear = r(j) < 0.4;
papa_bear = r(j) > 0.8;
if mama_bear || papa_bear; break; end
Dharma
le 21 Mar 2018
Dharma
le 21 Mar 2018
Cette question est clôturée.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!