MATLAB: Is it possible to speed up this loop or avoid from using

for loopperformancespeed

I give an example code below including 4 loops. How can I speed up this procedure? thanks for any help and ideas.
clc;clear all
%%inputs
dx=1; dy=1; xo=5;
f1=5;
f2=10;
f3=15;
kx=1:50;
ky=1:50;
k=rand(50,50);
z=rand(50,50);
%%%
%%%% how can I improve this example below for running faster ?
tic
for j=1:50
for i=1:50
total=0;
for m=1:50
beta= (m-1)*dy;
for n=1:50
alpha= (n-1)*dx;
f4 =(1-exp(-(xo+ 2.*pi.*k(j,i)).*z(m,n)));
f5 = exp(-2.*pi.*(kx(i).*alpha + ky(j).*beta));
total = total+ f1.*f2.*f3.*f4.*f5;
end
end
L(j,i)=total;
end
end
toc

Best Answer

  • dx=1; dy=1; xo=5;
    f1=5;
    f2=10;
    f3=15;
    kx=1:50;
    ky=1:50;
    k=rand(50,50);
    z=rand(50,50);
    %%%
    ky=ky(:);
    z=reshape(z,[1,1,size(z)]);
    alpha=reshape((0:49)*dx,1,1,1,[]);
    beta=reshape((0:49)*dy,1,1,[]);
    f4 = (1-exp(-(xo+ 2.*pi.*k).*z));
    f5 = exp(-2.*pi.*(kx.*alpha + ky.*beta));
    L=(f1.*f2.*f3).*sum( sum( f4.*f5, 3) ,4);