Solving Matrix. Correct code provided. While Loop Error not ending correctly

2 visualizaciones (últimos 30 días)
I attempting to solve this system using Gauss Sidell. I believe all my equations are correct, but the last error displayed is incorrect. It is supposed to be below 5% as specified for es.
MATLAB CODE:
function Untitled5(a,b,lamda,es) %For 3X3 Matrix
%02/25/20 William D.
%GaussSeidel Method: Problem 11.8
a=[0.8,-0.4,0;-0.4,0.8,-0.4;0,-0.4,0.8];
b=[41;25;105];
lamda=1.2; %-> Correction Factor
es=5;
n=length(b); %Find largest dimension of vector b
iter=1;
itermax=1000; %Max number iterations
ea1=10; %initialize error values
ea2=10;
ea3=10;
x1=0; %Initival guesses for x values
x2=0;
x3=0;
while (es<ea1) && (es<ea2) && (es<ea3) && (iter<itermax)
x1_old=x1; %replace new values calculated as old
x2_old=x2;
x3_old=x2;
x1=(b(1)-a(1,2)*x2-a(1,3)*x3)/a(1,1); %Solve for new x1 value
x1=lamda*x1+(1-lamda)*x1_old; %Correct x1 value, Enhances Convergence
x2=(b(2)-a(2,1)*x1-a(2,3)*x3)/a(2,2); %Solve for new x2 value
x2=lamda*x2+(1-lamda)*x2_old;
x3=(b(3)-a(3,1)*x1-a(3,2)*x2)/a(3,3);%Solve for new x3 value
x3=lamda*x3+(1-lamda)*x3_old; %Correct x3 value, enhance Convergence
ea1=abs((x1-x1_old)*100/x1); %Find approx. errors
ea2=abs((x2-x2_old)*100/x2);
ea3=abs((x3-x3_old)*100/x3);
iter=iter+1; %Increase Iteration Counter
end
fprintf('Error Values:') %Display Final Error Values
disp(ea1)
disp(ea2)
disp(ea3)
fprintf('X values') %Display Final X Values
disp(x1)
disp(x2)
disp(x3)
%Nobody Cares, Work Harder
%Keep Hammering
end
DISPLAY:
>> Untitled5
Error Values: 9.8347 <-----------SHOULD BE BELOW 5 LIKE THE REST.. /////////////////////////////////////////////////////////////////////
1.5494
3.1399
X values 180.6203
256.7983
261.0151

Respuesta aceptada

Walter Roberson
Walter Roberson el 25 de Feb. de 2020
No it should not be. Your while uses && between the parts. The && operator is only true if both sides are true. With your code as soon as the second test, ea2, does not pass the test, then the test becomes false and the loop exists even though the first part was true.
Your code is designed to exit the loop as soon as one or more of the values are within tolerance. This was deliberate on your part.
  2 comentarios
N/A
N/A el 25 de Feb. de 2020
Editada: N/A el 25 de Feb. de 2020
Okay, do you have any recommendations on what I should do to make sure all 3 es<ea# are satisfied. I would like it to stop when all ea# becomes less than es and iter is still less than itermax. Sorry, I know this is probably a dumb question.
Walter Roberson
Walter Roberson el 25 de Feb. de 2020
Editada: Walter Roberson el 25 de Feb. de 2020
Use || instead of && to cause it to continue if any of the tolerances have not been met.

Iniciar sesión para comentar.

Más respuestas (0)

Community Treasure Hunt

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

Start Hunting!

Translated by