How can I make this code like a cycle?

clc
clear all
%Data
v1=1;
x1=0;
v2=1;
E=10e-5;
b1=-0.3;
b2=-0.6;
%Process
P=4*v2*sin(x1); % I Evaluate all this piece of code until
Q=-4*v2*cos(x1)+(4*(v2^2));
J=[4*v2*cos(x1) 4*sin(x1); 4*v2*sin(x1) 8*v2-4*cos(x1)];
A=[b2-P;b1-Q];
B=inv(J)*A;
E1=B(1,:)
E2=B(2,:)
x1=x1+E1
v2=v2+E2 %this part is evaluated in if (Note that x1 and v2 have a new value)
if abs(E1)>E || abs(E2)>E
P=4*v2*sin(x1);
Q=-4*v2*cos(x1)+(4*(v2^2));
J=[4*v2*cos(x1) 4*sin(x1); 4*v2*sin(x1) 8*v2-4*cos(x1)];
A=[b2-P;b1-Q];
B=inv(J)*A;
E1=B(1,:) %(Note that E1 and E2 have a new value)
E2=B(2,:)
x1=x1+E1
v2=v2+E2 %(Note that x1 and v2 have a new value)
else
P=4*v2*sin(x1);
Q=-4*v2*cos(x1)+(4*(v2^2));
J=[4*v2*cos(x1) 4*sin(x1); 4*v2*sin(x1) 8*v2-4*cos(x1)];
A=[b2-P;b1-Q];
B=inv(J)*A;
E1=B(1,:) %(Note that E1 and E2 have a new value)
E2=B(2,:)
x1=x1+E1
v2=v2+E2 %(Note that x1 and v2 have a new value)
end
% x1,v2,E1 and E2 are the values that change but x1 and v2 intials are given first, i wish to make a cycle for each new value of
%variables mentioned, that is i want to make the process over and over again (evaluating the new values of the variables) until the
% condition abs(E1)>E || abs(E2)>E is false, as you can see i can only value until a certain point (only two times) i want the code until the
%conditon is false

 채택된 답변

Geoff Hayes
Geoff Hayes 2020년 5월 13일

1 개 추천

JM - perhaps you can just replace the if/else block with
maxIterations = 1000;
atIteration = 0;
while (abs(E1)>E || abs(E2)>E) && atIteration <= maxIterations
P=4*v2*sin(x1);
Q=-4*v2*cos(x1)+(4*(v2^2));
J=[4*v2*cos(x1) 4*sin(x1); 4*v2*sin(x1) 8*v2-4*cos(x1)];
A=[b2-P;b1-Q];
B=inv(J)*A;
E1=B(1,:) %(Note that E1 and E2 have a new value)
E2=B(2,:)
x1=x1+E1
v2=v2+E2 %(Note that x1 and v2 have a new value)
atIteration = atIteration + 1;
end
So the while loop would exit when both abs(E1) AND abs(E2) are less than E. (Or when the maximum number of iterations has been reached.)

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Symbolic Math Toolbox에 대해 자세히 알아보기

태그

질문:

JM
2020년 5월 13일

댓글:

JM
2020년 5월 13일

Community Treasure Hunt

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

Start Hunting!

Translated by