Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: vectorizing loops
Date: Wed, 3 Nov 2010 00:58:03 +0000 (UTC)
Organization: The MathWorks, Inc.
Lines: 59
Message-ID: <iaqc2r$kri$1@fred.mathworks.com>
References: <iapfjj$6s2$1@fred.mathworks.com>
Reply-To: <HIDDEN>
NNTP-Posting-Host: webapp-05-blr.mathworks.com
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1288745883 21362 172.30.248.35 (3 Nov 2010 00:58:03 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Wed, 3 Nov 2010 00:58:03 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 1187260
Xref: news.mathworks.com comp.soft-sys.matlab:683386

"Gregory Carnegie" <gregorick@hotmail.com> wrote in message <iapfjj$6s2$1@fred.mathworks.com>...
> hello people,
> i'm sort of a novice matlab user at best. however, i have been tasked with optimizing a peice of code:
> 
> for k=1:3
>     for a=1:N
>         disp(['N = ',num2str(a),' done ',num2str(k)])
>         for b=1:N
>             if k==1
>                 s(a,b)=0.;
>             end
>             off(k)=0;
>             if (pos(k,a)<=0.25)
>                 if (pos(k,b)>=0.75)
>                     off(k)=1;
>                 end
>             end
>             if (pos(k,a)>=0.75)
>                 if (pos(k,b)<=0.25)
>                     off(k)=-1
>                 end
>             end
>             s(a,b)=s(a,b)+(pos(k,a)-pos(k,b)+off(k))^2.0;
>             if k==3
>                 s(a,b)=sqrt(s(a,b));
>             end
>         end
>     end
> end
> 
> match=zeros(1,N);
> 
> for a=1:N
>     mindist=1e10;
>     for c=1:N
>         if  (a~=c)
>             mindist=min(s(a,c),mindist);
>             if (mindist==s(a,c))
>                 match(a)=c;
>             end
>         end
>     end
> end
> 
> does anybody know of any books, videos or any sort of media that can help me learn how to do this.
> p.s. i know about preallocation of variables. i am more interested in vectorizing loops.
- - - - - - - - - - - -
  That entire first set of three nested for-loops can be replaced with the following:

 [A,B] = ndgrid(1:N,1:N);
 pA = pos(:,A);
 pB = pos(:,B);
 s = reshape(...
        sqrt(sum((pA-pB+(pA<=.25&pB>=.75)-(pA>=.75&pB<=.25)).^2)) ...
       ,N,N);

A similar reduction can replace the second set of for-loops but I will let you discover it for yourself.  Hint: read the documentation for 'min' carefully.

Roger Stafford