count the number of positive values in a vector in matlab

Assuming the vector is named v, you can count the number of positive values in v using the following code snippet in MATLAB:

main.m
num_positive = nnz(v > 0)
26 chars
2 lines

nnz stands for "number of non-zeros" and counts the number of elements in the logical array v > 0 that are true. This gives us the number of positive values in the vector.

Alternatively, you can also use the MATLAB sum function to achieve the same result:

main.m
num_positive = sum(v > 0)
26 chars
2 lines

Both of these methods should give you the number of positive values in the vector v.

related categories

gistlibby LogSnag