Taking weighted means over matrices with missing data

4 次查看(过去 30 天)
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

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')

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 CenterFile Exchange 中查找有关 Logical 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by