Why is my own echelon function printing incorrect matrix

1 回表示 (過去 30 日間)
Natalie Murawski
Natalie Murawski 2019 年 9 月 23 日
コメント済み: Natalie Murawski 2019 年 9 月 24 日
I am trying to create an echelon function, however, I am having trouble debugging my error. It works for almost all matrices but for the following matrix it gives an incorrect result:
A=[1 2 3 ; 1 2 4 ; 1 2 4]
echelon(A)
function x = echelon(A)
[m,n]= (size(A)); % m= rows , %n= columns
j=1;
i=1;
while( i <m )
for k=i+1:m
if (A(i,j)==0)
C = A(i,:); %Let C be the ith first row of the matrix
A(i,:)= A(i+1,:);%Exchange the row with the one below it
A(i+1,:) = C %Let C be the row that was above now (This code swaps rows)
end
if ~all(A(k,:)==0) %check to see if row of zeros or not
A(k,:)=A(k,:)-((A(k,j)/A(i,j))*A(i,:)) %zero out corresponding row
end
end
j=j+1;
i=i+1;
end
x=A
end
It gives the following incorrect result:
1 2 3
0 0 1
0 0 1
Also for the following matrix:
A=[1 2 3 ; 1 2 5]
gives the following incorrect result:
1 2 3
0 0 2
  2 件のコメント
James Tursa
James Tursa 2019 年 9 月 24 日
Are you trying to produce any row echelon form, or the reduced row echelon form?
Natalie Murawski
Natalie Murawski 2019 年 9 月 24 日
Just echelon form, not reduced echelon form, so just with 1 as pivots.

サインインしてコメントする。

採用された回答

James Tursa
James Tursa 2019 年 9 月 24 日
I haven't checked all of your code, but I assume this:
if ~all(A(k,:))==0 %check to see if row of zeros or not
was meant to be this instead:
if ~all(A(k,:)==0) %check to see if row of zeros or not
Also, you divide by A(i,j) before checking to see if it is 0.
  3 件のコメント
James Tursa
James Tursa 2019 年 9 月 24 日
編集済み: James Tursa 2019 年 9 月 24 日
Best way to debug at this point is to step through your code line by line and see what is happening to A at each step. Then you can easily find where that divide by 0 is happening and correct it. If you still have problems, post your current code and ask more questions.
What algorithm are you using to ensure you are not dividing by 0? Looks like you may need to rethink how you are doing your row swapping.
Natalie Murawski
Natalie Murawski 2019 年 9 月 24 日
Alright, thank you!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeGet Started with MATLAB についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by