フィルターのクリア

Taking weighted means over matrices with missing data

6 ビュー (過去 30 日間)
William
William 2013 年 5 月 14 日
I have a matrix with some NaN entries. I want to calculate the weighted averages of each row, according to a supplied row vector of weights. Where a row has one or more missing values, I simply want to scale up the remaining weights. This is easy enough to do as a for loop over all rows; but I was wondering if there's a simple way to do so using just matrix operations.
Illustration: say my matrix is:
[4 NaN 1 NaN; 5 3 8 NaN; 1 6 2 4; 8 4 7 2]
The weight vector is:
[0.4 0.3 0.2 0.1]
I want to return the column vector:
[3; 5; 3; 6]
For the last row, 6 = 8*0.4 + 4*0.3 + 7*0.2 + 2*0.1. For the first row, 3 = (4*0.4 + 1*0.2)/(0.4 + 0.2). And so on.
Is this possible using matrix operations over the whole matrix at once, or will it have to be done row by row in a loop?

回答 (4 件)

Teja Muppirala
Teja Muppirala 2013 年 5 月 14 日
M = [4 NaN 1 NaN; 5 3 8 NaN; 1 6 2 4; 8 4 7 2];
w = [0.4 0.3 0.2 0.1];
W = bsxfun(@times,~isnan(M),w);
W = bsxfun(@rdivide,W,sum(W,2));
M(isnan(M)) = 0;
sum(M.*W,2)
ans =
3.0000
5.0000
3.0000
6.0000
  1 件のコメント
Teja Muppirala
Teja Muppirala 2013 年 5 月 14 日
A bit simpler:
W = bsxfun(@times,~isnan(M),w);
M(isnan(M)) = 0;
sum(M.*W,2)./sum(W,2)

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


David Sanchez
David Sanchez 2013 年 5 月 14 日
I think it is not possible, but you can write your own function to do it.

Yao Li
Yao Li 2013 年 5 月 14 日
A=[4 NaN 1 NaN; 5 3 8 NaN; 1 6 2 4; 8 4 7 2];
A_u=A./A;
A(isnan(A))=0;
A_u(isnan(A_u))=0;
weight=[0.4 0.3 0.2 0.1];
y=weight*(A')./(weight*A_u')
  1 件のコメント
Teja Muppirala
Teja Muppirala 2013 年 5 月 14 日
This will have some trouble if any of the elements in A are zero, because 0./0 equals NaN.

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


Andrei Bobrov
Andrei Bobrov 2013 年 5 月 14 日
M = [4 NaN 1 NaN; 5 3 8 NaN; 1 6 2 4; 8 4 7 2];
w = [0.4 0.3 0.2 0.1]';
t = isnan(M);
M(t) = 0;
out = (M*w)./(~t*w);

カテゴリ

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