2

Lets suppose we have a structure v which has variable number of elements in its objects

>> v(1).a = 1:10;
>> v(2).a = 1:20;
>> v(3).a = 1:30;

Now if we want to put it into a cell array we can simply concatenate and we will have a a with 3 cells with in

>> c = {v(1).a,v(2).a,v(3).a}

c = 

    [1x10 double]    [1x20 double]    [1x30 double]

and we can access any element within cell by using

c{i}(j)

but now for example if i have to fill the same array dynamically in a for loop

c = v(1).a
for i= 2:numel(v)
    c= {c ,v(i).a};
end

for the first 2 iterations it works in the same way as c = {v(1).a,v(2).a}

c = 

[1x10 double]    [1x20 double]

but after the 3rd iteration it converts the first two array into a cell with a cell

c = 

{1x2 cell}    [1x30 double]

how can avoid this ? and create a cell of array instead, like the first case, using a for loop

2 Answers 2

3

Try creating c as a cell array and then appending cell arrays to it:

c = {v(1).a}
for i = 2:numel(v)
    c = [c, {v(i).a}];
end

or with a simpler initialisation:

c = {};
for i = 1:numel(v)
    c = [c , {v(i).a}];
end

However, you can do it much more simply with a one-liner:

c = { v.a }

This last solution is a MATLAB "comma-separated list" and is a convenient way to build arrays and cell arrays. If you type v.a at the command line you'll see you get three answers returned (namely v(1).a, v(2).a, v(3).a). By writing { v.a } it's equivalent to writing those three answers, separated by commas, i.e. equivalent to {v(1).a, v(2).a, v(3).a}.

1
  • Yes i could but actually i am using this in a call back function , each time the call back function is called it adds a new cell , but your first 2 solutions solve my problem Commented May 31, 2016 at 11:10
1

I would recommend this approach:

c = {};
for i = 1:numel(v)
    c{end+1} = v(i).a;
end

or

c = {};
for i = 1:numel(v)
    c(end+1) = {v(i).a};
end

which I suspect (based on this answer) will be faster than the concatenation approach proposed by Justin.

3
  • Dan makes a good point. For a large number of elements this is the way to go, otherwise you may create a new c each time, rather than just appending..
    – Jetpac
    Commented May 31, 2016 at 11:18
  • I just ran your and justins approach using a timer and your one is faster even for just appending3 elements, i agree with Justin that for a large array this is definetely the way to go Commented May 31, 2016 at 11:24
  • 1
    @Umar I would argue for the readability of this approach as well and also it will work weather c is a column or a row matrix where the concatenation approach would require , changed to a ;
    – Dan
    Commented May 31, 2016 at 11:25

Not the answer you're looking for? Browse other questions tagged or ask your own question.