What is the difference between "while" and "for" in this program?
15 views (last 30 days)
Show older comments
ang ji
on 7 Nov 2019
Answered: JESUS DAVID ARIZA ROYETH
on 7 Nov 2019
This is a matlab program of column principal element Gauss elimination method:
function GEpiv(A,b)
[m,n]=size(A);
nb=n+1;
Ab=[A,b];
for i=1:m-1
[pivot,p]=max(abs(Ab(i:m,i)));
ip=p+i-1;
if ip ~=i
Ab([i ip],:)=Ab([ip i],:);
end
pivot=Ab(i,i);
for k=i+1:m
Ab(k,i:nb)=Ab(k,i:nb)-(Ab(k,i)/pivot)*Ab(i,i:nb);
end
end
x=zeros(n,1);
x(n)=Ab(n,nb)/Ab(n,n);
% for i=n-1:1
% x(i)=(Ab(i,nb)-Ab(i,i+1:n)*x(i+1:n,1))/Ab(i,i);
% end
while(i>=1)
x(i)=(Ab(i,nb)-Ab(i,i+1:n)*x(i+1:n,1))/Ab(i,i);
i=i-1;
end
for k=1:n
fprintf('x[%d] = %f\n',k,x(k));
end
A=[2,4,1;2,6,-1;1,5,2];
b=[4;10;2];
Run the program, I wii get

But if I use the for loop , I will get

I think the result should be the same,but in fact they are not,why?
0 Comments
Accepted Answer
JESUS DAVID ARIZA ROYETH
on 7 Nov 2019
correction and solution:
you should specify that the for goes in the opposite direction
for i=n-1:-1:1
x(i)=(Ab(i,nb)-Ab(i,i+1:n)*x(i+1:n,1))/Ab(i,i);
end
0 Comments
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!