Sum each element of a vector with each element of a second vector

后端 未结 2 1296
忘了有多久
忘了有多久 2021-01-20 16:48

I have two vectors and I want a matrix which elements are the sum of each element of vector 1 and each element of vector 2.

For example, the first element in the firs

相关标签:
2条回答
  • 2021-01-20 17:19

    This is how you would do it (note the matrix subset is not two brackets, but comma separated):

    u <- c(1,2,3)
    v <- c(4,5,6)
    
    A <- matrix( c(1:6), 3, 3 )
    
    for(i in 1:3)
    {
       for(j in 1:3)
       {
          A[i,j] <- u[i]+v[j]
       }
    }
    

    But this is not the way someone who knows R would approach it. In general there are better ways to do things in R than nested for-loops. Another way is:

    A <- outer(u,v,`+`)
    
    0 讨论(0)
  • 2021-01-20 17:20

    We can also use sapply

    sapply(u, `+`, v)
    
    0 讨论(0)
提交回复
热议问题