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?
0 个评论
回答(4 个)
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
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
2013-5-14
I think it is not possible, but you can write your own function to do it.
0 个评论
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
2013-5-14
This will have some trouble if any of the elements in A are zero, because 0./0 equals NaN.
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);
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!