How can I make this code like a cycle?

4 visualizaciones (últimos 30 días)
JM
JM el 13 de Mayo de 2020
Comentada: JM el 13 de Mayo de 2020
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

Respuesta aceptada

Geoff Hayes
Geoff Hayes el 13 de Mayo de 2020
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.)

Más respuestas (0)

Categorías

Más información sobre Programming en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by