Title | Performing element-by-element operations on matrices | |
Author | Allen McDowell, StataCorp | |
Date | July 2001; updated April 2005 |
Matrix manipulations have been greatly enhanced in Stata 9 using the Mata language. One of the capabilities is an element-by-element calculation using the colon operator. For example:
. mata ------------------------------------------------- mata (type end to exit) ------ : x 1 2 +---------+ 1 | 1 2 | 2 | 3 4 | +---------+ : y 1 2 +---------+ 1 | 3 5 | 2 | 7 9 | +---------+ : z = x :/ y : z 1 2 +-----------------------------+ 1 | .3333333333 .4 | 2 | .4285714286 .4444444444 | +-----------------------------+ : end --------------------------------------------------------------------------------
Or, in Stata, suppose I have the following two matrices, A and B,
. matrix A=(1,2,3,4,5 \ 6,7,8,9,10) . mat list A A[2,5] c1 c2 c3 c4 c5 r1 1 2 3 4 5 r2 6 7 8 9 10 . matrix B=(11,12,13,14,15 \ 16,17,18,19,20) . matrix list B B[2,5] c1 c2 c3 c4 c5 r1 11 12 13 14 15 r2 16 17 18 19 20
I want to perform element-by-element division. That is, suppose I want to generate the matrix C so each element of C is the ratio of the corresponding elements in A and B, so that C[1,1] = A[1,1]/B[1,1]; C[1,2] = A[1,2]/B[1,2]; etc.
First, I generate the matrix C so that it has the correct dimensions. I must fill in the elements with some value, so I chose zeros.
. matrix C = J(2,5,0) . matrix list C C[2,5] c1 c2 c3 c4 c5 r1 0 0 0 0 0 r2 0 0 0 0 0
Now I can set up nested forvalues loops, with the outer loop indexing the rows and the inner loop indexing the columns.
forvalues i = 1/2 { forvalues j = 1/5 { matrix C[`i',`j']= A[`i',`j']/B[`i',`j'] } } matrix list C C[2,5] c1 c2 c3 c4 c5 r1 .09090909 .16666667 .23076923 .28571429 .33333333 r2 .375 .41176471 .44444444 .47368421 .5
I can easily modify the above code to accommodate other algebraic expressions involving the individual matrix elements and matrices of any dimensions.