# How do I swap 2 rows of a cell array?

11 views (last 30 days)
Pietro Fedrizzi on 21 Oct 2021
Commented: dpb on 21 Oct 2021
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 on 21 Oct 2021
One way...
>> C=num2cell(randi(10,3,2))
C =
3×2 cell array
{} {}
{} {}
{} {}
>> C(2:3,:)=flipud(C(2:3,:))
C =
3×2 cell array
{} {}
{} {}
{} {}
>>
dpb on 21 Oct 2021
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...

Bruno Luong on 21 Oct 2021
C([2 3],:) = C([3 2],:);
Pietro Fedrizzi on 21 Oct 2021
Thanks!