How can I swap two columns of a matrix in MATLAB?
Mostra commenti meno recenti
How can I swap two columns of a matrix in MATLAB?
2 Commenti
David Sinex
il 3 Ott 2022
In a single line using fliplr() and given 2 indices idx1 & idx2,
idx1 = 2;
idx2 = 5;
AA(:,[idx1,idx2]) = fliplr(AA(:,[idx1,idx2]));
Walter Roberson
il 3 Ott 2022
idx1 = 2;
idx2 = 5;
AA(:,[idx1,idx2]) = AA(:,[idx2,idx1]);
Risposte (1)
Manvi Goel
il 6 Giu 2019
There is an easy way to extract a column of a matrix in MATLAB
Suppose you have a matrix A:
A = [1, 2, 3 ; 4, 5, 6]

and you want to swap its first and the second columns.
The following can be done by extracting the first column, storing its value in a temporary variable and replacing second's value with the stored value:
v = A(:, 1);
A(:, 1) = A(:, 2);
A(:, 2) = v;

5 Commenti
Star Strider
il 6 Giu 2019
You can actually do that in one line:
A = [1, 2, 3 ; 4, 5, 6]
A = A(:,[2 1 3])
such that:
A =
1 2 3
4 5 6
A =
2 1 3
5 4 6
Steven Lord
il 6 Giu 2019
There's a different way to do it in one line, though I'm going to split it across two lines to avoid duplicating the vector listing the columns to swap.
A = [1, 2, 3 ; 4, 5, 6]
% Two lines
v = [1 2];
A(:, v) = A(:, flip(v))
% One line
A(:, [1 2]) = A(:, [2 1]) % or
A(:, [1 2]) = A(:, flip([1 2]))
Sterling Baird
il 28 Lug 2021
Modificato: Sterling Baird
il 28 Lug 2021
You can also use A = fliplr(A) if there are only two columns
Andrea
il 25 Feb 2023
thanks! helped me as well. I hoped to take the product between the original matrix and a simple binary matrix which would perform the transformation but in my case the matrix is text cell so linear algebra operations are not possible (unless I am missing something)
Walter Roberson
il 25 Feb 2023
It is not clear what 0 or false times a text entry would be ? Are you hoping, for example, that
false * "hello"
would give a result of "0" ?
Categorie
Scopri di più su Creating and Concatenating Matrices in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!