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