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 randomly select a row from a matrix?

Asked by Graeme

Graeme (view profile)

on 17 Jun 2013
Accepted Answer by Evan

Evan (view profile)

I have a matrix (m) that is 17543 x 17. The values are of the type double.

I want to randomly select 1 row from this matrix and save it as a new vector.

I tried this:

mrow = m(randsample(m:17543,1),:)

This works if the values are integers but it does not work because they are doubles.

It returns the error message:

"Subscript indices must either be real positive integers or logicals."

Any help would be really appreciated.

Thanks,

Graeme

0 Comments

Graeme

Graeme (view profile)

Products

3 Answers

Answer by Evan

Evan (view profile)

on 17 Jun 2013
Edited by Evan

Evan (view profile)

on 17 Jun 2013
Accepted answer

Try this:

ind = ceil(rand * size(m,1));
mrow = m(ind,:);

4 Comments

Evan

Evan (view profile)

on 17 Jun 2013

Are you sure? I just tried this out with a random sample of size 17543x17 and I'm getting different rows each time. When you run my code, does the value of "ind" always return 1? I think it would only return 1 every time if m was a 1xn matrix.

Graeme

Graeme (view profile)

on 17 Jun 2013

Apologies you are correct.

Thanks you very much for your help!

Evan

Evan (view profile)

on 17 Jun 2013

No worries! And you're welcome--glad you got it fixed. :)

Evan

Evan (view profile)

Answer by Jonathan Sullivan

Jonathan Sullivan (view profile)

on 17 Jun 2013

Try using randi

Example

randomRow = m(randi(size(m,1)),:);

0 Comments

Jonathan Sullivan

Jonathan Sullivan (view profile)

Answer by Wayne King

Wayne King (view profile)

on 17 Jun 2013
Edited by Wayne King

Wayne King (view profile)

on 17 Jun 2013
m = randn(17543,17);
idx = randperm(size(m,1),1);
B = m(idx,:);

idx tells you which row you randomly selected.

If you have an older version of MATLAB where the above does not work do:

m = randn(17543,17);
idx = randperm(size(m,1),1);
B = m(idx(1),:);

0 Comments

Wayne King

Wayne King (view profile)

Contact us