MATLAB: Summing without nested loops

nested loopsperformancespeed

I have the following code which has 6 for loops to obtain a sum. I was wondering if the sum can be done without the use for loops, since they are very slow in matlab. (Something like vectorizing)
function ts=Tes(i,j,k,l,m,n,x)
ts=beselj(i-j,x)*besselj(j-k,x)*besselj(k-l,x)*besselj(l-m,x)*besselj(l-n,x);
end
function ds=Ds(x)
dds=0;
for i=1:21
for j=1:21
for k=1:21
for l=1:21
for m=1:21
for n=1:21
dds=dds+Tes(i,j,k,l,m,n,x);
end
end
end
end
end
ds=dds;
end
Thanks in advance!

Best Answer

The loops are still there, but this is significantly faster.
Comments:
  1. The calculation of besselj() dominated the use of time.
  2. besselj() was called with the same arguments many times
  3. The calls of Tes() themself (the function call overhead) used a significantly amount of time
  4. profile() isn't very useful for this code
  5. The line ds=dds; overwrote ds for each value of i
  6. besselj(l-n,x) shouldn't that be besselj(m-n,x) ?
function ds=Ds(x)
dds=0;
ds = nan(21,1);
hashtable = besselj((-20:20),x);
for i=1:21
for j=1:21
for k=1:21
for l=1:21
for m=1:21
for n=1:21
dds = dds + hashtable(i-j+21)...
* hashtable(j-k+21)...
* hashtable(k-l+21)...
* hashtable(l-m+21)...
* hashtable(l-n+21);
end
end
end
end
end
ds(i,1) = dds;
dds = 0;
end
end
Speed test
>> tic, ds = Ds( 0.3 ); toc
Elapsed time is 0.194939 seconds.
>> tic, ds = Ds( 0.6 ); toc
Elapsed time is 0.172967 seconds.
"since they [loops] are very slow in matlab" That is not always true. In this case the JIT-compiler does a good job.
Comparison with original code
The code of my answer (Ds.m) is two thousand times faster than the original code (DsSlow.m) and the two return identical results.
>> tic, ds_slow = DsSlow( 0.6 ); toc
Elapsed time is 393.114152 seconds.
>> tic, ds = Ds( 0.6 ); toc
Elapsed time is 0.175559 seconds.
>> (ds-ds_slow)'
ans =
Columns 1 through 14
0 0 0 0 0 0 0 0 0 0 0 0 0 0
Columns 15 through 21
0 0 0 0 0 0 0
>>
where
function ds = DsSlow(x)
dds=0;
ds = nan(21,1);
for i=1:21
for j=1:21
for k=1:21
for l=1:21
for m=1:21
for n=1:21
dds = dds + Tes(i,j,k,l,m,n,x);
end
end
end
end
end
ds(i,1) = dds;
dds = 0;
end
end
function ts = Tes(i,j,k,l,m,n,x)
ts = besselj(i-j,x)*besselj(j-k,x)*besselj(k-l,x)*besselj(l-m,x)*besselj(l-n,x);
end