Path: news.mathworks.com!not-for-mail
From: "Doug Hull" <hull@mathworks.SPAMPROOFcom>
Newsgroups: comp.soft-sys.matlab
Subject: Re: Avoiding loops
Date: Mon, 19 Jan 2009 19:56:01 +0000 (UTC)
Organization: The MathWorks Inc
Lines: 81
Message-ID: <gl2lsh$1cv$1@fred.mathworks.com>
References: <gkkcva$4ka$1@fred.mathworks.com>
Reply-To: "Doug Hull" <hull@mathworks.SPAMPROOFcom>
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 1232394961 1439 172.30.248.35 (19 Jan 2009 19:56:01 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Mon, 19 Jan 2009 19:56:01 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 869436
Xref: news.mathworks.com comp.soft-sys.matlab:512545


This code did not work, but I added 
d= 1;

to the beginning, then it did.

using the profiler,  saw that this line:

>     y(i)=(x(ir,:)-mu)*inv(sigma)*(x(ir,:)-mu)';

was the problem, I did not know what part was slow, so I broke it into a smaller set of lines:

    aaa = (x(ir,:)-mu);
    bbb = inv(sigma);
    ccc = (x(ir,:)-mu)';
    y(i)=aaa*bbb*ccc;

Now, the profiler can see that the bottleneck is on line bbb.

This value never changes, there i no reason to calculated it every time through the nested for loops.

I moved it outside the loops, and cut 50% of the time.

Doug

FINAL CODE:

-------------
d = 1;  
nv=500;
   nx=400;
    x=rand(nx,2); % data 2D
    sigma=cov(x);
    bbb = inv(sigma); %%%%% MOVED
    y=zeros(1,nx);
        

    for j=1:nv % Loop in free parameter mu
    mu= [rand(1,1) rand(1,1)];
    
    for i=1:nx % Loop to calculate the likelihood function (lf)
    ir=round(1+(nx-1)*rand(1,1));
    aaa = (x(ir,:)-mu);

    ccc = (x(ir,:)-mu)';
    y(i)=aaa*bbb*ccc;
    end
    
    lf=0.5*sum(y)+nx*0.5*log((det(sigma)))+nx*0.5*d*log(2.0*pi); % likelihood
    p1(j)=lf;
    end
    p=exp(-sum(p1(j))/nv)
---------------------

"Jose " <jose.l.vega@gmail.com> wrote in message <gkkcva$4ka$1@fred.mathworks.com>...
> Can anyone help me with is: I want to do this code more efficient,
> can I vectorize the first loop of the parameter mu?
> 
> Thanks, 
> 
> Jose.
> 
>    nv=1000;
>    nx=2000;    
>     x=rand(nx,2); % data 2D    
>     sigma=cov(x)
>     y=zeros(1,nx);
>         
> 
>     for j=1:nv  % Loop in free parameter mu
>     mu= [rand(1,1) rand(1,1)]; 
>     
>     for i=1:nx  % Loop to calculate the likelihood function (lf)
>     ir=round(1+(nx-1)*rand(1,1));
>     y(i)=(x(ir,:)-mu)*inv(sigma)*(x(ir,:)-mu)';
>     end
>     
>     lf=0.5*sum(y)+nx*0.5*log((det(sigma)))+nx*0.5*d*log(2.0*pi); % likelihood
>     p1(j)=lf;
>     end    
>     p=exp(-sum(p1(j))/nv)
>