MATLAB Answers

randomly select elements of an array without repeat and create a matrix with these elements as rows

5 views (last 30 days)
piyius raj
piyius raj on 9 May 2021
Commented: dpb on 9 May 2021
Hi All,
I have integers from 1 to n. I want to choose m integers without replacement. I want to repeat this process p times and create a matrix of size m x p. For each repetition, I am starting with the initial integers (from 1 to n).
I know that choosing the elements can be done using
but can this matrix be created without using a for loop?

Accepted Answer

dpb on 9 May 2021
"1 to n. I want to choose m integers withiut replacement p times out of these integers, "
What does the above mean, precisely? IFF n > m*p, then
is without replacement for the full process; if it is p samples of m from the initial N, that's without replacement for each sample but with replacement across samples.
It's ambiguous which is meant for sure. To do the latter is a loop in one fashion or another; randperm isn't vectorized internally and the randi and other PRGs are pseudo-random, they don't do without replacement.
dpb on 9 May 2021
That is the same verbiage as before that is ambiguous. The code you show above is WITH replacement overall, only without by individual sample.
As noted, you can avoid an explicit loop but there will be the equivalent somewhere in the solution.
Unless M,P are extremely large, the time won't be an issue; you do need to preallocate, however, or you;ll see it as the sizes grow...
for i=1:P

Sign in to comment.

More Answers (0)




Community Treasure Hunt

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

Start Hunting!

Translated by