[R] [External] converting MATLAB -> R | element-wise operation

Richard M. Heiberger rmh @end|ng |rom temp|e@edu
Fri Mar 1 00:12:14 CET 2024


I decided to do a direct comparison of transpose and sweep.


library(microbenchmark)

NN <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, byrow = TRUE)  # Example matrix
lambda <- c(2, 3, 4)  # Example vector
colNN <- t(NN)

microbenchmark(
  sweep     = sweep(NN, 2, lambda, "/"),
  transpose = t(t(NN)/lambda),
  colNN     = colNN/lambda
)


Unit: nanoseconds
      expr   min    lq     mean median      uq   max neval cld
     sweep 13817 14145 15115.06  14350 14657.5 75932   100 a  
 transpose  1845  1927  2151.68   2132  2214.0  7093   100  b 
     colNN    82   123   141.86    123   164.0   492   100   c

Note that transpose is much faster than sweep because it is doing less work,
I believe essentially just changing the order of indexing.

Using the natural sequencing for column-ordered matrices is much much faster.

> On Feb 28, 2024, at 18:43, peter dalgaard <pdalgd using gmail.com> wrote:
> 
>> rbind(1:3,4:6)/t(matrix(c(2,3,4), 3,2))



More information about the R-help mailing list