[R] [External] converting MATLAB -> R | element-wise operation
Richard M. Heiberger
rmh @end|ng |rom temp|e@edu
Fri Mar 1 04:12:02 CET 2024
I added two more rows
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)
matlam <- matrix(lambda, byrow=TRUE, nrow=2, ncol=3)
microbenchmark(
sweep = sweep(NN, 2, lambda, "/"),
transpose = t(t(NN)/lambda),
colNN = colNN/lambda,
fullsize = NN / matrix(lambda, byrow=TRUE, nrow=2, ncol=3),
rowlam = NN / matlam
)
Unit: nanoseconds
expr min lq mean median uq max neval cld
sweep 12546 12792 13919.91 12997.0 13325.0 85608 100 a
transpose 1640 1763 1986.04 1947.5 2050.0 7462 100 b
colNN 82 82 161.13 123.0 123.0 3854 100 c
fullsize 738 820 932.34 881.5 963.5 2829 100 bc
rowlam 82 123 168.92 164.0 164.0 820 100 c
reshaping the denominator to the correct size in advance is very helpful if you will be doing this division more than once.
> On Feb 29, 2024, at 18:12, Richard M. Heiberger <rmh using temple.edu> wrote:
>
> 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))
>
> ______________________________________________
> R-help using 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.
More information about the R-help
mailing list