MATLAB Answers


How can I vectorize for loop with randsample

Asked by Merit
on 13 Oct 2012

I like to know if there is a any simpler way of doing this (without for-loop):

    A = zeros(4,3)   %this size is just an example
    for i=1 : 4      %I want to add 4 vectors ...
      A(i,:) = randsample(7,3)'  %... which are 3 different numb from [1-7]
    A =
       4     6     2
       1     7     3
       2     1     5
       3     5     6

So my point is to create a matrix from different vectors, which I have created with randsample. Is there a way I can vectorize this?

Have been fighting with this many days :)

Yours Merit



No products are associated with this question.

1 Answer

Answer by Walter Roberson
on 13 Oct 2012
Edited by Walter Roberson
on 13 Oct 2012
 Accepted answer

numvecs = 4;
popsize = 7;
numselected =3;
[junk, randidx] = sort(rand(numvecs, popsize), 2);  %sort along row
A = randidx(:,1:numselected);



on 13 Oct 2012

Thank you Walter, just what I needed :)


Join the 15-year community celebration.

Play games and win prizes!

Learn more
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

MATLAB Academy

New to MATLAB?

Learn MATLAB today!