r - For loops to create symmetric matrices -


i want reduce time , memory usage (i used outer consumes more memory have) reducing iterations create symmetric matrix, sol[i, j] same sol[j, i].

my code far:

# prepare input subss <- list(a = c(1, 2, 4), b = c(1, 2, 3), c = c(4, 5)) <- matrix(runif(25), ncol = 5, nrow = 5) # pre allocate memory sol <- matrix(nrow = length(subss), ncol = length(subss),            dimnames = list(names(subss), names(subss)))  x <- 0 (i in seq_along(subss)) {     # omit subsets calculated ?     (j in seq_along(subss)) {         x <- x + 1         message(x)          # function use here might result in na         sol[i, j] <- mean(a[subss[[i]], subss[[j]]])          sol[j, i] <- sol[i, j] # overwrite when shouldn't     } } 

will use 9 iterations, how can avoid them , 6 iterations?

i need calculate symmetric values, this question doesn't apply. other one doesn't work either because there might many combinations , @ point can't allocate vector in memory.

a for loop slower outer. try byte-compiling loop or implement in rcpp.

subss <- list(a = c(1, 2, 4), b = c(1, 2, 3), c = c(4, 5)) set.seed(42) <- matrix(runif(25), ncol = 5, nrow = 5)  #all combinations of indices ij <- combn(seq_along(subss), 2)  #add = j ij <- matrix(c(ij, rep(seq_along(subss), each = 2)), nrow = 2)  #preallocate res <- numeric(ncol(ij))  #only 1 loop (k in seq_len(ncol(ij))) {      message(k)      res[k] <- mean(a[subss[[ij[1, k]]], subss[[ij[2, k]]]])  } #1 #2 #3 #4 #5 #6  #create symmetric sparse matrix     library(matrix) sol <- sparsematrix(i = ij[1,], j = ij[2,],                     x = res, dims = rep(length(subss), 2),                      symmetric = true, index1 = true) #3 x 3 sparse matrix of class "dscmatrix" #                                   #[1,] 0.7764715 0.6696987 0.7304413 #[2,] 0.6696987 0.6266553 0.6778936 #[3,] 0.7304413 0.6778936 0.5161089 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -