Switching rows in matrix

88 ビュー (過去 30 日間)
Rachel McMurphy
Rachel McMurphy 2019 年 12 月 3 日
編集済み: cater re 2019 年 12 月 4 日
First off, here is the code I have:
function m = move(M,i,j)
[x, y] = size(M); %n is rows and m is columns
submatrix = M([i:x],[1:y]); %creates submatrix of ith row down
column_j = submatrix(:,j); %gives jth column
row = find(column_j,1); %gives row number of first nonzero
i = M(i,:); %gives ith row of M
k = M(row+1,:); %gives row that has nonzero in M
M([i k],:) = M([k i],:)
end
For reference, all the little steps are required to show in my assignment and I've done my best to explain what their outputs are. For matrix
M = [1 3 2 -4 1 10 -3;0 0 0 -2 0 4 0;0 0 0 -4 1 7 -2;0 0 -3 6 -2 -10 4];
I have to find the submatrix of M from ith row down and the subcolumn of choice (lines 3 and 4), find the row number (line 5), and then take that specific row (which I got in line 7) and switch it with the ith row. So by doing:
move(M,2,3)
with the above matrix, the output should be
M =[1 3 2 -4 1 10 -3;0 0 -3 6 -2 -10 4;0 0 0 -4 1 7 -2;0 0 0 -2 0 4 0]
but my last step (line 8) which should switch the rows is bringing up an error. If anything is confusing, please let me know, I can try to explain the assignment as best as I can

回答 (1 件)

cater re
cater re 2019 年 12 月 4 日
編集済み: cater re 2019 年 12 月 4 日
Error is erased, but you need to fix this code. The code don't make result to your intend.
M = [1 3 2 -4 1 10 -3;0 0 0 -2 0 4 0;0 0 0 -4 1 7 -2;0 0 -3 6 -2 -10 4];
i=2
j=3
[x, y] = size(M); %n is rows and m is columns
submatrix = M([i:x],[1:y]); %creates submatrix of ith row down
column_j = submatrix(:,j); %gives jth column
row = find(column_j,1); %gives row number of first nonzero
l = M(i,:); %gives ith row of M
k = M(row+1,:); %gives row that has nonzero in M
M(i,:) = k
M(j,:) = l
switching:
M = [1 3 2 -4 1 10 -3; 0 0 0 -2 0 4 0 ; 0 0 0 -4 1 7 -2 ; 0 0 -3 6 -2 -10 4];
i=2
j=4
temp = M(j,:)
M(j,:) = M(i,:)
M(i,:) = temp

カテゴリ

Help Center および File ExchangeData Types についてさらに検索

製品


リリース

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by