Switching rows in matrix

92 vues (au cours des 30 derniers jours)
Rachel McMurphy
Rachel McMurphy le 3 Déc 2019
Modifié(e) : cater re le 4 Déc 2019
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

Réponses (1)

cater re
cater re le 4 Déc 2019
Modifié(e) : cater re le 4 Déc 2019
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

Catégories

En savoir plus sur Data Types dans Help Center et File Exchange

Produits


Version

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by