Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: problem vectorizing
Date: Sat, 29 Nov 2008 02:16:01 +0000 (UTC)
Organization: The MathWorks, Inc.
Lines: 30
Message-ID: <ggq8l1$jt9$1@fred.mathworks.com>
References: <ggpuuf$scq$1@fred.mathworks.com>
Reply-To: <HIDDEN>
NNTP-Posting-Host: webapp-02-blr.mathworks.com
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1227924961 20393 172.30.248.37 (29 Nov 2008 02:16:01 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Sat, 29 Nov 2008 02:16:01 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 1187260
Xref: news.mathworks.com comp.soft-sys.matlab:503733


"Zsolt " <zlpst@yahoo.com> wrote in message <ggpuuf$scq$1@fred.mathworks.com>...
> I would like to vectorize the double for loop below, can't find matlab matrix operator to proceed, can anyone help?  Note, current implementation performs the correct operation, it just takes way to long for data size I need to calculate for
> 
> X = linspace(-a/2,a/2,length(Gpp));
> [X Y] = meshgrid(X);
> r = sqrt((X).^2+(Y).^2);
> tic
> ep = zeros(size(Egp));
> 
> for m=1:length(Gpp)
>     for n=1:length(Gpp)
>         ep = ep + Egp(m,n)*exp(i*Gpp(m,n).*r);
>     end
> end

  I presume Gpp, Egp, r, and ep are all square matrices of the same size.  You might conceivably gain a little time by changing the order here and completing the summation within each loop as in:

 ep = zeros(size(Egp));
 for m=1:length(Gpp)
   for n=1:length(Gpp)
     ep(m,n) = sum(sum(Egp.*exp(i*Gpp*r(m,n))));
   end
 end

(or then again this might not help.)

  However, I don't see the need for any further vectorization.  If, as you indicate, these matrices are of large size, the overhead involved in the for-loop indexing should be quite small compared with the time used in the summation, multiplication, and exponentiation computations within each loop period.  I remind you that, as you have written the code, you are dealing here with every possible combination of elements from the matrix r with those of Gpp and Egp, which makes it an order(length(Gpp)^4) procedure and that is bound to take a lot of time for large length(Gpp).  Each doubling of length(Gpp) will multiply the time of execution by a factor of approximately sixteen!  Vectorization is not going to get you around that.

Roger Stafford