How do I flip the order of cells in a cell array?
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.
Answers (2)
Simpler:
C(end:-1:1) = C(:)
or
C = flip(C)
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
JJH
on 6 Dec 2018
madhan ravi
on 6 Dec 2018
can you upload your cellarray as a .mat file?
JJH
on 6 Dec 2018
madhan ravi
on 6 Dec 2018
Have no clue what you are talking about without knowing how the data is stored
JJH
on 6 Dec 2018
Guillaume
on 6 Dec 2018
Assuming what you want is exactly what you've described in the question, it's trivial to do. See Stephen's answer.
JJH
on 6 Dec 2018
"Well I thought it should be easy but it doesn't seem to work when I enter that."
Then most likely you did something wrong (or your original question does not explain the situation completely). Show us exactly what you tried that "does not seem to work".
Note that you should avoid using cd like that: it is slow and makes debugging harder. It is much better to use absolute/relative filenames.
JJH
on 7 Dec 2018
JJH
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")
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!