【问题标题】:Randomly select number and its index from an array in matlab从matlab中的数组中随机选择数字及其索引
【发布时间】:2015-05-03 09:51:32
【问题描述】:

我有一个数组 c=[1 2 3 4 5];可能有多个重复数字。 我想从数组中随机选择一个元素及其索引。 谁能帮帮我..

【问题讨论】:

  • 欢迎来到 SO!请查看stackoverflow.com/tour。通常,当您提出问题时,您会展示您已经尝试解决问题的方法。
  • 我试过 C(randi(numel(C)) 给了我随机数,但我怎么能找到那个数字的索引,因为这个数字在数组中出现了这么多次。
  • 尝试 C(randi(numel(C),1)) 如果您以后需要它,randi(numel(C),1) 将成为您的索引。考虑将其添加到您的问题中。

标签: matlab random


【解决方案1】:

你可以find

代码:

C = [1,2,3,4,5,4,4,5];  %// Example input. Change with your original array

no = C(randi(numel(C))) %// Your code to find a random number.
idx = find(C == no)    %// find all the indices matching the value of the number.

输出:

no =

 5


idx =

 5     8

【讨论】:

    【解决方案2】:

    先获取索引:

    idx = randi(numel(c));
    

    然后从数组中获取元素

    val = c(idx);
    

    【讨论】:

      猜你喜欢
      • 2014-04-21
      • 1970-01-01
      • 2014-04-28
      • 1970-01-01
      • 1970-01-01
      • 2020-10-27
      • 1970-01-01
      • 2021-10-22
      • 2018-09-17
      相关资源
      最近更新 更多