How to Swap alternate rows of a column matrix

I have a arbitary column matrix. Please suggest how to swap alternate rows of the matrix? For example:
A = [r1; r2; r3; r4; r5; r6]
Assume even number of rows. Expected is
A= [r2; r1; r4; r3; r6; r5]

답변 (2개)

Andrei Bobrov
Andrei Bobrov 2016년 1월 28일

0 개 추천

n = size(A,1);
k = rem(n,2);
out = A(flipud(reshape(1:n-k,2,[])),:);
if k == 1, out = [out;A(end,:)]; end
Stephen23
Stephen23 2022년 4월 26일
편집: Stephen23 2022년 4월 26일
Simple approach using indexing (only works for matrices with an even-number of rows):
inp = randi(9,8,4)
inp = 8×4
7 2 2 5 9 6 5 8 9 1 6 5 1 7 7 4 6 7 8 4 7 3 1 8 3 5 5 7 2 9 1 1
out = inp([2:2:end;1:2:end],:)
out = 8×4
9 6 5 8 7 2 2 5 1 7 7 4 9 1 6 5 7 3 1 8 6 7 8 4 2 9 1 1 3 5 5 7

카테고리

도움말 센터File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

질문:

2016년 1월 28일

편집:

2022년 4월 26일

Community Treasure Hunt

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

Start Hunting!

Translated by