Reputation: 14614
I would like to create a matrix of n x n dimension, with the values
f = matrix(0,n,n)
for (x in (1:n)) {
for (y in (1:n)) {
f[x,y] = x^2 + y^2
}
}
Is there a way to vectorize this (to avoid the two loops) to speed the program?
Upvotes: 0
Views: 129
Reputation: 18437
You can use outer
outer(x, y, function(x, y) x^2 + y^2)
For example
x <- 1:4
y <- 2:5
outer(x, y, function(x, y) x^2 + y^2)
[,1] [,2] [,3] [,4]
[1,] 5 10 17 26
[2,] 8 13 20 29
[3,] 13 18 25 34
[4,] 20 25 32 41
Upvotes: 6
Reputation: 5955
What about this?
n <- 10
M <- matrix(rep(1:n,n), ncol=n, byrow=T)
f <- (M**2)+t((M**2))
f
Upvotes: 1