3.3 Representing Summation Using Matrix Notation
Consider the sum: n∑k=1xk=x1+⋯+xn. Let x=(x1,…,xn)′ be an n×1 vector and 1=(1,…,1)′ be an n×1 vector of ones. Then, x′1=[x1…xn]⋅[1⋮1]=x1+⋯+xn=n∑k=1xk, and, 1′x=[1…1]⋅[x1⋮xn]=x1+⋯+xn=n∑k=1xk. Next, consider the sum of squared x values, n∑k=1x2k=x21+⋯+x2n. This sum can be conveniently represented as, x′x=[x1…xn]⋅[x1⋮xn]=x21+⋯+x2n=n∑k=1x2k. Last, consider the sum of cross products, n∑k=1xkyk=x1y1+⋯xnyn. This sum can be compactly represented by, x′y=[x1…xn:]⋅[y1⋮yn]=x1y1+⋯xnyn=n∑k=1xkyk. Note that x′y=y′x.
In R, summing the elements in a vector can be done using matrix algebra.
# create vector of 1's and a vector of x
rep(1,3)
onevec = onevec
## [1] 1 1 1
c(1,2,3)
xvec =# 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:
4:6
yvec = xvec
## [1] 1 2 3
yvec
## [1] 4 5 6
crossprod(xvec,yvec)
## [,1]
## [1,] 32
crossprod(yvec,xvec)
## [,1]
## [1,] 32
◼