3 ## This example goes back to the following StackOverflow questions:
4 ## http://stackoverflow.com/questions/7153586/can-i-vectorize-a-calculation-which-depends-on-previous-elements
5 ## and provides a nice example of how to accelerate path-dependent
6 ## loops which are harder to vectorise. It lead to the following blog
8 ## http://dirk.eddelbuettel.com/blog/2011/08/23#rcpp_for_path_dependent_loops
10 ## Thanks to Josh Ulrich for provided a first nice (R-based) answer on
11 ## StackOverflow and for also catching a small oversight in my posted answer.
13 ## Dirk Eddelbuettel, 23 Aug 2011
15 ## Copyrighted but of course GPL'ed
24 z[i] <- ifelse(z[i-1]==1, 1, 0)
33 z[i] <- if(z[i-1]==1) 1 else 0
40 funRcpp <- cxxfunction(signature(zs="numeric"), plugin="Rcpp", body="
41 Rcpp::NumericVector z = Rcpp::NumericVector(zs);
43 for (int i=1; i<n; i++) {
44 z[i] = (z[i-1]==1.0 ? 1.0 : 0.0);
50 z <- rep(c(1,1,0,0,0,0), 100)
51 ## test all others against fun1 and make sure all are identical
52 all(sapply(list(fun2(z),fun1c(z),fun2c(z),funRcpp(z)), identical, fun1(z)))
54 res <- benchmark(fun1(z), fun2(z),
57 columns=c("test", "replications", "elapsed", "relative", "user.self", "sys.self"),
63 res2 <- benchmark(fun1(z), fun2(z),
66 columns=c("test", "replications", "elapsed", "relative", "user.self", "sys.self"),
72 if (FALSE) { # quick test to see if Int vectors are faster: appears not
73 funRcppI <- cxxfunction(signature(zs="integer"), plugin="Rcpp", body="
74 Rcpp::IntegerVector z = Rcpp::IntegerVector(zs);
76 for (int i=1; i<n; i++) {
77 z[i] = (z[i-1]==1.0 ? 1.0 : 0.0);
82 z <- rep(c(1L,1L,0L,0L,0L,0L), 100)
83 identical(fun1(z),fun2(z),fun1c(z),fun2c(z),funRcppI(z))
85 res3 <- benchmark(fun1(z), fun2(z),
88 columns=c("test", "replications", "elapsed", "relative", "user.self", "sys.self"),
93 z <- c(1L,1L,0L,0L,0L,0L)
94 res4 <- benchmark(fun1(z), fun2(z),
97 columns=c("test", "replications", "elapsed", "relative", "user.self", "sys.self"),