## Create a matrix that stores rows that are not from a random sample

Asked by Elanakayon Annalingam

### Elanakayon Annalingam (view profile)

on 10 Nov 2019 at 3:22
Latest activity Edited by Stephan

### Stephan (view profile)

on 10 Nov 2019 at 9:54
I have a 1020x9 matrix and I took a random sample that is half the original size (510x9), I want to retrieve the other half. I think the best way to do this is to do matrix comparison of the orignal matrix and the random sample and store the rows they don't have in common into a new matrix. How can I accomplish this?

KALYAN ACHARJYA

### KALYAN ACHARJYA (view profile)

on 10 Nov 2019 at 9:37
Can you elaborate with small example?

### Thiago Henrique Gomes Lobato (view profile)

Answer by Thiago Henrique Gomes Lobato

### Thiago Henrique Gomes Lobato (view profile)

on 10 Nov 2019 at 9:42

The function ismember may be what you need to efficiently solve your problem:
OriginalMatrix = randn(1020,9);
RandomMatrixIndex = randperm(1020);
IndexFirstMatrix = RandomMatrixIndex(1:end/2);
IndexSecondMatrix = RandomMatrixIndex(end/2+1:end);
FirstMatrix = OriginalMatrix(IndexFirstMatrix,:);
IndexFound = ismember(OriginalMatrix,FirstMatrix,'rows');
EqualIndex = find(IndexFound==1); % Index for your first matrix
FoundedIndexSecondMatrix = find(IndexFound==0); % Remaining index, those that you want
% Comparison to check that they are the same
Cmp1 = norm( sort(IndexFirstMatrix)-EqualIndex')
Cmp2 = norm( sort(IndexSecondMatrix)-FoundedIndexSecondMatrix')
Cmp1 =
0
Cmp2 =
0

### Stephan (view profile)

on 10 Nov 2019 at 9:52
Edited by Stephan

### Stephan (view profile)

on 10 Nov 2019 at 9:54

A way smarter is using the ismember function - here is an example - all you need ist the last line, the first two lines are just to get some numbers to illustrate:
matrix = randi(10,6,3)
sample = matrix(1:2:end,:)
result = matrix(~ismember(matrix,sample,'rows'),:)
matrix =
2 9 6
7 4 5
5 7 10
8 2 7
8 1 7
10 8 9
sample =
2 9 6
5 7 10
8 1 7
result =
7 4 5
8 2 7
10 8 9