Search code examples
matlabmatrix-indexing

Split array based on given indices


I want to split one array into two based on given indices. Specifically, have two arrays, one array A with data (3 columns) and one B with indices.

A = [10 11 12; 
     20 21 22; 
     30 31 32; 
     40 41 42]
B = [1 3]

As a result, I want two new arrays C and D where C includes all values in A on given indices in B and D including the rest.

C = [10 11 12; 
     30 31 32] 
D = [20 21 22; 
     40 41 42]

For now, I'm having a loop (check for i in B with ismember and append value in A to array C/D accordingly) but since I have a lot of data, it takes quite long. Any help is appreciated, I know that there is a arrayfunction for everything in matlab.


Solution

  • Given

    A = [10 11 12; 
         20 21 22; 
         30 31 32; 
         40 41 42];
    B = [1 3];
    

    We can create C with some simple indexing

    C = A( B, : ); % rows from A indexed by B, all columns
    

    And create D using the setdiff of all row indices of A and the array B

    D = A( setdiff( 1:size(A,1), B ), : ); % rows from A *not* indexed by B, all columns