计算符合条件的值 [英] Counting values that meet a condition
本文介绍了计算符合条件的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试计算列向量中的值大于 0.5
的次数.下面的代码将我带到了我需要的位置,但我想知道这是执行此操作的最有效方法.
I am trying to count the number of times a value in a column vector is greater than 0.5
. The code below gets me where I need to be but I am wondering is this the most efficient way to do this.
n = 500
AA = rand(n,1);
for i = 1:n
if abs(AA(i))>0.5
BB(i)=1;
else
BB(i)=0;
end
end
sBB = sum(BB);
SD = sBB/n;
推荐答案
此任务可受益于向量化:
This task can benefit from vectorization:
n = 500
AA = rand(n,1); % You used vectorization already (!) and not create each entry separately...
BB = AA>0.5; % Results in a vector of logicals which signifies where the condition was met
SD = sum(BB)/n; % Can also be `nnz(BB)/n` or `mean(BB)`
这篇关于计算符合条件的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文