随机select数字及其来自matlab中数组的索引

Randomly select number and its index from an array in matlab

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

你可以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

首先获取索引:

idx = randi(numel(c));

然后从数组中获取元素

val = c(idx);