MATLAB: Compare two matrices (different number of rows, same number of columns)

compare matrices

Hello!
Please help me solve the following issue!
I have two matrices: A size m x k and B size n x k (same the number of columns k).
I want to create a matrix T size m x n such that each element T(i,j) is computed by the sum of the min values of each pair A(i,p) and B(j,p), p = 1..k.
For example:
A = [1 2 2; 0 1 2; 0 2 3; 1 0 2];
B = [2 2 0; 3 0 1; 0 2 1];
[m,k] = size(A);
[n,k] = size(B);
for i = 1:m
for j = 1:n
temp = 0;
for p = 1:k
temp = temp + min(A(i,p),B(j,p));
end
T(i,j) = temp;
end
end
From the code, we have T(2,3) = 2 (sum min of elements from row 2 in A and row 3 in B by column)
The code is fine when m,n,k is small.
However, as there are 3 for loops in the code, when m,n and k are large (around >3000), it takes a long time and even could not release a result. I spent time searching but still could not find a suitable function or another way to remove the for loop and improve the code. I really need and appreciate your helps!
Thank you so much!
Khanh

Best Answer

This gave a modest speedup:
T = zeros(m,n);
for i = 1:m
for j = 1:n
T(i,j) = sum(min(A(i,1:k),B(j,1:k)));
end
end
Note that you should always preallocate the memory of an array.