Adding unique values to an array

8 vues (au cours des 30 derniers jours)
Lou
Lou le 25 Avr 2022
Réponse apportée : Voss le 25 Avr 2022
I'm trying to generate 100 unique random numbers.
I've been trying through various iterations to either do an if not in RNQ append, if in RNQ continue type loop.
I want to keep generating numbers UNTIL I have 100 unique numbers.
I have a pway of discretising them to a specific distribution, but am stuck at the previous generating part.
RNQ = []
for N = 1:inf
r = rand(N,1);
RNQ = [RNQ;x]
UNI = unique(RNQ);
if numel(UNI)==100
break
else
continue
end
end

Réponse acceptée

Voss
Voss le 25 Avr 2022
You can use ismember to check whether the new random number is already in the array of unique numbers:
UNI = [];
while numel(UNI) < 100
r = rand(); % generate one random number (~Uniform [0,1])
if ismember(r,UNI)
continue
end
UNI = [UNI; r];
end

Plus de réponses (0)

Produits


Version

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by