How to add tolerance to iteration with if statement

41 vues (au cours des 30 derniers jours)
Bethany Sinclair
Bethany Sinclair le 27 Oct 2022
Réponse apportée : Chunru le 27 Oct 2022
I have a Gauss-seidel iteration code, which works to 99 iterations with a relaxation factor. However, when I put an if statement in (no other changes), to say if the different between iteration a^x+1-a^x is less than a certain tolerance say 0.1 then stop the iteration sequence before the specified 99 iterations.
Any help to spot any issues would be appreciated!
a2(1,1)=0;
b2(1,1)=0;
c2(1,1)=0;
R2=0.3;
for i=1:99
if a2(i+1,1)-a2(i,1)<0.1
a2(i+1,1)=(1-R2)*a2(i,1)+R2*(4-b2(i,1)-c2(i,1));
b2(i+1,1)=(1-R2)*b2(i,1)+R2*(2*a2(i+1,1)+4*c2(i,1)-33)/3;
c2(i+1,1)=(1-R2)*c2(i,1)+R2*(3*a2(i+1,1)-2*b2(i+1,1)-2)/2;
end
end
figure(5);
plot(a1);
hold on
plot (b1);
plot (c1);

Réponse acceptée

Chunru
Chunru le 27 Oct 2022
x(1,1)=0; %Initial guess, x=0
y(1,1)=0; %Initial guess, y=0
z(1,1)=0; %Initial guess, z=0
R=0.3; %relaxation factor
for i=1:99 %99 is the number of iterations
x(i+1,1)=(1-R)*x(i,1)+R*(4-y(i,1)-z(i,1)); %what multiplied with R is the "new" x value produced by the equation
y(i+1,1)=(1-R)*y(i,1)+R*(2*x(i,1)+4*z(i,1)-33)/3; %what multiplied with R is the "new" y value produced by the equation
z(i+1,1)=(1-R)*z(i,1)+R*(3*x(i,1)-2*y(i,1)-2)/2; %what multiplied with R is the "new" z value produced by the equation
if abs(x(i+1)-x(i)) < 0.1
break
end
end
plot(x);
hold on
plot(y);
plot(z);

Plus de réponses (1)

Chunru
Chunru le 27 Oct 2022
% if a2(i+1,1)-a2(i,1)<0.1
% change the above to:
if abs(a2(i+1,1)-a2(i,1))<0.1
  3 commentaires
Chunru
Chunru le 27 Oct 2022
Not sure what algo you want to implement. Can you describe it?
Bethany Sinclair
Bethany Sinclair le 27 Oct 2022
Below is a code for iteration to find 3 values of a simulteneous equation to 99 iterations. I want to be able to stop the iteration algorithm early (before the 99 iterations are up) if the results fal within a certain tolerance. I.e - the result for A is within 0.1 of the previous iteration. The code below works, it just doesn't like it when I put the if statement in?
x(1,1)=0; %Initial guess, x=0
y(1,1)=0; %Initial guess, y=0
z(1,1)=0; %Initial guess, z=0
R=0.3; %relaxation factor
for i=1:99 %99 is the number of iterations
x(i+1,1)=(1-R)*x(i,1)+R*(4-y(i,1)-z(i,1)); %what multiplied with R is the "new" x value produced by the equation
y(i+1,1)=(1-R)*y(i,1)+R*(2*x(i,1)+4*z(i,1)-33)/3; %what multiplied with R is the "new" y value produced by the equation
z(i+1,1)=(1-R)*z(i,1)+R*(3*x(i,1)-2*y(i,1)-2)/2; %what multiplied with R is the "new" z value produced by the equation
end
plot(x);
hold on
plot(y);
plot(z);

Connectez-vous pour commenter.

Catégories

En savoir plus sur 2-D and 3-D Plots dans Help Center et File Exchange

Produits


Version

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by