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?
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))