MATLAB: How to average only positive values in an array

MATLABmean

My problem: I have a matrix M with 20 columns and thousands of rows. Each column in the matrix has positive and negative values (and each column has a different ratio of positive to negative numbers). I want to find the average value of only the positive numbers in each column in the matrix, and put those averages into an array (so a 1 x 20 array). How can I code this?

Best Answer

x = rand(1000, 20) - 0.5;
Positive = x > 0;
x(~Positive) = 0;
MeanPositive = sum(x, 2) ./ sum(Positive, 2);