Reputation: 33
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 first row of this matrix is the sum of the first element of vector 1 and the first element of vector 2; the second element of the first row is the sum of the first element of vector 1 and the second element of vector 2 and so on.
For example, with these two vectors
u <- c(1,2,3)
v <- c(4,5,6)
The desired result would be:
# [,1] [,2] [,3]
# [1,] 5 6 7
# [2,] 6 7 8
# [3,] 7 8 9
What I have tried:
A <- matrix( c(1:6), 3, 3 )
for(i in 1:3)
{
for(j in 1:3)
{
A[j][i] <- u[i]+v[j]
}
}
But I get some warnings:
Warning messages:
1: In A[j][i] <- u[i] + v[j] :
number of items to replace is not a multiple of replacement length
2: In A[j][i] <- u[i] + v[j] :
number of items to replace is not a multiple of replacement length
3: In A[j][i] <- u[i] + v[j] :
number of items to replace is not a multiple of replacement length
4: In A[j][i] <- u[i] + v[j] :
number of items to replace is not a multiple of replacement length
5: In A[j][i] <- u[i] + v[j] :
number of items to replace is not a multiple of replacement length
6: In A[j][i] <- u[i] + v[j] :
number of items to replace is not a multiple of replacement length
Can anybody help me?
Upvotes: 3
Views: 1857
Reputation: 13363
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,`+`)
Upvotes: 7