How to switch two row of matrix? For example: matrix A is: 1 3 4; 2 4 5 and Y want to be 2 4 5; 1 3 4 ?

3 Kommentare

Nikhil Sachan
Nikhil Sachan am 1 Feb. 2019
temp=A(2,:);
A(1,:)=A(2,:);
A(2,:)=temp;
%this will swap required rows
madhan ravi
madhan ravi am 21 Feb. 2019
Bearbeitet: madhan ravi am 21 Feb. 2019
A more efficient answer had been accepted 5 years ago.
Tristan McRae
Tristan McRae am 22 Feb. 2019
omg savage

Melden Sie sich an, um zu kommentieren.

 Akzeptierte Antwort

Azzi Abdelmalek
Azzi Abdelmalek am 5 Okt. 2013
Bearbeitet: Azzi Abdelmalek am 5 Okt. 2013

28 Stimmen

A=[1 3 4; 2 4 5]
A([1 2],:)=A([2 1],:)

3 Kommentare

Evil Meet
Evil Meet am 27 Okt. 2020
Thank you very much. U r awesome
Kevin Moss
Kevin Moss am 12 Jun. 2021
can anyone explain the logic behind why/how this works?
this works pretty clear
we take first and second all the row and make it equal to second and first all the row
for example, if you wanted to switch the third and the first row, you should type like this:
A([1 3], :) = A([3 1], :)
where ':' at second place stands for taking all the columns and '[1 3]' stands for first and third row

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Pontus Vikstål
Pontus Vikstål am 12 Aug. 2019
Bearbeitet: Pontus Vikstål am 12 Aug. 2019

1 Stimme

This way might be even faster.
A = [1 3 4; 2 4 5]
x = [0 1;1 0];
A = x*A
Then there's also this way
A = [1 3 4; 2 4 5]
A = flip(A)

2 Kommentare

madhan ravi
madhan ravi am 25 Jul. 2020
If A has more than two rows this won’t work.
Luis Mendez Lopez
Luis Mendez Lopez am 22 Sep. 2020
Yeah i will do that with my 600*600 matrix

Melden Sie sich an, um zu kommentieren.

Kategorien

Community Treasure Hunt

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

Start Hunting!

Translated by