MATLAB Answers

swapping rows in a matrix

9 views (last 30 days)
How can i create a matrix which is a copy of an other matrix except 2 rows have to swap.
for example 4*4nmatrix called M how can i create an new matrix which is a copy of M, but the first and the third row are swapped

  0 Comments

Sign in to comment.

Accepted Answer

Stephen Cobeldick
Stephen Cobeldick on 26 Nov 2019
>> X = [1,3]; % rows to swap
>> M = randi(9,4,5)
M =
6 7 6 2 9
2 3 2 1 1
1 6 9 7 9
4 6 7 5 2
>> W = M;
>> W(X,:) = W(X([2,1]),:)
W =
1 6 9 7 9
2 3 2 1 1
6 7 6 2 9
4 6 7 5 2

  1 Comment

Adam Danz
Adam Danz on 26 Nov 2019
+1 simple & neat

Sign in to comment.

More Answers (0)

Sign in to answer this question.