Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: How to avoid for loops in 3 vector function.
Date: Mon, 2 May 2011 23:31:05 +0000 (UTC)
Organization: The MathWorks, Inc.
Lines: 62
Message-ID: <ipnerp$5qk$1@fred.mathworks.com>
References: <ipmluu$l21$1@fred.mathworks.com> <ipms3s$mcs$1@fred.mathworks.com> <ipnbu0$ku2$1@fred.mathworks.com>
Reply-To: <HIDDEN>
NNTP-Posting-Host: www-02-blr.mathworks.com
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1304379065 5972 172.30.248.47 (2 May 2011 23:31:05 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Mon, 2 May 2011 23:31:05 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 2799711
Xref: news.mathworks.com comp.soft-sys.matlab:724874

"Lan" wrote in message <ipnbu0$ku2$1@fred.mathworks.com>...
> Thanks! I did what you suggested, put most of the code outside the loop and create a t_ temp. But the code still runs very slowly.... Is there another way to avoid the loop completely? 
> 
> "Florin Neacsu" wrote in message <ipms3s$mcs$1@fred.mathworks.com>...
> > "Lan" wrote in message <ipmluu$l21$1@fred.mathworks.com>...
> > > I have a problem with a function Sn(M0, V0, v, b). M0, V0 are 2000x1 given vectors. I want to maximize Sn over b, for each different v belonging to V0.
> > > 
> > > V0, M0, Y are n x 1 vectors (n=2000)
> > > 
> > > for i=1:length(V0)
> > >     v=V0(i);
> > >     b = (-3:0.01:3);
> > >     l = length(b);
> > >     vec0 = 2*Y - ones(n,1);% n x 1 vector
> > >     mV0=repmat(V0,1,l); % n x n matrix
> > >     t=repmat(M0, 1, l)+v*ones(n, l)+repmat(b,n,1); % n x l matrix
> > >     vec1=(t./h+0.5*ones(n,l)).*(abs(t./h) <= 0.5) +((t./h) > 0.5); % n x l matrix
> > >     vec2=(abs((mV0 - v*ones(n,l))/h)<=0.5); % n x l matrix
> > >     sn0=vec0'*(vec1.*vec2);
> > >     sn=1/(n*h)*sn0; % 1 x l array
> > >     p = find(sn>=max(sn));
> > >     betaH(i)=b(p(1));
> > > end
> > > 
> > > This runs very slowly. How do I vectorize the loop? Or is there any other way to make the function run faster?
> > 
> > Hello,
> > 
> > There are many operations you could pull out of the for loop :
> > 
> > 
> > >     b = (-3:0.01:3);
> > >     l = length(b);
> > >     vec0 = 2*Y - ones(n,1);% n x 1 vector
> > >     mV0=repmat(V0,1,l); % n x n matrix
> > 
> > and also
> > 
> > >t=repmat(M0, 1, l)+v*ones(n, l)+repmat(b,n,1); % n x l matrix
> > 
> > only uses the v, so you could do (ouside the for loop) something like
> > 
> > >t_temp=repmat(M0, 1, l)+)+repmat(b,n,1); 
> > >my_ones=ones(n,l);
> > 
> > and inside the loop 
> > 
> > >t=t_temp+v*my_ones;
> > 
> > Try changing these lines and see if it gets fast enough for your needs.
> > 
> > Regards,
> > Florin

Hi,

Have you tried using profiler to identify the botlenecks ? 

Another solution would be to tell us what you are trying to do and maybe someone could suggest a different approach.

Regards,
Florin