How Can I Take Samples from a Matrix Randomly?

Hi Everyone
I want to take samples from a matrix randomly which is called as in my case"matrix". I just simplified the "matrix", actually size of "matrix" is 65500x3 and size of "train" is 2560x3. So I don't want to do this manually. My purpose is generate one seperate "test" matrix from "matrix" and that first two column of "test" matrix must be different from first two column of "train" matrix. To make this I wrote this code, but it is poor and it doesn't work properly. Any idea?
train=[2 1 3;1 2 3;3 1 2;2 2 1;1 1 2];
matrix=[1 2 3;2 1 3;3 1 2;2 2 2;1 1 1;1 2 4;2 2 2];
test=[];
adj=6;
[rows cols]=size(train);
for j=1:adj
flag1=[0];
flag2=[0];
flag3=[1];
while flag3 ~= 1
temp=datasample(matrix,1);
for i=1:rows
if sum(temp(1,1:2) == train(i, 1:2))==2
flag1=[flag1 1];
end
end
flag3=sum(flag1 || flag2 == 1);
end
test=vertcat(test,temp);
end
test
train

1 comentario

Azzi Abdelmalek
Azzi Abdelmalek el 27 de Abr. de 2016
I want to take samples into a matrix randomly, but this samples 1. and 2. columns values can't be identical with another test matrix rows 1. and 2. colmns values
What does that mean?

Iniciar sesión para comentar.

 Respuesta aceptada

Stephen23
Stephen23 el 27 de Abr. de 2016
Editada: Stephen23 el 27 de Abr. de 2016
Try this:
>> idx = ~ismember(matrix(:,1:2),train(:,1:2),'rows')
>> test = matrix(idx,:)
It compares only the first two columns, and returns an index where the matrix data is not in train.
But with your example train data there are no rows that are not already matches for the first two columns, so here is an example with a simpler train matrix:
>> train = [2 1 3;1 2 3;3 1 2]
train =
2 1 3
1 2 3
3 1 2
>> idx = ~ismember(matrix(:,1:2),train(:,1:2),'rows');
>> test = matrix(idx,:)
test =
2 2 2
1 1 1
2 2 2
if you only want the unique rows then run this:
>> test = unique(matrix(idx,:),'rows')

1 comentario

Aliyar Gunes
Aliyar Gunes el 27 de Abr. de 2016
Thank you Stephen, this is what I want. Thanks a lot.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Get Started with MATLAB en Centro de ayuda y File Exchange.

Preguntada:

el 27 de Abr. de 2016

Editada:

el 30 de Abr. de 2016

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by