How Can I Take Samples from a Matrix Randomly?
4 views (last 30 days)
Show older comments
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 Comment
Azzi Abdelmalek
on 27 Apr 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?
Accepted Answer
Stephen23
on 27 Apr 2016
Edited: Stephen23
on 27 Apr 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')
More Answers (0)
See Also
Categories
Find more on Get Started with MATLAB in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!