[R] Computing the sum of cross products of rows of a matrix

Stephan Lindner lindners at umich.edu
Sun Sep 20 05:42:43 CEST 2009


Hi everyone,


I would like to compute the sum of cross products of rows of a
matrix. Does anyone know how to do this without an explicit loop for
computational efficiency? Below is a code example.


Thanks!

	Stephan




# I.e., if I have a matrix like this 

x <- matrix(rep(c(1,2,3),3),ncol=3)

## > x
##      [,1] [,2] [,3]
## [1,]    1    1    1
## [2,]    2    2    2
## [3,]    3    3    3


## and a storage matrix like this 

cross <- matrix(rep(0,9),ncol=3)


## then use a loop to sum up the cross products of the rows 

for (i in 1:nrow(x)){ cross <- cross+tcrossprod(x[i,]) }


## The result
##
## > cross
##      [,1] [,2] [,3]
## [1,]   14   14   14
## [2,]   14   14   14
## [3,]   14   14   14






-- 
-----------------------
Stephan Lindner
University of Michigan




More information about the R-help mailing list