How to Add a row vector to a column vector like matrix multiplication

前端 未结 3 684
自闭症患者
自闭症患者 2021-01-24 01:44

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:



        
相关标签:
3条回答
  • 2021-01-24 01:54

    You can use the repmat function (replicate matrices):

    repmat(A,1,3)+repmat(B,3,1)
    
    0 讨论(0)
  • 2021-01-24 01:56

    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

    0 讨论(0)
  • 2021-01-24 02:09

    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
    
    0 讨论(0)
提交回复
热议问题