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

18 vues (au cours des 30 derniers jours)
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?

Réponse acceptée

JESUS DAVID ARIZA ROYETH
JESUS DAVID ARIZA ROYETH le 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

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by