繁体   English   中英

Matlab:按特定标准从矩阵中选择子矩阵

[英]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列中的公司。 请注意,每个公司的年份可能不平衡。 我想根据第一列减去子矩阵。 例如,对于931142103的A(1:3,2:11)

 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

我很难将这些复杂的代码459200101入索引: 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)});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM