How do I swap 2 rows of a cell array?

조회 수: 30 (최근 30일)
Pietro Fedrizzi
Pietro Fedrizzi 2021년 10월 21일
댓글: dpb 2021년 10월 21일
I have a 3x2 cell array and I need to swap row 2 and row 3. How can I solve this simple problem? Is there a function to do so that I don't know?

채택된 답변

dpb
dpb 2021년 10월 21일
One way...
>> C=num2cell(randi(10,3,2))
C =
3×2 cell array
{[5]} {[1]}
{[9]} {[5]}
{[6]} {[5]}
>> C(2:3,:)=flipud(C(2:3,:))
C =
3×2 cell array
{[5]} {[1]}
{[6]} {[5]}
{[9]} {[5]}
>>
  댓글 수: 7
Bruno Luong
Bruno Luong 2021년 10월 21일
"Change the indices to 2 and 4 (presuming at least four rows in the array, of course) and they don't do the same thing at all."
??? I just don't know what your are trying to say here. They do the same thing to my book
C=num2cell(randi(10,5,2))
C = 5×2 cell array
{[ 1]} {[6]} {[ 1]} {[4]} {[ 6]} {[2]} {[ 3]} {[8]} {[10]} {[4]}
Corg = C;
% dpb method
C([2 4],:)=flipud(C([2 4],:))
C = 5×2 cell array
{[ 1]} {[6]} {[ 3]} {[8]} {[ 6]} {[2]} {[ 1]} {[4]} {[10]} {[4]}
C=Corg;
% Bruno method
C([2 4],:)=C([4 2],:)
C = 5×2 cell array
{[ 1]} {[6]} {[ 3]} {[8]} {[ 6]} {[2]} {[ 1]} {[4]} {[10]} {[4]}
dpb
dpb 2021년 10월 21일
You wrote above
% dpb method
C([2 4],:)=flipud(C([2 4],:))
but that is NOT the code I wrote; you elided the colon that selects contiguous rows.
What I actually wrote in the original answer was
C([2:3],:)=flipud(C([2:3],:));
So, when change the 3 to a 4 one will get 3 rows instead of just two because I assumed (given the OP's example) there could be a more general case of wanting more than just two rows.
You just missed seeing the other colon, Bruno...

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

추가 답변 (1개)

Bruno Luong
Bruno Luong 2021년 10월 21일
C([2 3],:) = C([3 2],:);

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by