Generate Unique Random Matlab Numbers with a range

前端 未结 1 1900
终归单人心
终归单人心 2021-01-28 18:55

Say I want 5 numbers between 1 to 10. However, I do not want any number to be repeated. How do I do this?

I thought of doing

 randi([1,length(a)])


        
相关标签:
1条回答
  • 2021-01-28 19:20

    One way to do it is by using randperm:

    N = 10;    % Numbers from 1 to N will be permuted
    n = 5;    % Numbers to be extracted
    x = randperm(N);    % Permute numbers between 1 and N
    x = x(1:n);    % Retain first n
    

    This can be generalized to any set of values:

    N = 10;    % Length of vector of N numbers to be permuted
    y = randn(N, 1);    % Vector from which you want to extract values
    n = 5;    % Numbers to be extracted
    x = randperm(N);    % Permute numbers between 1 and N
    x = y(x(1:n));    % Retain first n of y
    

    The problem is when N is large and n is small:

    tic
    N = 1e7;
    n = 2;
    x = randperm(N);
    x = x(1:n);
    toc
    

    Then you need to find a better solution. If you have the Statistics Toolbox, try:

    tic
    x = randsample(N, n, false);
    toc
    

    Another approach, which is also slow but doesn't make use of randperm or randsample:

    N = 1e7;
    n = 2;
    y = randn(N, 1);
    tic
    x = randn(N, 1);
    [x x] = sort(x);
    x = y(x(1:n));
    toc
    
    0 讨论(0)
提交回复
热议问题