Search code examples
matlabcell-array

How to separate one cell element into two separate cell elements in MATLAB


I have a cell array which looks like this:

abc = {[1,0,1,0];[1,1,0,1];[1,1,1,0]};

I want to separate each cell element into two groups like this:

abc(:,2) = {[1,0];[1,1];[1,1]};
abc(:,3) = {[1,0];[0,1];[1,0]};

I tried using this statement to do it:

abc(:,2:3) = cellfun(@(x) mat2cell(x,[1],[2,2]),abc(:,1),'uni',0);

But this statement gives the following error:

Assignment has fewer non-singleton rhs dimensions than non-singleton subscripts

When I try to assign it to abc(:,2) instead of abc(:,2:3), I get the result but as a cell within a cell which is not my requirement.


Solution

  • You can't assign directly to columns 2:3 of abc because the output of cellfun doesn't match the expected dimension. It is 3 x 1 while abc(:,2;3) is 3 x 2. You can use call to cat to make it work though.

    abc = {[1,0,1,0];[1,1,0,1];[1,1,1,0]};
    
    tmp = cellfun(@(x) mat2cell(x,[1],[2,2]),abc(:,1),'uni',0);
    abc(:,2:3) = cat(1, tmp{:});
    
    %// [1x4 double]    [1x2 double]    [1x2 double]
    %// [1x4 double]    [1x2 double]    [1x2 double]
    %// [1x4 double]    [1x2 double]    [1x2 double]
    

    An alternative that doesn't use cellfun could be.

    abc = {[1,0,1,0];[1,1,0,1];[1,1,1,0]};
    
    abc(:,2:3) = mat2cell(cat(1, abc{:}), ones(1,size(abc,1)), [2 2]);