这是一个循环解决方案和一个repmat解决方案。
% 定义一些示例数据。
Edit: a and b are column vectors, not row vectors.
a = [ 1:10 ]';
b = [ 6:10 ]'; % 5:10 has vertical size of 6, not 5, so to match the question 6:10 is used.
First, the very basic loop solution: loop through all aIndex,bIndex pairs, subtract the difference of elements addressed by aIndex and bIndex and store the result in LoopDifferenceMatrix(aIndex, bIndex).
for aIndex = 1:size(a,1)
for bIndex = 1:size(b,1)
LoopDifferenceMatrix(aIndex, bIndex) = a(aIndex) - b(bIndex);
end
end
This is an alternative repmat solution. Replicate a horizontally by using repmat so that its horizontal size matches size(b,1) (the horizontal size of b). Then replicate transposed b vertically by using repmat so that its vertical size matches size(a,1) (the original horizontal size of a). Subtract replicated a from replicated b and store the result in DifferenceMatrix.
DifferenceMatrix = repmat(a, 1, size(b,1)) - repmat(b', size(a,1), 1);
DifferenceMatrix =
-5 -6 -7 -8 -9
-4 -5 -6 -7 -8
-3 -4 -5 -6 -7
-2 -3 -4 -5 -6
-1 -2 -3 -4 -5
0 -1 -2 -3 -4
1 0 -1 -2 -3
2 1 0 -1 -2
3 2 1 0 -1
4 3 2 1 0
isequal(DifferenceMatrix, LoopDifferenceMatrix)
ans =
1