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

18 vues (au cours des 30 derniers jours)
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
randperm
but can this matrix be created without using a for loop?

Réponse acceptée

dpb
dpb le 9 Mai 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
A=reshape(randperm(N,m*p),m,[]);
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.
  2 commentaires
piyius raj
piyius raj le 9 Mai 2021
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. m is less than n.
for i=1:p
A = [A; randperm(n,m)]
end
but I dont want to use for loop.
dpb
dpb le 9 Mai 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...
A=zeros(P,M);
for i=1:P
A(i,:)=randperm(N,M);
end

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Produits


Version

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by