select randomly "N" rows of a matrix?

how i can select randomly "N" rows of a matrix? for example
M =
[ a12, a12]
[ a21, a22]
[ a31, a32]
[ a41, a42]
For N=2
B =
[ a12, a12]
[ a31, a32]
[ a21, a22]

 Accepted Answer

try:
N=2; % no. of rows needed
M=rand(5) % generate a 5x5 matrix random
c=randperm(length(M),N)
B=M(c,:) % output matrix

4 Comments

Right. The above does require a relatively new version of MATLAB, though; older versions of MATLAB did not support the second argument to randperm()
i have the following error
c=randperm(length(M),N)
??? Error using ==> randperm
Too many input arguments.
@Noe, Then use: c = randperm(size(M, 1)); c = c(1:N);

Sign in to comment.

More Answers (0)

Categories

Find more on Random Number Generation in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!