计算满足条件的值

问题描述 投票:0回答:1

我试图计算列向量中的值大于0.5的次数。下面的代码让我得到了我需要的地方,但我想知道这是最有效的方法。

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;
matlab performance optimization count condition
1个回答
2
投票

此任务可以从矢量化中受益:

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)`
© www.soinside.com 2019 - 2024. All rights reserved.