Solving Matrix. Correct code provided. While Loop Error not ending correctly
1 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
Walter Roberson
2020-2-25
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 个评论
Walter Roberson
2020-2-25
编辑:Walter Roberson
2020-2-25
Use || instead of && to cause it to continue if any of the tolerances have not been met.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Linear Algebra 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!