将元胞数组分成组Matlab
divide cell array into groups Matlab
我有元胞数组:
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 个新的较小的元胞数组 M1
、M2
和 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};
可能的方法是什么?
您可以执行以下操作:
% 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
)。除了作为解决此问题的更通用方法之外,最好将所有结果元胞数组打包到一个索引变量中,而不是在工作区中包含许多变量。
我有元胞数组:
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 个新的较小的元胞数组 M1
、M2
和 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};
可能的方法是什么?
您可以执行以下操作:
% 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
)。除了作为解决此问题的更通用方法之外,最好将所有结果元胞数组打包到一个索引变量中,而不是在工作区中包含许多变量。