How do I flip the order of cells in a cell array?

조회 수: 44 (최근 30일)
JJH
JJH 2018년 12월 6일
편집: Stephen23 2018년 12월 7일
If I have a cell array with a single row of cells of different sizes, e.g
cellarray = {3x2 double} {4x2 double} {5x2 double}
how can I flip the order of the arrays in the cell without flipping the individual elements - the outcome I want is
cellarray = {5x2 double} {4x2 double} {3x2 double}
but no change to the actual matrices in each cell. I thought this was the fliplr command but this doesn't work.

답변 (2개)

Stephen23
Stephen23 2018년 12월 6일
편집: Stephen23 2018년 12월 6일
Simpler:
C(end:-1:1) = C(:)
or
C = flip(C)

madhan ravi
madhan ravi 2018년 12월 6일
편집: madhan ravi 2018년 12월 6일
However there are better solutions than this , try :
result=cell(1,numel(cellarray));
ctr=1;
for i =numel(cellarray):-1:1
result{ctr}=cellarray{i};
ctr=ctr+1;
end
result
  댓글 수: 11
JJH
JJH 2018년 12월 7일
I think there is something strange happening when the cell is created - if I add the commands
vecarray{kk} = vec
vec
vecarray{end}
I find that vecarray{kk} prints the cells in the order that I stated that I wanted to change in my first comment - so that the 3x2 element is first. If I then print vec directly after that in the same loop, I get a 5x2 matrix. If I print vecarray{end} I get a 3x2 matrix. I'm not sure how this can happen as it seems to have the same thing stored in the opposite order.
Stephen23
Stephen23 2018년 12월 7일
편집: Stephen23 2018년 12월 7일
"I think there is something strange happening when the cell is created "
There is nothing strange happening at all. MATLAB is doing exactly what you tell it to do. Just because you reverse the order which you put the values into the cells makes no difference to the indices that you are using. These two loops will create exactly the same arrays with the same data in the same locations:
C = nan(1,5);
for k = 5:-1:1 % assign in descending order
C(k) = k^2;
end
D = nan(1,5);
for k = 1:5 % assign in ascending order
D(k) = k^2;
end
Just because we define element 5 first, it does not somehow become that 1st element of the array. Nope. The 5th element is always the 5th element, which is fixed by the indexing, not by which one we define first. To allocate to a different element, you need to change the indexing (e.g. as madhan ravi showed you).
So your comparison:
vecarray{kk} = vec
vec
vecarray{end}
tells us nothing until you check what value kk has: is it the same as numel(vecarray) (equivalent to end when used as an index) ? Judging by your code the answer is "no". So do they refer to the same cell? (hint: "no")

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

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by