【问题标题】:Subtraction two vectors in Matlab [duplicate]Matlab中的两个向量相减[重复]
【发布时间】:2012-11-17 14:27:16
【问题描述】:

可能重复:
MATLAB: Matrix of differences

我不知道如何表达这个问题,但我会尽力而为:

我有两个向量,AB

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

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

结果矩阵应该是length(A) x length(B),看起来像这样:

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

有没有什么方法可以在没有循环的情况下做到这一点?

【问题讨论】:

  • 链接的副本是从A 中减去A。从A 中减去B 应该很容易计算出来。
  • 昨天我对同一个问题的回答完全正确Here.

标签: matlab vector matrix subtraction


【解决方案1】:

像@Memming 和@Jonas 这样的行说:

Result = bsxfun(@minus, a, b');

【讨论】:

  • 感谢他的优化。它更快。
【解决方案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

【讨论】:

  • @Memming ... 以及更高效的内存
  • bsxfun 不允许使用用sym..声明的变量。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-09
  • 1970-01-01
相关资源
最近更新 更多