且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用matlab根据一列拆分矩阵.

更新时间:2022-12-11 21:41:24

使用逻辑索引

B=A(A(:,end)==10,:);
C=A(A(:,end)==2,:);

返回

>> B
B =
     1     4     2     5    10
     2     1     5     6    10

>> C
C =
     2     4     5     6     2
     2     3     5     4     2

编辑:在这里回应Dan的评论是一般情况的扩展名

In reply to Dan's comment here is the extension for general case

e = unique(A(:,end));
B = cell(size(e));
for k = 1:numel(e)
    B{k} = A(A(:,end)==e(k),:);
end

或更紧凑的方式

B=arrayfun(@(x) A(A(:,end)==x,:), unique(A(:,end)), 'UniformOutput', false);

所以

A =
     1     4     2     5    10
     2     4     5     6     2
     2     1     5     6    10
     2     3     5     4     2
     0     3     1     4     9
     1     3     4     5     1
     1     0     4     5     9
     1     2     4     3     1

您将得到单元格数组B

>> B{1}
ans =
     1     3     4     5     1
     1     2     4     3     1

>> B{2}
ans =
     2     4     5     6     2
     2     3     5     4     2

>> B{3}
ans =
     0     3     1     4     9
     1     0     4     5     9

>> B{4}
ans =
     1     4     2     5    10
     2     1     5     6    10