Speed up a programme with for loops?

2 次查看(过去 30 天)
Hi, I am working with a program like this:
E0=10
A = zeros(10000,10000);
for k = 1:10000
for j = 1:10000
A(k,j)=E0*exp(-10^(-6.5)*((k-5000)^2+(j-5000)^2));
end
end
for k=1:10:9990
for j=1:10:9990
X=rand*pi;
for h=1:10
for l=1:10
A(k+l-1,j+h-1) = A(k+l-1,j+h-1) *exp(+1i*X);
end
end
end
end
as you can imagine it is very slow, but I can't reduce matrix size and I would like to find a way to speed up the programme, thanks.
one way we can write:
for k=1:10:9990
for j=1:10:9990
X=rand*pi;
for h=1:10
for l=1:10
A(k+l-1,j+h-1)=E0*exp(-10^(-6.5)*((k+l-1-5000)^2+(j+l-1-5000)^2));
A(k+l-1,j+h-1) = A(k+l-1,j+h-1) *exp(+1i*X);
end
end
end
end
That should be the same, are there others?
Moreover I have noticed that if i repeat the programme with a for loop, each cycle is slower than the previous one, how can I overcome this?
Thanks

回答(1 个)

Dana
Dana 2020-10-2
编辑:Dana 2020-10-2
You can vectorize this easily for huge computational savings:
%% Using loops
tic
E0=10;
A = zeros(10000,10000);
for k = 1:10000
for j = 1:10000
A(k,j)=E0*exp(-10^(-6.5)*((k-5000)^2+(j-5000)^2));
end
end
for k=1:10:9990
for j=1:10:9990
X=rand*pi;
for h=1:10
for l=1:10
A(k+l-1,j+h-1) = A(k+l-1,j+h-1) *exp(+1i*X);
end
end
end
end
disp('Using loops:')
toc
%% Vectorizing
tic
E0=10;
N = 10000;
m = 10;
nX = N/m;
XX = pi*rand(nX);
x = ((1:N).'-N/2).^2;
A = E0*exp(-10^(-6.5)*(x+x.'));
krX = kron(exp(1i*XX),ones(m));
A = A.*krX;
disp('Vectorizing:')
toc
which yields output on my machine:
Using loops:
Elapsed time is 11.358504 seconds.
Vectorizing:
Elapsed time is 0.577795 seconds.
By the way, I did the vectorization assuming that using 9990 as the upper bounds for k and j in your second loop structure was an error on your part. With how you did it, the bottom-right 10x10 block of A wouldn't be mutiplied by a random number. If you wanted it to be, you should instead use 9991 (or really any number from 9991 up to 10000) as the upper limits. If, on the other hand, how you had it was how you wanted, then immediately after the line where XX is defined in the vectorization code, you should do XX(nX,nX)=0.
  1 个评论
Alberto Paniate
Alberto Paniate 2020-10-2
编辑:Alberto Paniate 2020-10-2
Thanks, yes huge computational saving.
Regarding the 9990 part, I have seen it and I should use 9991 even if it is not a big deal for my purpose.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by