split a matrix according to a column with matlab.

后端 未结 3 1178
别那么骄傲
别那么骄傲 2021-01-14 13:57
A = [1,4,2,5,10
     2,4,5,6,2
     2,1,5,6,10
     2,3,5,4,2]

And I want split it into two matrix by the last column A ->B and C

B         


        
3条回答
  •  时光取名叫无心
    2021-01-14 14:46

    Use logical indexing

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

    returns

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

    EDIT: 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
    

    or more compact way

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

    so for

    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
    

    you get the matrices in elements of cell array 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
    

提交回复
热议问题