将单元格数组分成Matlab组

时间:2017-02-02 08:26:26

标签: matlab 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;

我需要根据第一列的矩阵等式对M的所有行进行分组。因此,有3个新的较小的单元阵列M1M2M3

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};

有什么方法可以做到?

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

% 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

这将产生一个单元格数组MM

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

其中MM{k}与您的Mk类似(例如MM(1)是您的M1)。除了作为解决此问题的更通用方法之外,最好将所有结果单元格数组包装在一个索引变量中,而不是在工作区中包含许多变量。

相关问题