计算符合条件的值

时间:2019-02-21 13:06:23

标签: matlab performance optimization count conditional-statements

我正在尝试计算列向量中的值大于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;

1 个答案:

答案 0 :(得分: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)`