How to add tolerance to iteration with if statement

조회 수: 42 (최근 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 CenterFile Exchange에서 2-D and 3-D Plots에 대해 자세히 알아보기

제품


릴리스

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by