Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: Faster and vectorized
Date: Thu, 29 Oct 2009 18:39:06 +0000 (UTC)
Organization: The MathWorks, Inc.
Lines: 71
Message-ID: <hccnga$p4a$1@fred.mathworks.com>
References: <hcbr1h$ne0$1@fred.mathworks.com> <hcchsn$pv$1@fred.mathworks.com> <hcciqm$a3$1@fred.mathworks.com> <hcck92$28n$1@fred.mathworks.com> <hcclvh$jo9$1@fred.mathworks.com>
Reply-To: <HIDDEN>
NNTP-Posting-Host: webapp-03-blr.mathworks.com
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1256841546 25738 172.30.248.38 (29 Oct 2009 18:39:06 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Thu, 29 Oct 2009 18:39:06 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 1886545
Xref: news.mathworks.com comp.soft-sys.matlab:581106


> There's something in the:
> Out(filled>0)=NaN; % faster than fill with accumarray
> row that doesn't work the right way. The output is all NaNs...
replaced ">" with "==";

BRUNO'S 

function Out = WeMean2(Values, Weights, Class)
Class(isnan(Values) | isnan(Weights)) = 0; % Align Class to Values and Weights
[unC, ~, C] = unique(Class); % Unique di Class and col sub
[m n] = size(Class); % Class dimensions
I = repmat((1:m).',1,n); % row sub
K = [I(:) C(:)]; % subs
sz = [m length(unC)]; % Out dimensions
Den = accumarray(K, Weights(:), sz); % Denominator
Num = accumarray(K, Values(:).*Weights(:), sz); % Numerator
Out = Num./Den; % Output
filled = accumarray(K, 1, sz); % Clear not filled with NaN
Out(filled == 0) = NaN; % major sign replaced with ==
% Place header
idx = unC ~= 0;
header = unC(idx).';
Out= [header; Out(:,idx)];
end

MINE
(look at the first post)

Perfomance check and same result..

for Ssize = 10:100:900;
Values = 10.*rand(Ssize); Values(ceil(100.*rand(Ssize/2))) = NaN; % Generate Values
Weights = 50000.*rand(Ssize); Weights(ceil(100.*rand(Ssize/2))) = NaN; % Generate Weights
Class = floor(Ssize*2/5.*rand(Ssize)); % Generate Classes to which values belong

tic; A = WeMean(Values, Weights, Class); toc; % Mine
tic; B = WeMean2(Values, Weights, Class); toc; % Bruno's

isequalwithequalnans(A,B); % always verified
end

Elapsed time is 0.001306 seconds.
Elapsed time is 0.001084 seconds.

Elapsed time is 0.033996 seconds.
Elapsed time is 0.008017 seconds.

Elapsed time is 0.232533 seconds.
Elapsed time is 0.028339 seconds.

Elapsed time is 0.714834 seconds.
Elapsed time is 0.063467 seconds.

Elapsed time is 1.705921 seconds.
Elapsed time is 0.077690 seconds.

Elapsed time is 2.787658 seconds.
Elapsed time is 0.166200 seconds.

Elapsed time is 4.025173 seconds.
Elapsed time is 0.222698 seconds.

Elapsed time is 6.259864 seconds.
Elapsed time is 0.259810 seconds.

Elapsed time is 9.305980 seconds.
Elapsed time is 0.376411 seconds.

And the winneeeeeerrr is BRUNO!

I tried to implement a solution with accumarray but as i wrote in the firt post but could't accomplish what u did.