简体   繁体   中英

Matlab: random integers from a range with no repetition

I want to get an array with randomized integer included in range with no repeat, I used :

randperm(15,3)

output is :

8, 10, 12

This function not use a range, I would like to random values only from 10 eg

If you have the Statistics toolbox, you can use randsample without replacement.

% MATLAB R2017a
LB = 3;   % lower bound of range (integer)
UB = 17;  % upper bound of range (integer),  UB > LB
randsample(LB:UB,3,'false') 

@ Wolfie 's method using randperm works well and requires no toolbox .

LB - 1 + randperm(UB-LB+1,3)

Notice that randi works well for uniformly distributed (discrete uniform) integers in a range but it samples with replacement (can give duplicates). This requires no toolbox to my knowledge but would require combining with a procedure to remove duplicates and resample until all integers were unique.

randi([LB UB],3,1)

Note: will remove @ Wolfie 's method if @Wolfie posts it as answer or can make this answer community wiki based on consensus.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM