Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

New to MATLAB?

How can I select randomly?

Asked by Beril Emrealp

Beril Emrealp (view profile)

on 12 Dec 2012

Hello, I have an 10000 rows and 10 columns matrix. I want to select randomly 500 rows from this matrix. I want to ask you, randperm function is true for this purpose. How can I select 500 rows randomly from this matrix?

0 Comments

Beril Emrealp

Beril Emrealp (view profile)

Products

No products are associated with this question.

2 Answers

Answer by Jos (10584)

Jos (10584) (view profile)

on 12 Dec 2012
Accepted answer

Random can be defined in two ways:

% A is your original matrix
Nrows = size(A,1) ; % number of rows
% Option 1: randomly select 500 UNIQUE(!) rows
idx = randperm(Nrows) ; 
idx = idx(1:500) ;
% Option 2: randomly select 500 rows 
idx = randi(Nrows,[Nrows 1]) ;
% and then ...
B = A(idx,:) ;

2 Comments

Beril Emrealp

Beril Emrealp (view profile)

on 12 Dec 2012

Thank you very much for the answer. :)) It works great. But I want to ask you a question more. You wrote "randomly select 500 UNIQUE(!) rows", in this way for example when 550th row is selected, no more it can be selected. Is it true?

Jan Simon

Jan Simon (view profile)

on 12 Dec 2012

The RANDPERM approach creates unique indices, while the indices created by RANDI can be non-unique, e.g. [1, 503, 1017, 1, ...].

Jos (10584)

Jos (10584) (view profile)

Answer by Jan Simon

Jan Simon (view profile)

on 12 Dec 2012
Edited by Jan Simon

Jan Simon (view profile)

on 12 Dec 2012
M = rand(10000, 10);
index = randperm(10000, 500);  % In modern Matlab versions
R = M(index, :);

In older Matlab versions randperm does not accept a 2nd input. Then:

index = randperm(10000);
index = index(1:500);

If this must be fast, use the C-Mex FEX: Shuffle.

index = Shuffle(10000, 'index', 500)

7 Comments

Image Analyst

Image Analyst (view profile)

on 14 Dec 2012

I could hear the sound of a hand slapping a forehead all the way across the Atlantic. ;-)

Matt Fig

Matt Fig (view profile)

on 14 Dec 2012

Apparently saying, "M is your original matrix" would have made all the difference ;-).

Beril Emrealp

Beril Emrealp (view profile)

on 19 Dec 2012

I understand :)))

Jan Simon

Jan Simon (view profile)

Contact us