Patzerook
Patzerook

Reputation: 33

How to move a number of columns in a matrix to the right most in matlab

Suppose I have an mxn matrix A. Suppose I have a list (or a vector) P of i elements where each element of P indicates the number of a column in A. I need to move all the columns indicated by P to the right most of A; for instance the the columns indicated in the first and the i'th elements in P will become the (n-i)'th and the n'th column of A respectively.

Hope my statement is clear, let me know if there is any ambiguity. thanks.

Upvotes: 1

Views: 179

Answers (1)

Daniel
Daniel

Reputation: 36710

To get the columns 3,5,7 to the right, first c is constructed which indicates the new order of columns. Then the columns are indexed using c which reorders them.

>> M=magic(10);
>> c=[3,5,7];
>> c=[setdiff(1:size(M,2),c),c]

c =

  Columns 1 through 9

     1     2     4     6     8     9    10     3     5

  Column 10

     7

>> M=M(:,c);

Upvotes: 1

Related Questions