Matlab:select来自矩阵的子矩阵

Matlab: select submatrix from matrix by certain criteria

我有一个矩阵A

A=[f magic(10)]
    A=

931142103          92          99           1           8          15          67          74          51          58          40
931142103          98          80           7          14          16          73          55          57          64          41
931142103           4          81          88          20          22          54          56          63          70          47
459200101          85          87          19          21           3          60          62          69          71          28
459200101          86          93          25           2           9          61          68          75          52          34
459200101          17          24          76          83          90          42          49          26          33          65
459200101          23           5          82          89          91          48          30          32          39          66
37833100          79           6          13          95          97          29          31          38          45          72
37833100          10          12          94          96          78          35          37          44          46          53
37833100          11          18         100          77          84          36          43          50          27          59

第一列是公司代码。其余列是公司的数据,每行指的是给定年份第 1 列中的公司。请注意,年份可能并非对每个公司都是平衡的。 我想根据第一列减去子矩阵。例如,对于 A(1:3,2:11) 对于 931142103:

 A(1:3,2:11)

ans =

    92    99     1     8    15    67    74    51    58    40
    98    80     7    14    16    73    55    57    64    41
     4    81    88    20    22    54    56    63    70    47 

459200101(即 A(4:7,2:11))和 A(8:10,2:11) 相同 37833100.

我觉得代码应该是这样的:

  indices=find(A(:,1));
    obs=size(A(:,1));
    for i=1:obs,
        if i==indices(i ??)
            A{i}=A(??,2:11);
        end
    end

我很难索引这些复杂的代码:45920010137833100 以便将它们收集在一起。我怎样才能写出我的子矩阵 A{i} 的行?

非常感谢!

一种方法 arrayfun -

%// Get unique entries from first column of A and keep the order 
%// with 'stable' option i.e. don't sort
unqA1 = unique(A(:,1),'stable') 

%// Use arrayfun to select each such submatrix and store as a cell 
%// in a cell array, which is the final output
outA = arrayfun(@(n) A(A(:,1)==unqA1(n),:),1:numel(unqA1),'Uni',0)

或者这个-

[~,~,row_idx] = unique(A(:,1),'stable')
outA = arrayfun(@(n) A(row_idx==n,:),1:max(row_idx),'Uni',0)

最后,您可以调用 celldisp(outA)

来验证结果

如果第 1 列中的值总是分组显示(如您的示例所示),您可以按如下方式使用 mat2cell

result = mat2cell(A, diff([0; find(diff(A(:,1))); size(A,1)]));

如果他们不这样做,只需在应用上述内容之前根据第 1 列对 A 的行进行排序:

A = sortrows(A,1);
result = mat2cell(A, diff([0; find(diff(A(:,1))); size(A,1)]));

如果您不介意结果在内部没有被排序,您可以使用 accumarray 来实现:

[~,~,I] = unique(A(:,1),'stable');
partitions = accumarray(I, 1:size(A,1), [], @(I){A(I,2:end)});