0

Can I fixed number of rows randomly from the dataset?

example

 A=[1 2 3 4; 
   5 6 7 8; 
   9 10 11 12; 
   13 14 15 16; 
   17 18 19 20];

I want to random select training dataset 3 rows and random select testing dataset 2 rows.

training_dataset= [1 2 3 4; 
                   13 14 15 16;
                   5 6 7 8;];

and

   testing_dataset= [ 9 10 11 12; 
                    17 18 19 20];

I found only the random number from the array.

Thank you so much

desertnaut
  • 57,590
  • 26
  • 140
  • 166
Watt Cnx
  • 49
  • 6
  • 5
    Please [edit] your question to clarify: do you want to select a fixed number of rows randomly, or a random number of rows? — Also please include what you have tried so far. You must have found some solutions through Google or whatever. Why are those not suitable? Adding that helps narrow down the question. Thanks! – Cris Luengo Mar 16 '19 at 16:30

1 Answers1

2

This solution uses the randperm and setdiff commands.

indTrainRow = randperm(size(A,1),3)
indTestRow = setdiff(1:size(A,1),indTrainRow)

training_dataset = A(indTrainRow,:);
testing_dataset = A(indTestRow,:);

You can also use randsample but this requires the Statistics toolbox.

indTrainRow = randsample(1:size(A,1),3,'false') 

After posting this I found some related posts. My mistake for not finding these before answering.

Related Posts:
Random selection of matrix columns
How can I divide/split up a matrix by rows between two other matrices?

SecretAgentMan
  • 2,856
  • 7
  • 21
  • 41