Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This a job where Rcpp excels. Nested loops are straight forward to implement and you don't need much C++ experience. (I like RcppEigen, but you don't really need it for this. You could use "pure" Rcpp.)</p> <pre><code>library(RcppEigen) library(inline) incl &lt;- ' using Eigen::Map; using Eigen::MatrixXd; typedef Map&lt;MatrixXd&gt; MapMatd; ' body &lt;- ' const MapMatd A(as&lt;MapMatd&gt;(AA)), B(as&lt;MapMatd&gt;(BB)); const int nA(A.rows()), mA(A.cols()), mB(B.cols()); MatrixXd R = MatrixXd::Ones(nA,mB); for (int i = 0; i &lt; nA; ++i) { for (int j = 0; j &lt; mB; ++j) { for (int k = 0; k &lt; mA; ++k) { R(i,j) *= (1 - A(i,k) * B(k,j)); } R(i,j) = 1 - R(i,j); } } return wrap(R); ' funRcpp &lt;- cxxfunction(signature(AA = "matrix", BB ="matrix"), body, "RcppEigen", incl) </code></pre> <p>Now, lets put your code in an R function:</p> <pre><code>doupleApply &lt;- function(A, B) t(apply(A,1, function(x) apply(B,2,function(y) 1-prod(1-x*y)))) </code></pre> <p>Compare the results:</p> <pre><code>all.equal(doupleApply(A,B), funRcpp(A,B)) #[1] TRUE </code></pre> <p>Benchmarks:</p> <pre><code>library(microbenchmark) microbenchmark(doupleApply(A,B), funRcpp(A,B)) # Unit: microseconds # expr min lq median uq max neval #doupleApply(A, B) 169.699 179.2165 184.4785 194.9290 280.011 100 # funRcpp(A, B) 1.738 2.3560 4.6885 4.9055 11.293 100 set.seed(42) A &lt;- matrix(rnorm(3*1e3), ncol=3) B &lt;- matrix(rnorm(3*1e3), nrow=3) all.equal(doupleApply(A,B), funRcpp(A,B)) #[1] TRUE microbenchmark(doupleApply(A,B), funRcpp(A,B), times=5) # Unit: milliseconds # expr min lq median uq max neval # doupleApply(A, B) 4483.46298 4585.18196 4587.71539 4672.01518 4712.92597 5 # funRcpp(A, B) 24.05247 24.08028 24.48494 26.32971 28.38075 5 </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload