What is the difference between "while" and "for" in this program?
15 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
ang ji
el 7 de Nov. de 2019
Respondida: JESUS DAVID ARIZA ROYETH
el 7 de Nov. de 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 comentarios
Respuesta aceptada
JESUS DAVID ARIZA ROYETH
el 7 de Nov. de 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 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!