What is the difference between "while" and "for" in this program?
15 ビュー (過去 30 日間)
古いコメントを表示
ang ji
2019 年 11 月 7 日
回答済み: JESUS DAVID ARIZA ROYETH
2019 年 11 月 7 日
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 件のコメント
採用された回答
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 件のコメント
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!