Reveresing the order of columns in an array

조회 수: 2 (최근 30일)
Bartosz Bagrowski
Bartosz Bagrowski 2022년 5월 17일
답변: Torsten 2022년 5월 17일
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]

답변 (3개)

Les Beckham
Les Beckham 2022년 5월 17일
편집: Les Beckham 2022년 5월 17일
% 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]
q = 5×4
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)
1 4 3 2 5 8 7 6 9 12 11 10 13 16 15 14 17 20 19 18

Bartosz Bagrowski
Bartosz Bagrowski 2022년 5월 17일
I meant changing the order of the columns in such a way:
q=[1 2; 3 4; 5 6; 7 8; 9 10; 11 12]
i1=2
i2=6
qnew=[1 2; 11 12; 9 10; 7 8; 5 6; 3 4]
so we reverse the order of columns from the second one till the sixth one
  댓글 수: 1
Les Beckham
Les Beckham 2022년 5월 17일
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]
q = 6×2
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)
1 2 11 12 5 6 7 8 9 10 3 4

댓글을 달려면 로그인하십시오.


Torsten
Torsten 2022년 5월 17일
A = [1 2; 3 4; 5 6; 7 8; 9 10; 11 12];
perm = [1 6 5 4 3 2];
A = A(perm,:)

카테고리

Help CenterFile Exchange에서 Multidimensional Arrays에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by