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 <pda...@gmail.com> wrote:
> 
>> rbind(1:3,4:6)/t(matrix(c(2,3,4), 3,2))

______________________________________________
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to