How do I calculate the mean of only positive values

27 次查看(过去 30 天)
I have a 3x24 array with negative and positive values, how do I calculate its mean value?

回答(2 个)

Image Analyst
Image Analyst 2020-12-23
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')

dpb
dpb 2020-12-23
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.

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by