MATLAB Answers

flip certain columns in matrix

93 views (last 30 days)
john creighton
john creighton on 20 Oct 2014
Commented: Adam on 11 Dec 2017
hey all i need to flip every nth column in a matrix. ie. if i have matrix A=[1 2 3;4 5 6;7 8 9] i need it to become A=[1 8 3;4 5 6;7 2 9] any suggestions?

  0 Comments

Sign in to comment.

Accepted Answer

Adam
Adam on 20 Oct 2014
Edited: Adam on 20 Oct 2014
n = 2;
colIdx = 2:n:size(A,2);
A(:,colIdx) = flip( A(:,colIdx) )
assuming you want to flip even columns (in the case of n = 2). Obviously for odd colums just change the first line to:
colIdx = 1:n:size(A,2);

  1 Comment

john creighton
john creighton on 20 Oct 2014
Thanks Adam. works perfectly :)

Sign in to comment.

More Answers (1)

raja bala
raja bala on 10 Dec 2017
A(:,[2]) = flip (A(:,[2]))

  1 Comment

Adam
Adam on 11 Dec 2017
This flips the 2nd column only, as does
A(:,2) = flip (A(:,2))
without the square brackets.

Sign in to comment.

Sign in to answer this question.


Translated by