Create vector with unique values

조회 수: 14 (최근 30일)
Lev Mihailov
Lev Mihailov 2022년 3월 31일
댓글: Bruno Luong 2022년 3월 31일
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)

채택된 답변

David Hill
David Hill 2022년 3월 31일
편집: David Hill 2022년 3월 31일
v=1+rand(1,5000);
  댓글 수: 1
Bruno Luong
Bruno Luong 2022년 3월 31일
편집: Bruno Luong 2022년 3월 31일
You can't be sure there is no repetition, especially consider the number of floating point numbers in (0,1) and generate by rand() on a computer are finite (but large), but I admit the chance is tiny.

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Bruno Luong
Bruno Luong 2022년 3월 31일
편집: Bruno Luong 2022년 3월 31일
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
r = 1×5000
1.0939 1.1626 1.1336 1.1551 1.2421 1.0354 1.5319 1.3017 1.2257 1.9326 1.8532 1.9819 1.9699 1.2436 1.2587 1.9323 1.9716 1.1154 1.2823 1.7038 1.7327 1.1640 1.9592 1.9968 1.1904 1.6269 1.1277 1.5514 1.2853 1.3155
% check
all(r>=1 & r<=2)
ans = logical
1
length(unique(r))==length(r)
ans = logical
1
  댓글 수: 4
Bruno Luong
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
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
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)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by