1

I'm looking for a quick, simple way of accessing specific arrays that are inside cell arrays. For example, let's say I have

A = rand(10,2);
B = rand(15,1);
C = rand(130,1);
D = rand(16,1);
E = rand(1000,25);
my_cell = {A,B,C,D,E};

Let's say I want the 1st, 2nd, and 4th matrices only (i.e., A, B and D) inside a new cell array. So the new cell array would be composed of {A, B, D}. This is obviously easy using a for loop:

idx=[1,2,4];
new_cell=cell(1,length(idx));
for i=1:length(idx)
   new_cell{i}=my_cell{idx(i)};
end

I was wondering if there was an even quicker/simpler way. Maybe there's an obivous indexing trick or function I'm not aware of? I'd appreciate the help.

0

2 Answers 2

3

Yes, you can index your cell array like a normal array (i.e. using parentheses instead of brackets). Actually, it is a "normal" array: it's a normal array of "cell" elements. So indexing them like a normal array simply returns the individual "cell elements" rather than their contents.

Therefore you can just do

my_cell(idx)


EDIT: Just to make the difference clear between "indexing a cell like an array" and "collecting the comma-separated-output into a new cell array" approaches:

>> my_cell = {'A','B','C'; 'D','E','F'; 'G', 'H', 'I'}    
my_cell = 
    'A'    'B'    'C'
    'D'    'E'    'F'
    'G'    'H'    'I'

>> my_cell(1:2,1:2)
ans = 
    'A'    'B'
    'D'    'E'

>> {my_cell{1:2,1:2}}  % this will ALWAYS be a horizontal cell vector
ans = 
    'A'    'D'    'B'    'E'
Sign up to request clarification or add additional context in comments.

1 Comment

Doesnt get simpler than this :) Thanks
1

{my_cell{idx}} should do the trick.

my_cell{idx} returns the elements in my_cell indexed by idx as a comma separated list. It is equivalent to A, B, D. All you need to do is to close this list with {} to make a cell array out of it.

2 Comments

note. this approach will not work if you wish to preserve structure. Change your original cell to my_cell = {A;B;C;D;E} and you'll see what I mean.
Awesome! Thanks for the heads up about the structure. I see what you mean.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.