recursion - how to make double for loops faster in R -
i trying below calculation using r. function recursive , uses double loop calculate values of "result" matrix. there method replace loops or achieve if condition faster?
x<-rnorm(2400,0, 3) y<-rnorm(400,0,3) no_row<-length(x) no_col<-length(y) input<-matrix(data=1,nrow = no_row, ncol = no_col) result<-matrix(nrow = no_row, ncol = no_col) calculation<-function(x,y) { for(i in 1:no_row) { for(j in 1:no_col) { z<-exp(x[i]-y[j]) result[i,j]<-(z/1+z) } } new_x<-x-1 new_y<-y-1 residual<-input-result sq_sum_residulas<-sum((rowsums(residual, na.rm = t))^2) if(sq_sum_residulas>=1){calculation(new_x,new_y)} else(return(residual)) } output<-calculation(x,y)
the outer
function tool looking for.
compare these 2 functions generate result
matrix
x<-rnorm(100,0, 3) y<-rnorm(100,0,3) calculation<-function(x,y) { result <- matrix(nrow = length(x), ncol = length(y)) for(i in seq_along(x)) { for(j in seq_along(y)) { z<-exp(x[i]-y[j]) result[i,j]<-(z/1+z) } } result } calculation2 <- function(x, y){ result <- outer(x, y, function(x, y) { z <- exp(x - y); z / 1 + z}) result } library(microbenchmark) microbenchmark( calculation(x, y), calculation2(x, y) ) unit: microseconds expr min lq mean median uq max neval calculation(x, y) 1862.40 1868.119 1941.5523 1871.490 1876.1825 8375.666 100 calculation2(x, y) 466.26 469.192 515.3696 471.392 480.9225 4481.371 100
that discrepancy in time seems grow length of vectors increases.
note, solve speed double for
loop, there seem other issues in function. isn't clear me trying do, or why calling calculation
within itself. have written, there no changes x
, y
before gets calling again, stuck in loop forever, if worked @ (it doesn't on machine)
Comments
Post a Comment