swap columns of a matrix

67 次查看(过去 30 天)
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?
  1 个评论
Keerthi Krishna PARVATHANENI
Easy way is to swap the coloums based on the positon
For example:
A=[10 20 30;
40 50 60];
swap the coloum 1 to 2 can be done by
A(:,[2 1 3])
ans =
20 10 30
50 40 60
Exact approach can be adopted ot swap rows
A([2 1],:)
ans =
40 50 60
10 20 30
I think, this can be easy way with minium code.
Enjoy :)

请先登录,再进行评论。

采纳的回答

Thomas
Thomas 2014-2-25
编辑:Thomas 2014-2-25
You could also use
out= fliplr(k_minus)

更多回答(2 个)

Mischa Kim
Mischa Kim 2014-2-25
编辑:Mischa Kim 2014-2-25
Use
k_minus_rev = k_minus(:, [length(k_minus(1,:)):-1:1])
  4 个评论
Jos (10584)
Jos (10584) 2014-2-25
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 2019-4-2
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.

请先登录,再进行评论。


rishabh gupta
rishabh gupta 2018-1-12
you can also use: k_minus_rev = k_minus(:, [length(k_minus):-1:1])
  2 个评论
Stephen23
Stephen23 2018-1-12
编辑:Stephen23 2018-1-12
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 2019-4-30
is it possible to do this with a loop?

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by