How can I swap two columns of a matrix in MATLAB?
390 次查看(过去 30 天)
显示 更早的评论
How can I swap two columns of a matrix in MATLAB?
2 个评论
David Sinex
2022-10-3
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
2022-10-3
idx1 = 2;
idx2 = 5;
AA(:,[idx1,idx2]) = AA(:,[idx2,idx1]);
回答(1 个)
Manvi Goel
2019-6-6
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 个评论
Andrea
2023-2-25
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
2023-2-25
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" ?
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!