Stephan Lindner
2009-Sep-20 03:42 UTC
[R] Computing the sum of cross products of rows of a matrix
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
Jorge Ivan Velez
2009-Sep-20 03:47 UTC
[R] Computing the sum of cross products of rows of a matrix
Dear Stephan, Try crossprod(x) HTH, Jorge On Sat, Sep 19, 2009 at 11:42 PM, Stephan Lindner <> wrote:> 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 > > ______________________________________________ > R-help@r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide > http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. >[[alternative HTML version deleted]]