How to add tolerance to iteration with if statement
8 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Bethany Sinclair
am 27 Okt. 2022
Beantwortet: Chunru
am 27 Okt. 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);
0 Kommentare
Akzeptierte Antwort
Chunru
am 27 Okt. 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);
0 Kommentare
Weitere Antworten (1)
Chunru
am 27 Okt. 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 Kommentare
Siehe auch
Kategorien
Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
