Hello Jesujoba,
it looks like A and B must have the same number of columns but can have a different number of rows. The for-loop method and the repmat method (below) agree, although for the integer data I used, repmat is exact but for-loop has some tiny numerical blips. That's because in for-loop, norm takes a square root and you square that out again.
For loops aren't all bad. Repmat may be faster and more efficient when A and B are large, but with for-loop the intent is clearer from just looking at the code. Repmat would require annotation to even know what its task is.
If there are 10 columns and A and B each have 100 rows, then on my PC the calculation by for-loop takes about 140 millisec. Not bad. For 800 rows, for-loop takes less than a sec. Repmat in that case comes in at about .05 sec, and while it can be a point of pride to make things faster, speed and vectorization aren't everything.
To me one of the biggest values of the repmat method is not speed, but as a particular example of messing around with matrices in Matlab. For a small matrix like in this problem, taking out the semicolons on each line illustrates the process.
ca = 2;
cb = ca;
ra = 3;
rb = 2;
A = randi(10,ra,ca);
B = randi(10,rb,cb);
clear C
for i = 1:ra
for j = 1:rb
C(i,j) = (norm(A(i,:)-B(j,:)))^2;
end
end
Arep = repmat(A,rb,1);
Brep = repmat(B',ra,1);
Brep = reshape(Brep,ca,[])';
Cvals = (Arep-Brep).^2;
C2 = sum(Cvals,2);
C2 = reshape(C2,ra,rb);
C
C2
Best Answer