Path: news.mathworks.com!not-for-mail
From: "Steven Lord" <slord@mathworks.com>
Newsgroups: comp.soft-sys.matlab
Subject: Re: can I avoid a loop here?
Date: Tue, 19 Feb 2008 13:10:43 -0500
Organization: The MathWorks, Inc.
Lines: 38
Message-ID: <fpf633$8eb$1@fred.mathworks.com>
References: <e01a38fc-431a-415f-9162-8e7ad7a422c0@q33g2000hsh.googlegroups.com>
Reply-To: "Steven Lord" <slord@mathworks.com>
NNTP-Posting-Host: lords.dhcp.mathworks.com
X-Trace: fred.mathworks.com 1203444643 8651 144.212.105.187 (19 Feb 2008 18:10:43 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Tue, 19 Feb 2008 18:10:43 +0000 (UTC)
X-Priority: 3
X-MSMail-Priority: Normal
X-Newsreader: Microsoft Outlook Express 6.00.2900.3138
X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2900.3198
X-RFC2646: Format=Flowed; Original
Xref: news.mathworks.com comp.soft-sys.matlab:452452




"Ross" <fed.rossi@gmail.com> wrote in message 
news:e01a38fc-431a-415f-9162-8e7ad7a422c0@q33g2000hsh.googlegroups.com...
> Hi,
> I face the following problem:
>
> Let j and x be two vectors of same length.
> I would like to apply function FUN to the subset of xs, where the
> subset is defined by the index j.
>
> --------------
> Eg:
>
> j = [1 2 2 2 3 3]'
> x = [6 43 3 4 2 5]'
>
> FUN is sum
>
> the result wanted is [6 50 7]'
> -----------------
>
> Is there a way to avoid looping?

>> j = [1; 2; 2; 2; 3; 3];
>> x = [6; 43; 3; 4; 2; 5];
>> M = accumarray([j ones(size(j))], x)

M =

     6
    50
     7

-- 
Steve Lord
slord@mathworks.com