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
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,`+`)
We can also use sapply
sapply(u, `+`, v)