Reveresing the order of columns in an array
    7 views (last 30 days)
  
       Show older comments
    
Hi guys, 
I would like to write a code to reverse the columns order as in a following example: 
q=[1 2 3 4, 5 6 7 8, 9 10 11 12, 13 14 15 16, 17 18 19 20];
for example, the program randomly picks: 
i1=2
i2=4
so we want to rearrange the order of colums from the second till the forth one and as an output get 
qnew=[1 4 3 2, 5 8 7 6, 9 12 11 10, 13 16 15 14, 17 20 19 18]
0 Comments
Answers (3)
  Les Beckham
      
 on 17 May 2022
        
      Edited: Les Beckham
      
 on 17 May 2022
  
      % Note: use semicolons instead of commas for row breaks so you get 4 columns
q = [1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16; 17 18 19 20]
i1=2;
i2=4;
qnew = q;
qnew(:,i1) = q(:,i2);
qnew(:,i2) = q(:,i1);
disp(qnew)
0 Comments
  Bartosz Bagrowski
 on 17 May 2022
        1 Comment
  Les Beckham
      
 on 17 May 2022
				Well, that is a different question.  This q only has two columns.  It appears that now you want to swap the rows.
q=[1 2; 3 4; 5 6; 7 8; 9 10; 11 12]
i1=2;
i2=6;
qnew = q;
qnew(i1,:) = q(i2,:);
qnew(i2,:) = q(i1,:);
disp(qnew)
  Torsten
      
      
 on 17 May 2022
        A = [1 2; 3 4; 5 6; 7 8; 9 10; 11 12];
perm = [1 6 5 4 3 2];
A = A(perm,:)
0 Comments
See Also
Categories
				Find more on Matrices and Arrays in Help Center and File Exchange
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

