|
"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
|