How to add tolerance to iteration with if statement

9 ビュー (過去 30 日間)
Bethany Sinclair
Bethany Sinclair 2022 年 10 月 27 日
回答済み: Chunru 2022 年 10 月 27 日
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);

採用された回答

Chunru
Chunru 2022 年 10 月 27 日
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);

その他の回答 (1 件)

Chunru
Chunru 2022 年 10 月 27 日
% 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 件のコメント
Chunru
Chunru 2022 年 10 月 27 日
Not sure what algo you want to implement. Can you describe it?
Bethany Sinclair
Bethany Sinclair 2022 年 10 月 27 日
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);

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

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

製品


リリース

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by