1. Pre-allocate the output! 2. Relying on LENGTH to reply the wanted dimension is prone to errors. Use SIZE(X, dim) instead.
lenA = size(A, 1);
lenB = size(B, 1);
Y = zeros(lenA, lenB);
for i = 1:lenB
for j = 1:lenA
Y(j,:) = B(i,:) - A(j,:);
end
end
Now the values of Y are overwritten completely in every iteration of the for i loop. Most likely this is not intented. If this problem is fixed, you can try if BSXFUN or manual expansion by ONES is faster instead of the inner loop:
Y = bsxfun(@minus, B(i, :), A);
Bi = B(i, :);
Y = Bi(ones(1, lenA), :) - A;