Search code examples
rmatrixsparse-matrixlinear-algebra

How to efficiently compute the sum of squares of each of row of a sparse matrix in R?


I have a matrix M and I want to compute the sum of the squares of the entries for each row. So for a small matrix I could write (in R):

x <- diag(M %*% t(M))

However, my matrix is a sparse matrix with about 10 million rows and 100 columns and doing the above first computes the entire 10 million by 10 million matrix and then extracts the diagonal from it and hence is very inefficient.

What would be a good way to do this with matrix operations without computing unneeded values?


Solution

  • You can simply do this by using apply function. For example, Mat is your relevant matrix, then

    apply(Mat, 1, FUN = function(x) sum(x^2))