Path: news.mathworks.com!not-for-mail
From: "Bruno Luong" <b.luong@fogale.findmycountry>
Newsgroups: comp.soft-sys.matlab
Subject: Re: Faster and vectorized
Date: Thu, 29 Oct 2009 17:03:19 +0000 (UTC)
Organization: FOGALE nanotech
Lines: 19
Message-ID: <hcchsn$pv$1@fred.mathworks.com>
References: <hcbr1h$ne0$1@fred.mathworks.com>
Reply-To: "Bruno Luong" <b.luong@fogale.findmycountry>
NNTP-Posting-Host: webapp-05-blr.mathworks.com
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1256835799 831 172.30.248.35 (29 Oct 2009 17:03:19 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Thu, 29 Oct 2009 17:03:19 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 390839
Xref: news.mathworks.com comp.soft-sys.matlab:581059


Try this:

function Out = WeMean(Values, Weights, Class)

Class(isnan(Values) | isnan(Weights)) = 0;
[unC trash C] = unique(Class);
[m n] = size(Class);
I = repmat((1:m).',1,n);
K = [I(:) C(:)];
sz = [m length(unC)];
Den = accumarray(K, Weights(:), sz);
Num = accumarray(K, Values(:).*Weights(:), sz);
filled =  accumarray(K, 1, sz);
Out = Num./Den;
header = unC(2:end).';
Out= [header; Out(:,2:end)];
Out(~filled)=NaN; % faster than fill with accumarray

% Bruno