Create vector with unique values
9 次查看(过去 30 天)
显示 更早的评论
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)
0 个评论
采纳的回答
David Hill
2022-3-31
编辑:David Hill
2022-3-31
v=1+rand(1,5000);
1 个评论
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
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
% check
all(r>=1 & r<=2)
length(unique(r))==length(r)
4 个评论
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)
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!