简体   繁体   English

在Matlab中的列表中选择一个随机非零元素的索引

[英]Select the index of a random non-zero element in list in Matlab

Is there any ready command to get the intended output from the input? 是否有任何就绪命令可以从输入中获得预期的输出?

Input 输入项

>>> a=[1 0 3 0 5 6 7 8 0 10 0 0]; selectNonZero(a)

Intended output 预期输出

1 or 3 or 5 or 6 or 7 or 8 or 10

Trials 试用版

>> b=a(a~=0); pi=randi([1, length(b)]); b(pi)    % The original index of b(pi)?

>> fix=[0 1 2 2 2 2 2]; pi+fix(pi)               % Fix changed index, cum command?

You can do it this way. 您可以这样进行。 It's similar to your approach, but using find to know the indices of nonzero values. 它与您的方法类似,但是使用find可以知道非零值的索引。

jj = find(a~=0); % indices of nonzero values of a
ind = jj(randi(length(jj))); % randomly pick one of those indices
val = a(ind); % corresponding value of a

The results you want are sel (selected value) and ind (its index within a ). 您想要的结果是sel (选定值)和ind (其在a索引)。

A variant of Luis' answer is to use the built-in nnz function: Luis回答的一种变体是使用内置的nnz函数:

idx = find(a);
rand_idx = idx(randi(nnz(a)));

If you have the Statistics Toolbox installed, you can reduce this into a one-liner using randsample : 如果您安装了统计工具箱,则可以使用randsample将其randsample为一种randsample

rand_idx = randsample(find(a), 1);

Note: if you want to choose a random value (and not its index), replace find(a) with nonzeros(a) (this is a shorter alternative to generating a random index and then doing a(rand_idx) ). 注意:如果要选择随机值(而不是其索引), nonzeros(a) find(a)替换为nonzeros(a) (这是生成随机索引然后执行a(rand_idx)的更短选择)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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