Search code examples
matlabcell-array

divide cell array into groups Matlab


I have cell array:

M = cell(5,3);

M{1,1} = ['+' '-' '-'; '+' '+' '+'; '-' '-' '+'];
M{2,1} = ['+' '-' '-'; '+' '+' '+'; '+' '+' '+'];
M{3,1} = ['+' '-' '-'; '+' '+' '+'; '+' '+' '+'];
M{4,1} = ['+' '-' '-'; '+' '+' '+'; '-' '-' '+'];
M{5,1} = ['+' '-' '-'; '-' '+' '-'; '-' '-' '+'];

M{1,2} = ['+' '0' '-'; '+' '+' '+'; '-' '-' '+'];
M{2,2} = ['+' '0' '-'; '+' '+' '+'; '0' '+' '+'];
M{3,2} = ['+' '0' '-'; '0' '+' '+'; '+' '+' '+'];
M{4,2} = ['+' '-' '-'; '+' '+' '+'; '0' '-' '+'];
M{5,2} = ['+' '-' '-'; '-' '0' '-'; '0' '-' '+'];

M{1,3} = 1;
M{2,3} = 3;
M{3,3} = 7;
M{4,3} = 25;
M{5,3} = 33;

I need to group all rows of M according to equality of matrices from first column. So have 3 new smaller cell arrays M1,M2 and M3:

M1{1,1} = M{1,1};
M1{2,1} = M{4,1};
M1{1,2} = M{1,2};
M1{2,2} = M{4,2};
M1{1,3} = M{1,3};
M1{2,3} = M{4,3};

M2{1,1} = M{2,1};
M2{2,1} = M{3,1};
M2{1,2} = M{2,2};
M2{2,2} = M{3,2};
M2{1,3} = M{2,3};
M2{2,3} = M{3,3};


M3{1,1} = M{5,1};
M3{1,2} = M{5,2};
M3{1,3} = M{5,3};

What is possible way to do it?


Solution

  • You can do the following:

    % collect all different strings from the first column in M:
    str = cellfun(@(x) x(:).', M(:,1),'UniformOutput',false);
    % find all unique strings, and their indecies:
    [ustr,~,ic] = unique(str);
    % initialize new cell array:
    MM = cell(numel(ustr),1);
    % fill the new array by the corresponding rows in M for each unique string
    for k = 1:numel(ustr)
        MM(k) = {M(ic==k,:)};
    end
    

    This will result in a cell array MM:

    MM = 
        {2x3 cell}
        {2x3 cell}
        {1x3 cell}
    

    where MM{k} is like your Mk (e.g. MM(1) is your M1). Apart from being a more general way to solve this problem, it is better to pack all the resultant cell arrays in one indexed variable, instead of having many variables in your workspace.