Reputation: 25
I'm trying to create a loop so I can create 1000 random 2x2 matrices (in the range between -10 to 10)
so far I have
M = matrix(c(z = runif(4,min = -10, max = 10)),
nrow = 2, ncol = 2, byrow = TRUE)
I tried to use k=1000
for (i in 1:k) {
if (i>=0) print (i) else (print(-i)
}
Upvotes: 0
Views: 177
Reputation: 11981
You don't need for.loops to achieve that.
You can do so by using lapply
. This way you create a list containing the matrices:
set.seed(1)
lapply(1:3, function(z) matrix(runif(4, min = -10, max = 10), nrow = 2, ncol = 2))
[[1]]
[,1] [,2]
[1,] -4.689827 1.457067
[2,] -2.557522 8.164156
[[2]]
[,1] [,2]
[1,] -5.966361 8.893505
[2,] 7.967794 3.215956
[[3]]
[,1] [,2]
[1,] 2.582281 -5.880509
[2,] -8.764275 -6.468865
In order to create 1000 matrices use 1:1000
instead of 1:3
.
If you insist on using a loop you can use Markus' solution from the comments:
k <- 1000
out <- vector("list", length = k)
set.seed(1)
for (i in 1:k) {
out[[i]] <- matrix(runif(4, min = -10, max = 10), nrow = 2, ncol = 2)
}
out
Upvotes: 1