Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to divide each value of matrix by square root of sums of Respective columns of that matrix?

Tags:

r

How I can obtained by dividing each original value by the square root of the sum of squared original values for that column in the original matrix.

data(longley)
X <- as.matrix(longley[,-7])

X/sqrt(colSums(X^2))

Getting wrong results.

like image 464
itfeature.com Avatar asked Dec 08 '25 23:12

itfeature.com


1 Answers

Try this:

t(t(X)/sqrt(colSums(X^2)))

Benchmarks:

library(microbenchmark)
microbenchmark(t(t(X)/sqrt(colSums(X^2))),
               apply(X, 2 , function(x) x/sqrt(sum(x^2))))
# Unit: microseconds
#                                      expr     min       lq   median       uq     max neval
# t(t(X)/sqrt(colSums(X^2)))                 28.783  33.1305  34.9455  40.5640  68.147   100
# apply(X, 2, function(x) x/sqrt(sum(x^2))) 100.307 105.1940 106.9975 108.1075 193.015   100
like image 110
Roland Avatar answered Dec 10 '25 12:12

Roland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!