Search code examples
arraysmatlabindexingcell-array

Write array into cell


I've been using Matlab for quite awhile but this one has got me--I want a one-liner that will take an array and write it into the indexed entries of a cell, e.g.

>> c = cell(1,6);
>> b = [1 2 3];
>> c{[2 4 6]} = b; %This doesn't actually work
>> disp(c)

   []  [1]  []  [2]  []  [3]

I've tried all sorts of versions of this with num2cell, deal et al. but I can't find the magic bullet. Can it be done in a single assignment?


Solution

  • With mat2cell -

    c([2 4 6]) = mat2cell(b,1,ones(1,numel(b))); 
    

    With num2cell -

    c([2 4 6]) = num2cell(b);
    

    Output -

    >> disp(c)
        []    [1]    []    [2]    []    [3]