Create vector with unique values
이전 댓글 표시
I need to create a vector of length 5000 in the interval from 1 to 2 with unique values (so that there are no repetitions), is it possible to do this? (the randi command gives me the values, but there appear repetitions)
채택된 답변
추가 답변 (2개)
Rejection method, it likely needs a single iteration
n = 5000;
while true
r = unique(1+rand(1,round(n*1.1)));
p = length(r);
if p >= n
r = r(randperm(p,n));
break
end
end
r
% check
all(r>=1 & r<=2)
length(unique(r))==length(r)
댓글 수: 4
Les Beckham
2022년 3월 31일
편집: Les Beckham
2022년 3월 31일
I think this is the most correct approach.
Just curious, though, @Bruno Luong, why do the randperm "scrambling" of r? Couldn't you just take the first n elements since r is already random?
Les Beckham
2022년 3월 31일
Actually, I forgot that unique sorts by default. One could use
r = unique(1+rand(1,round(n*1.1)), 'stable');
to avoid the sorting and then just truncate the result to the first n elements.
Bruno Luong
2022년 3월 31일
편집: Bruno Luong
2022년 3월 31일
Yes, you point correctly unique sort the random stream.
+1 Good point alsoo using 'stable' option and avoid randperm.
Bruno Luong
2022년 3월 31일
Here is complete code with modification suggested by @Les Beckham
n = 5000;
while true
r = unique(1+rand(1,round(n*1.1)),'stable');
p = length(r);
if p >= n
r = r(1:n);
break
end
end
Bruno Luong
2022년 3월 31일
편집: Bruno Luong
2022년 3월 31일
% I'm sure there is no repetition but the set of values is not random
r = 1+randperm(5000)/5000;
% check
all(r>=1 & r<=2)
length(unique(r))==length(r)
카테고리
도움말 센터 및 File Exchange에서 Random Number Generation에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!