在Matlab中减去两个向量

时间:2012-11-17 14:27:16

标签: matlab vector matrix subtraction

  

可能重复:
  MATLAB: Matrix of differences

我不确定如何说出这个问题,但我会尽我所能:

我有两个向量,AB

我想按A的每个值减去B中的所有值。

例如,A中的所有值都会被B的第一个值减去。然后将A的所有值减去B的第二个值,依此类推。

结果矩阵应为length(A) x length(B),如下所示:

Ans = [A - B(1); A - B(2); A - B(3); ....... ]

如果没有循环,有没有办法做到这一点?

2 个答案:

答案 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