fun1 <- function(x,y) {
mat <- matrix(1:20, ncol=5)
mat[1:x, 1:y] <- rnorm(x*y)
mat
}
This will achieve your goal of creating a function that accepts indices as two arguments and returns a matrix with random normally distributed numbers by the index.
fun1(2,1)
# [,1] [,2] [,3] [,4] [,5]
#[1,] -0.2883407 5 9 13 17
#[2,] -0.5290704 6 10 14 18
#[3,] 3.0000000 7 11 15 19
#[4,] 4.0000000 8 12 16 20
Note that the last line is returned when the function is called.
The mat
matrix created in the function is not available in the Global environment:
mat
#Error: object 'mat' not found
Whenever you write a nested for
loop as a new user of R, alarm bells should go off. There is usually a better way. The advantage of the nested loop is that it "makes sense." But the clear logical progression turns out to be very inefficient in execution. There are exceptions of course, but you will most likely not run into them any time soon. It is better to take the time to learn R's programming intuition.
There are many discussions of scoping for study:
R environments and function call stacks
Scoping and functions in R 2.11.1 : What's going wrong?
http://developer.r-project.org/nonstandard-eval.pdf
http://adv-r.had.co.nz/Functions.html#lexical-scoping