MATLAB: Avoiding unnecessary for loops

for loophomeworkmemory

How do I do this without the loops in a few lines?
S = zeros(100,100);
sig = 0.05;
for i = 1:100
for j = 1:100
S(i,j) = exp(-norm(D(i,:)-D(j,:),'fro')/sig);
end
end

Best Answer

These are a few lines already. The mos expensive is the exp call, so you save the most time with using the symmetry (as mentioned by Jos already):
S = zeros(100,100);
sig = 0.05;
for i = 1:100
for j = i+1:100
S(i,j) = exp(-norm(D(i,:) - D(j,:)) / sig);
S(j,i) = S(i,j);
end
end
You can try if it is faster to replace norm by:
for i = 1:100
v = D(i, :);
for j = i+1:100
w = v - D(j, :);
S(i,j) = exp(-sqrt(w * w.') / sig);
S(j,i) = S(i,j);
end
end
Operating on columns is faster than on rows:
DT = D.';
for i = 1:100
v = DT(:, i);
for j = i+1:100
w = v - DT(:, j);
S(i,j) = exp(-sqrt(w.' * w) / sig);
S(j,i) = S(i,j);
end
end
Please post the timings you get.
Related Question