3.3 Representing Summation Using Matrix Notation

Consider the sum: nk=1xk=x1++xn. Let x=(x1,,xn) be an n×1 vector and 1=(1,,1) be an n×1 vector of ones. Then, x1=[x1xn][11]=x1++xn=nk=1xk, and, 1x=[11][x1xn]=x1++xn=nk=1xk. Next, consider the sum of squared x values, nk=1x2k=x21++x2n. This sum can be conveniently represented as, xx=[x1xn][x1xn]=x21++x2n=nk=1x2k. Last, consider the sum of cross products, nk=1xkyk=x1y1+xnyn. This sum can be compactly represented by, xy=[x1xn:][y1yn]=x1y1+xnyn=nk=1xkyk. Note that xy=yx.

Example 2.17 (Computing sums in R)

In R, summing the elements in a vector can be done using matrix algebra.

# create vector of 1's and a vector of x
onevec = rep(1,3)
onevec
## [1] 1 1 1
xvec = c(1,2,3)
# sum elements in x
t(xvec)%*%onevec
##      [,1]
## [1,]    6

The functions crossprod() and sum() are generally computationally more efficient:

crossprod(xvec,onevec)
##      [,1]
## [1,]    6
sum(xvec)
## [1] 6

Sums of squares are best computed using:

crossprod(xvec)
##      [,1]
## [1,]   14
sum(xvec^2)
## [1] 14

The dot-product two vectors can be conveniently computed using the crossprod() function:

yvec = 4:6
xvec
## [1] 1 2 3
yvec
## [1] 4 5 6
crossprod(xvec,yvec)
##      [,1]
## [1,]   32
crossprod(yvec,xvec)
##      [,1]
## [1,]   32