How to Add a row vector to a column vector like ma

2019-03-03 20:12发布

问题:

I have a nx1 vector and a 1xn vector. I want to add them in a special manner like matrix multiplication in an efficient manner (vectorized):

Example:

A=[1 2 3]'

B=[4 5 6]

A \odd_add B = 
[1+4 1+5 1+6
 2+4 2+5 2+6
 3+4 3+5 3+6
]

Regards

回答1:

You can use bsxfun:

A=[1 2 3]'

B=[4 5 6]

bsxfun(@plus, A, B)

The result is

ans =

     5     6     7
     6     7     8
     7     8     9


回答2:

You can use the repmat function (replicate matrices):

repmat(A,1,3)+repmat(B,3,1)