How to take the average of each column of a matrix without including a certain number

19 ビュー (過去 30 日間)
I have a matrix that has 864 rows and 7 columns and is filled with positive numbers and zeros. I want to take the average of each of those columns. However when MATLAB is taking the averages, I dont want it to include the zeros in its calculations. Can this be done?

採用された回答

Joseph Cheng
Joseph Cheng 2014 年 7 月 16 日
What you can do is do a quick substitution. if you know your matrix doesn't have any NaN (Not a number) then substitute the 0's for nan and then use the nanmean() which will exclude the NaNs from the average.
B=A;
B(A==0)=nan;
NonZeroAverages = nanmean(B);

その他の回答 (2 件)

Image Analyst
Image Analyst 2014 年 7 月 16 日
If you don't have nanmean because you don't have the Finance or Statistics toolbox, you can simply do
columnMeans = sum(a, 1) ./ sum(a~=0);
where "a" is the name of your matrix. This sums up the values in each column, then divides it by the sum of the non-zero values in each column.
  1 件のコメント
Image Analyst
Image Analyst 2014 年 7 月 16 日
Even if you do have those toolboxes, I'd use this method instead.

サインインしてコメントする。


Sara
Sara 2014 年 7 月 16 日
Let's call your array "a":
my_mean = zeros(size(a,2),1);
for i = 1:size(a,2)
d = a(:,i);d = d(d~=0);
my_mean(i) = mean(d);
end

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by