How can I select randomly?

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?

 채택된 답변

Jos (10584)
Jos (10584) 2012년 12월 12일

1 개 추천

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

Selin Soguksu
Selin Soguksu 2012년 12월 12일
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
Jan 2012년 12월 12일
편집: Jan 2012년 12월 12일
The RANDPERM approach creates unique indices, while the indices created by RANDI can be non-unique, e.g. [1, 503, 1017, 1, ...].

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Jan
Jan 2012년 12월 12일
편집: Jan 2012년 12월 12일

0 개 추천

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

Selin Soguksu
Selin Soguksu 2012년 12월 12일
Thank you for the answer, but it didn't solve my question.
Jan
Jan 2012년 12월 12일
편집: Jan 2012년 12월 12일
@Beril: That's interesting. Why does it not solve your problem although it seems to be the same code as in the accepted answer?
Selin Soguksu
Selin Soguksu 2012년 12월 13일
Because when I wrote M=rand(10000,10), MATLAB generates numbers between 0 and 1. But I didn't want this. I had an matrix with datas.
Jan
Jan 2012년 12월 13일
@Beril: Ouch. In my example M is only created to have any test data. In the real program this line should be omitted, of course. Your question contains only the description "I have an 10000 rows and 10 columns matrix" and I filled it with random data. This is a usual method in a forum, because it allows to test the code before posting it.
Image Analyst
Image Analyst 2012년 12월 14일
I could hear the sound of a hand slapping a forehead all the way across the Atlantic. ;-)
Matt Fig
Matt Fig 2012년 12월 14일
Apparently saying, "M is your original matrix" would have made all the difference ;-).
Selin Soguksu
Selin Soguksu 2012년 12월 19일
I understand :)))

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by