Sweeping along an axis can be represented by matrix multiplication. Given the matrix \(A\) and diagonal matrix \(D\), \(DA\) is equivalent to multiplying each row \(i\) of \(A\) by \(d_{ii}\), and \(AD\) is equivalent to multiplying each column \(j\) of \(A\) by \(d_{jj}\) A = matrix(runif(50000),ncol=100) w = apply(A, 1, norm, '2') all(abs(sweep(A,1, w, '/') - (diag(1/w) %*% A) ) < .Machine$double.eps) ## [1] TRUE It is reasonably expected that the sweeping operation on invidual row/column vector will be more efficient than the equivalent matrix operation, because no additional memory will be required to store the non-diagonal entries of \(D\).

Continue reading

Digit count

What is the better way to count the number of digit in a number? digit_count recursively divide the number by its base (10) cast it into string and use str_length to count the number of characters digit_count <- function(number,count=1) { if (number < 10) {return(count)} return(digit_count(number %/% 10, count=count+1)) } Definitions a = function(x) {return(digit_count(x))} b = function(x) {return(stringr::str_length(as.character(1000)))} Timing

Continue reading

Author's picture

Trang Tran


Student

USA