MATLAB: Norm of the difference of each row of two matrices of different dimensions

differencenorm

Hello, I have two matrices A and B of dimensions m-by-3 and n-by-3 respectively where n < m (they are basically RGB values of an image). For sake of simplicity assume m = 8 and n = 4. For each row in m, I need to calculate the the norm of the difference of that row with the each row of n. The way I am doing it now is using a nested for loop, but my m and n are way higher. So this is taking forever to run. I was wondering if there is any other efficient way to do it.
Just for the sake of completion here is my code for performing this operation:
for i = 1:size(m, 1)
for j = 1:size(n, 1)
d(j, 1) = norm(m(i, 1) - n(j, 1))
end
% I do some stuff with d here, but its not important to the
question.
end
Thanks.

Best Answer

Did you properly pre-allocate d before the loop? This would be your largest time killer if not...
Also, your example loops don't look like what you described. You are only storing the value of the norm for the final value of i. Also, I thought you were doing this by rows, yet you are only calculating the norm of the difference between two scalars. Your verbal description sounds more like this:
m = 8;
n = 4;
A = round(rand(m,3)*10);
B = round(rand(n,3)*10);
cnt = 1;
d = zeros(32,1); % Pre-allocate d
for ii = 1:m
for jj = 1:n
d(cnt) = norm(A(ii,:) - B(jj,:)) ;
cnt = cnt + 1;
end
end
If not, please modify this example and/or your description. Perhaps you are not meaning to store all of the norms? But then why only use the first column when you said you were using rows?
.
.
EDIT
O.k., So if your original code looks like this:
for ii = 1:m
for jj = 1:n
d(jj, 1) = norm(A(ii, :) - B(jj, :)) ;
end
end
Then this is much faster:
t = ones(1,size(B,1),'single'); % Use as an index into A
for ii = 1:m
Ar = A(ii,:);
d = sqrt(sum((Ar(t,:) - B).^2,2));
end