Taking weighted means over matrices with missing data

조회 수: 3 (최근 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 CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by