Switching rows in matrix

조회 수: 92 (최근 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 CenterFile Exchange에서 Data Types에 대해 자세히 알아보기

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by