1

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

askewchan
  • 45,161
  • 17
  • 118
  • 134
remo
  • 880
  • 2
  • 14
  • 32

3 Answers3

2

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
askewchan
  • 45,161
  • 17
  • 118
  • 134
H.Muster
  • 9,297
  • 1
  • 35
  • 46
  • Thank you, I hope the solution to be fast enough. – remo Jul 27 '12 at 17:55
  • As I have tested it, it's about 6 times slower than regular matrix multiplication. I used exp(A) and exp(B) and multiplied them and then retrieved the special summation using log() function. This approach is more faster!! Can your code be vectorized? – remo Jul 27 '12 at 18:23
  • I disagree with your tests; I find `bsxfun` to be many times faster than matrix multiplication, for all sizes of vector that I tested. This should be the case, as the computational complexity of multiplication is super-linear in the number of matrix elements. – Isaac Jul 27 '12 at 21:27
  • Yes, your answer is theoretically true, but the final speed depends on the implementation. You can redo my test in your machine as below: tic; eA= exp(A); eB = exp(B); result = log(eA*eB); toc; – remo Jul 28 '12 at 02:13
  • @remo: How large where the matrices you did the speed tests with? I have the impression that `bsxfun` outperforms your alternative approach for large matrices (I tested with A and B having 1000 elements each). – H.Muster Jul 28 '12 at 09:08
  • I have tested it on a 1000x1000 matrix!! – remo Jul 28 '12 at 17:19
0

You can use the repmat function (replicate matrices):

repmat(A,1,3)+repmat(B,3,1)
Nathan
  • 1,135
  • 2
  • 12
  • 27
0

From R2016b you can simply do:

A=[1 2 3]'

B=[4 5 6]

A+B

ans =

     5     6     7
     6     7     8
     7     8     9

Matlab will silently expand both vectors and do the element wise sum. This feature has not been without it's controversy. You can check the details here:

Matlab expands arithmetic

David
  • 644
  • 5
  • 4