What is the difference between "while" and "for" in this program?

조회 수: 16 (최근 30일)
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?

채택된 답변

JESUS DAVID ARIZA ROYETH
JESUS DAVID ARIZA ROYETH 2019년 11월 7일
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개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by