1

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.

Wolfie
  • 27,562
  • 7
  • 28
  • 55
Mella 30
  • 13
  • 4

2 Answers2

3

The most challenging part of this question is obtaining D. You can assign A to D without any cost and remove unneeded rows.

C = A(B,:);
D = A;
D(B,:) = [];
rahnema1
  • 15,264
  • 3
  • 15
  • 27
  • 1
    This solution is especially good if you don't need to preserve `A`, because you can obviously skip the intermediate creation of `D` with `A(B,:)=[]`. – Wolfie Aug 15 '19 at 08:45
1

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
Wolfie
  • 27,562
  • 7
  • 28
  • 55