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

19 visualizaciones (últimos 30 días)
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?

Respuesta aceptada

dpb
dpb el 9 de Mayo de 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 comentarios
piyius raj
piyius raj el 9 de Mayo de 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 el 9 de Mayo de 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

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Productos


Versión

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by