MATLAB Answers

swap columns of a matrix

조회 수: 113(최근 30일)
Rasmus
Rasmus 25 Feb 2014
Commented: Helen Joan 30 Apr 2019
Hello guys/girls
How do i swap columns??
I have this
k_minus =
-46 -43 -26 -14 7 19 11 32 39 45 45
0 -4 -7 -7 -44 -44 -7 -7 -15 -15 0
and I want the columns to be in opposite order - How do I do this? and can do this in one go?

  댓글 수: 0

로그인 to comment.

채택된 답변

Thomas
Thomas 25 Feb 2014
Thomas 님이 편집함. 25 Feb 2014
You could also use
out= fliplr(k_minus)

  댓글 수: 1

Rasmus
Rasmus 25 Feb 2014
That is actually easier! :)

로그인 to comment.

More Answers (2)

Mischa Kim
Mischa Kim 25 Feb 2014
Mischa Kim 님이 편집함. 25 Feb 2014
Use
k_minus_rev = k_minus(:, [length(k_minus(1,:)):-1:1])

  댓글 수: 4

표시 이전 댓글 수: 1
Mischa Kim
Mischa Kim 25 Feb 2014
Basically, when you do
k_minus(:,1)
you extract the sub-matrix consisting of all rows in the first column. With
k_minus(:,[2,1])
you extract all rows of the second, and the first columns, in that order. You can now generalize the last bit
[length(k_minus(1,:)):-1:1]
to extract all columns ( length(k_minus(1,:)) ), placing the last column first, and the first column last, in descending order ( -1 ).
Jos (10584)
Jos (10584) 25 Feb 2014
You do not need the length statement by using the keyword END:
MyMatrix_withReversedColumns = MyMatrix(:,end:-1:1)
but I do suggest you stick to FLIPLR. It is the same, but much easier to read!
kk
kk 2 Apr 2019
Thank you for this answer! It has helped me "merge" two matrices, i.e. creating a matrix consisting of the first column of matrix A, first column of matrix B, second column of matrix A, second column of matrix B, etc.

로그인 to comment.


rishabh gupta
rishabh gupta 12 Jan 2018
you can also use: k_minus_rev = k_minus(:, [length(k_minus):-1:1])

  댓글 수: 2

Stephen Cobeldick
Stephen Cobeldick 12 Jan 2018
The square brackets are totally superfluous, and using end is simpler than using length (of course length should be avoided generally because its output changes depending on the input array size: better to use numel or size with a specific dimension).
So a better (simpler, clearer, less buggy) is exactly as Jos already gave four years ago:
k_minus(:,end:-1:1)
Helen Joan
Helen Joan 30 Apr 2019
is it possible to do this with a loop?

로그인 to comment.

이 질문에 답변하려면 로그인을(를) 수행하십시오.


Translated by