Reputation: 69
I am trying to compute the L2 condition number of 1000 matrices. However, I am doing this for matrices of different dimensions. For instance, I am computing the L2 condition number for 1000 5x5 matrices, then doing the same thing again but for 10x10 matrices and so on.
I have already finished the problem, but the issue here is that I have 5 for loops that do the same thing. I know I can simplify my code via a nested for loop, but I'm not sure how to go about doing so. I've attached my code below.
Please note that the numbers are randomly generated with respect to the dimensions of the matrices.
#Set up for loops
set.seed(2019)
CN5 <- NULL
CN10 <- NULL
# First for loop for n = 5
## n = 5
for(i in 1:1000){
CN5[i] <- kappa(matrix(rnorm(25), nrow = 5))
}
mean(CN5)
sd(CN5)
median(CN5)
#Second for loop with n = 10
## n = 10
for(i in 1:1000){
CN10[i] <- kappa(matrix(rnorm(100), nrow = 10))
}
mean(CN10)
sd(CN10)
median(CN10)
How do I combine these loops so that I only have one?
Upvotes: 0
Views: 93
Reputation: 750
The general procedure, as suggested in the comments, is to write a function with arguments that take into account what is (or could) vary between different iterations.
From your code, the only thing that is varying is the dimension of square matrices n x n
.
set.seed(2019)
cn_function <- function(n) {
for(i in 1:1000) {
CN_n[i] <- kappa(matrix(rnorm(n^2), nrow = n))
}
# Return a list with the desired results
list(n = n, # Store n for good measure
cn_n = CN_n,
mean = mean(CN_n),
median = median(CN_n),
sd = sd(CN_n))
}
Then, if you have p.e. 1000 matrices 5x5 and 1000 matrices 10x10 you could store the results in another list results
, for example.
matrices_n <- c(5, 10) # or any number of `n`
results <- list()
for(i in seq_along(matrices_n)) {
results[[i]] <- cn_function(n = matrices_n[i])
}
Or using the awesome purrr
package instead of for
loops:
cn_function <- function(n) {
CN_n <- purrr::map_dbl(1:1000, ~kappa(matrix(rnorm(5^2), nrow = 5)))
# Return a list with the desired results
list(n = n, # Store n for good measure
cn_n = CN_n,
mean = mean(CN_n),
median = median(CN_n),
sd = sd(CN_n))
}
matrices_n <- c(5, 10)
results <- purrr::map(matrices_n, cn_function)
You can then access the values from the list like results[[1]]$mean
or something like that depending what you are gonna do with the results.
Upvotes: 1
Reputation: 20473
It looks like you could just put these in the same loop:
for(i in 1:1000){
CN5[i] <- kappa(matrix(rnorm(25), nrow = 5))
CN10[i] <- kappa(matrix(rnorm(100), nrow = 10))
}
Per the comment, you could consider a function:
get_kappa <- function(n = 25, nrow = 5) {
return(kappa(matrix(rnorm(n), nrow = nrow)))
}
for(i in 1:1000){
CN5[i] <- get_kappa(n = 25, nrow = 5)
CN10[i] <- get_kappa(n = 100, nrow = 10)
}
Upvotes: 1