MATLAB: Avoid for following loops

bsxfunndgrid

Hello everyone,
Can anyone show me how I can avoid following for loops. Thanks!
N1=10;
N2=10;
N3=10;
l1 = 100;
l2 = 100;
t=1;
n1 = [1:10];
n2 = [1:10];
x3 = rand(N3,1);
for ik1=1:N1
for ik2=1:N2
for ix3=1:N3
k1= 2*pi*n1(ik1)/l1;
k2= 2*pi*n2(ik2)/l2;
s = sqrt(k1^2+k2^2);
if s~=0
R11(ik1,ik2,ix3)=1/(exp(s*t)-exp(-s*t))*k1*exp(s*x3(ix3));
end
end
end
end

Best Answer

How about this beauty?
k1 = (2*pi.*n1(1:N1).')./l1;
S=bsxfun(@hypot,k1,2*pi*n2(1:N2)./l2);
P=bsxfun(@(s,ix3)(1./(exp(s.*t)-exp(-s.*t))).*exp(s.*ix3),S,x3(reshape(1:N3,1,1,N3)));
R22 = bsxfun(@times,k1,P);
Check to make sure it's close:
norm(R22(:)-R11(:))
The difference arises because I used hypot in places of sqrt(x^2+y^2), it's a more numerically stable implementation of this.
Also note, that just redoing your for loops with some simple preallocation and calculation rearranging would help a lot.
preallocate R11 before the loop:
R11 = zeros(N1,N2,N3);
And move things that don't change into their respective loops
for ix1 = etc
k1 = etc.
for ix2 = etc.
k2 = etc.
Since k1 and k2 are independent of the inner loops.