How do I calculate the mean of only positive values
40 views (last 30 days)
Show older comments
I have a 3x24 array with negative and positive values, how do I calculate its mean value?
0 Comments
Answers (2)
Image Analyst
on 23 Dec 2020
Here's a well commented example:
m = 10 * rand(3, 24) - 5 % Create sample data (replace with your actual array).
posMap = m > 0 % Get map of where the positive values are.
m2 = m .* posMap; % Initializes m2.
m2(~posMap) = nan % Set negative values to nan so we can ignore them when we take the mean.
% Get mean of each column, meaning you average going down rows.
columnMeans = mean(m2, 1, 'omitnan')
% Get the mean of each row, meaning you average over all the columns in each row.
rowMeans = mean(m2, 2, 'omitnan')
% Get the mean of any positive value, regardless of which row or column it lives in.
overallMean = mean(m2(:), 'omitnan')
0 Comments
dpb
on 23 Dec 2020
mean(X(X>0)) % global mean
or
arrayfun(@(i) mean(X(X(:,i)>0,i)),1:size(X,2)) % column means
depending upon which mean(s) one is after.
0 Comments
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!