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 18:11:08 +0000 (UTC)
Organization: The MathWorks, Inc.
Lines: 49
Message-ID: <ipms3s$mcs$1@fred.mathworks.com>
References: <ipmluu$l21$1@fred.mathworks.com>
Reply-To: <HIDDEN>
NNTP-Posting-Host: www-06-blr.mathworks.com
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1304359868 22940 172.30.248.38 (2 May 2011 18:11:08 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Mon, 2 May 2011 18:11:08 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 2799711
Xref: news.mathworks.com comp.soft-sys.matlab:724829

"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