How do I flip the order of cells in a cell array?
33 views (last 30 days)
Show older comments
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.
0 Comments
Answers (2)
madhan ravi
on 6 Dec 2018
Edited: madhan ravi
on 6 Dec 2018
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 Comments
Stephen23
on 7 Dec 2018
Edited: Stephen23
on 7 Dec 2018
"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")
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!