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