Reversing Columns in a Matrix

I need to reverse the order of specific columns in a vector. For example:
a = [1 2 3 4 5 6]
Reverse columns 2:5
a = [1 5 4 3 2 6]
How do I do this?

 Réponse acceptée

Sven
Sven le 19 Nov 2011

0 votes

Use fliplr to flip a matrix left-to-right:
a = [1 2 3 4 5 6]
b = [a(1) fliplr(a(2:5)) a(6)]
See also: flipud (flips it up-to-down) or flipdim (flips along a specified dimension).
(Edit based on your comments below)
So if you want to flip every permutation of elements (2:3, 2:4, 2:5, 2:6, 3:4, etc), then you can also use nchoosek as follows:
a = [1 2 3 4 5 6];
twoInds = nchoosek(1:length(a), 2);
numPerms = size(twoInds,1);
all_A = repmat(a, numPerms, 1);
for i = 1:numPerms
colNos = twoInds(i,1):twoInds(i,2);
all_A(i, colNos) = flipdim(a(colNos),2);
end
So now you have your original "a" variable, plus a matrix "all_A", where every row has a different piece of "a" flipped, left to right.
Was that what you were looking for?

3 commentaires

David
David le 19 Nov 2011
So how would I implement this if I need to run a test on all permutations of column flips? For example I need to run the test for columns 2:3, 2:4, 2:5, 2:6, 3:4, 3:5, etc. flipped.
Image Analyst
Image Analyst le 19 Nov 2011
Just use variables for the starting and stopping element. So as soon as you've generated a pair (let's call them s1 and s2) you'd do
b = [a(1:s1-1) fliplr(a(s1:s2)) a(s2+1:end)];
Sven
Sven le 19 Nov 2011
I've updated the answer based on this new request for what you want to do. Does it answer the question?

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Matrices and Arrays dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by