Command Reference : Matrix Language : Matrix Operations versus Loop Operations
Matrix Operations versus Loop Operations
You may perform matrix operations using element operations and loops instead of the built-in functions and commands. For example, the inner product of two vectors may be computed by evaluating the vectors element-by-element:
scalar inprod1 = 0
for !i = 1 to @rows(vec1)
inprod1 = inprod1 + vec1(!i)*vec2(!i)
This approach will, however, generally be much slower than using the built-in function:
scalar inprod2 = @inner(vec1, vec2)
You should use the built-in matrix operators rather than loop operators whenever you can. The matrix operators are always much faster than the equivalent loop operations.
Similarly, suppose, for example, that you wish to subtract the column mean from each element of a matrix. Such a calculation might be useful in constructing a fixed effects regression estimator. First, consider a slow method involving only loops and element operations:
matrix x = @convert(mygrp1)
scalar xsum
for !i = 1 to @columns(x)
xsum = 0
for !j = 1 to @rows(x)
xsum = xsum+x(!j,!i)
xsum = xsum/@rows(x)
for !j = 1 to @rows(x)
x(!j,!i) = x(!j,!i)-xsum
The loops are used to compute a mean for each column of data in X, and then to subtract the value of the mean from each element of the column. A faster method for subtracting column means uses the built-in operators and functions:
matrix x = @convert(mygrp1)
vector xmean = @cmeans(x)
x = x - @scale(@ones(@rows(x), @columns(x)),@transpose(xmean))
The first line converts the data in MYGRP1 into the matrix X. The second line computes the column means of X and saves the results in XMEAN. The last line subtracts the matrix of column means from X. Note that we first create a temporary matrix of ones, then use the @scale function to scale each column using the element in the corresponding column of the transpose of XMEAN.