[R] Why R is 200 times slower than Matlab ?
Erik Iverson
iverson at biostat.wisc.edu
Wed Apr 30 22:56:37 CEST 2008
Zhandong Liu wrote:
> I am switching from Matlab to R, but I found that R is 200 times slower than
> matlab.
>
> Since I am newbie to R, I must be missing some important programming tips.
The most important tip I would give you is to use the vectorized nature
of R whenever possible. This helps avoid messy indexing and 'for' loops.
Look at the following 3 functions. Yours, Gabor's, and my own (which I
was about to post when I saw Gabor's nice solution, and is basically the
same).
Also see the system timings after the definitions.
grw_permute <- function(input_fc){
fc_vector <- input_fc
index <- 1
k <- length(fc_vector)
fc_matrix <- matrix(0, 2, k^2)
for(i in 1:k){
for(j in 1:k){
fc_matrix[index] <- fc_vector[i]
fc_matrix[index+1] <- fc_vector[j]
index <- index + 2
}
}
return(fc_matrix)
}
grw.permute2 <- function(v) {
cbind( rep(v, each=length(v)), rep(v, length(v)) )
}
grw_permute3 <- function(input_fc) {
matrix(c(rep(input_fc, each = length(input_fc)),
rep.int(input_fc, times = length(input_fc))),
nrow = 2, byrow = TRUE)
}
> system.time(p1 <- grw_permute(1:300))
user system elapsed
1.548 0.064 2.341
> system.time(p2 <- grw_permute2(1:300))
user system elapsed
0.009 0.001 0.010
> system.time(p3 <- grw_permute3(1:300))
user system elapsed
0.008 0.002 0.010
Erik Iverson
More information about the R-help
mailing list