Populating a matrix of function evaluations in R without for-loop
for-loop, matrix, r
Solution
Use the `outer` function:
> outer(x,x,"^")
[,1] [,2] [,3] [,4] [,5]
[1,] 0.9549926 0.6309573 1e-02 1e-20 1e-200
[2,] 0.9772372 0.7943282 1e-01 1e-10 1e-100
[3,] 1.0000000 1.0000000 1e+00 1e+00 1e+00
[4,] 1.0232930 1.2589254 1e+01 1e+10 1e+100
[5,] 1.0471285 1.5848932 1e+02 1e+20 1e+200
> identical(M,outer(x,x,"^"))
[1] TRUE
You can use a function name or the quoted name of an operator. Note also I test that the answer from `outer` is the same as that from your loop. Always test!
Problem
I'd like to generate a matrix whose values are evaluations of a function which has two arguments. So far, the following does what I want, but I suspect that there is a nicer way to do this in R, without using the `for` loops. ``` x <- c(0.01, 0.1,1,10,100) n <- length(x) M <- matrix(NA, nrow=n, ncol=n) for (i in 1:n){ for (j in 1:n){ M[i,j]<-x[i]^x[j] } } ```