【问题标题】:Randomly number selector from a given list of numbers [duplicate]给定数字列表中的随机数字选择器[重复]
【发布时间】:2019-02-23 18:09:31
【问题描述】:

我已经给出了数字列表,

x=[x1, x2, x3, x4, x5, x6];
non_zero=find(x);

我希望 Matlab 一次在“非零”元素中随机选择任何人。我在网上搜索过,但没有这样的功能可以提供我需要的结果。

【问题讨论】:

    标签: matlab random matlab-guide


    【解决方案1】:

    您可以使用函数randi 从有效索引集中随机选择一个整数。

    x=[x1, x2, x3, x4, x5, x6];
    non_zero=find(x);
    
    index = randi(numel(non_zero));
    number = x(non_zero(index))
    

    或者,也许更清楚一点,首先制作x 的副本,从该副本中删除零元素,然后从[1 numel(x_nz)] 范围内选择一个随机整数。

    x=[x1, x2, x3, x4, x5, x6];
    x_nz = x; 
    x_nz(x == 0) = 0;
    
    index = randi(numel(x_nz));
    number = x_nz(index)
    

    为确保每次不会得到相同的序列,请先调用rng('shuffle') 设置随机数生成的种子。

    【讨论】:

      【解决方案2】:

      您考虑过randsample 还是datasample

      x = [1 4 3 2 6 5];        
      randsample(x,1,'true')    % samples one element from x randomly
      randsample(x,2,'true')    % two samples
      
      datasample(x,1)
      
      % Dealing with the nonzero condition
      y = [1 2 3 0 0 7 4 5];
      k = 2;                    % number of samples
      randsample(y(y>0),k,'true')
      
      datasample(y(y>0),k)   
      

      发布此答案后,我从@Rashid(由@ChrisLuengo 链接)找到了this excellent answer。他还建议考虑datasample(unique(y(y>0),k) 是否合适。

      【讨论】:

      • 您的意思是您在我昨天链接的副本中找到了最佳答案? :p
      • @CrisLuengo 是的,我该怎么办?在我发布答案之前,我没有查看您的链接。我应该把它变成一个社区维基吗?
      • 不,别担心。这只是有点浪费。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-19
      • 1970-01-01
      • 2023-01-11
      • 2021-03-05
      • 1970-01-01
      • 2016-06-08
      • 2022-06-17
      相关资源
      最近更新 更多