RfastOfficial / Rfast

A collection of Rfast functions for data analysis. Note 1: The vast majority of the functions accept matrices only, not data.frames. Note 2: Do not have matrices or vectors with have missing data (i.e NAs). We do no check about them and C++ internally transforms them into zeros (0), so you may get wrong results. Note 3: In general, make sure you give the correct input, in order to get the correct output. We do no checks and this is one of the many reasons we are fast.
143 stars 19 forks source link

eachrow not correctly multiplying matrices by vector #98

Closed ldkregar closed 7 months ago

ldkregar commented 8 months ago

Dear Manos, multiplying a matrix by a vector of fixed scalars either row or column wise should yield identical results, but it is not. Could you please have a look? Many thanks...

set.seed(123)
nrows <- 5
ncols <- 4
mtx1 <- matrix(rnorm(20), nrows, ncols)
mtx_g <- matrix(rnorm(20), ncols, nrows)

vec1_row <- rep(0.05, nrows)
vec1_col <- rep(0.05, ncols)

mtx_row_wise <- Rfast::eachrow(mtx1, vec1_row, "*")  %*% mtx_g
mtx_col_wise <- t(Rfast::eachrow(t(mtx1), vec1_col, "*"))  %*% mtx_g

all.equal(mtx_row_wise, mtx_col_wise)
mtx_row_wise
mtx_col_wise 
mtx_row_wise - mtx_col_wise
# difference occurs in the last row

# Expected behaviour - with sweep
mtx1_reg_row <- sweep(mtx1, MARGIN=1, vec1_row, "*")
mtx_reg_row_wise <- mtx1_reg_row  %*% mtx_g

mtx1_reg_col <- sweep(mtx1, MARGIN=2, vec1_col, "*")
mtx_reg_col_wise <- mtx1_reg_col  %*% mtx_g
all.equal(mtx_reg_row_wise, mtx_reg_col_wise)

sessionInfo()

R version 4.3.0 (2023-04-21) Platform: x86_64-apple-darwin20 (64-bit) Running under: macOS 14.2.1

Matrix products: default BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib LAPACK: /Library/Frameworks/R.framework/Versions/4.3-x86_64/Resources/lib/libRlapack.dylib; LAPACK version 3.11.0

locale: [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

time zone: Europe/London tzcode source: internal

attached base packages: [1] stats graphics grDevices utils datasets methods base

other attached packages: [1] data.table_1.14.8 ape_5.7-1 knitr_1.42 memento_0.1.0 testthat_3.1.8 devtools_2.4.5 usethis_2.1.6

ManosPapadakis95 commented 7 months ago

Closed as duplicate. I have already fix this issue for the next update.