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.)

1 件のコメント

JM
JM 2020 年 5 月 13 日
Thank you very much.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeSymbolic 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