Reputation: 191
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;
Upvotes: 0
Views: 393
Reputation: 24169
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)`
Upvotes: 2