Taking weighted means over matrices with missing data

5 vues (au cours des 30 derniers jours)
William
William le 14 Mai 2013
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?

Réponses (4)

Teja Muppirala
Teja Muppirala le 14 Mai 2013
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 commentaire
Teja Muppirala
Teja Muppirala le 14 Mai 2013
A bit simpler:
W = bsxfun(@times,~isnan(M),w);
M(isnan(M)) = 0;
sum(M.*W,2)./sum(W,2)

Connectez-vous pour commenter.


David Sanchez
David Sanchez le 14 Mai 2013
I think it is not possible, but you can write your own function to do it.

Yao Li
Yao Li le 14 Mai 2013
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 commentaire
Teja Muppirala
Teja Muppirala le 14 Mai 2013
This will have some trouble if any of the elements in A are zero, because 0./0 equals NaN.

Connectez-vous pour commenter.


Andrei Bobrov
Andrei Bobrov le 14 Mai 2013
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);

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by