我不确定如何说出这个问题,但我会尽我所能:
我有两个向量,A
和B
。
我想按A
的每个值减去B
中的所有值。
例如,A
中的所有值都会被B
的第一个值减去。然后将A
的所有值减去B的第二个值,依此类推。
结果矩阵应为length(A) x length(B)
,如下所示:
Ans = [A - B(1); A - B(2); A - B(3); ....... ]
如果没有循环,有没有办法做到这一点?
答案 0 :(得分:3)
像@Memming和@Jonas这样的界线说:
Result = bsxfun(@minus, a, b');
答案 1 :(得分:2)
a=[2 3 4]; %first take two vector a and b of any size
b=[5 6 5 7];
m=size(a); % Then Calculate the size of the vectors
n=size(b);
r1=a'*ones(n); % replicate the vector a and b one can use **repmat** here for replication
r2=ones(m)'*b; % like **repmat(a',n) & repmat(b,m(end),1)**
Result=r1-r2
Result =
-3 -4 -3 -5
-2 -3 -2 -4
-1 -2 -1 -3