/*******************************************************************\ |SAS PROGRAM to teach Basic Matrix manipulation July 7th 2002 | |by Kazuaki Uekawa, Ph.D. | |Independent SAS consultant | |(ueka@src.uchicago.edu) | |http://www.src.uchicago.edu/users/ueka | |http://www.geocities.com/sastip | ********************************************************************/ /* Reviewing matrix manipulation. Basis for doing regression programming using matrices. Also good for social network analysis. */ proc iml; y={1, 2, 3, 4}; x={2, 4, 6, 8}; z=3; Q1= {1 2 3, 1 2 3, 1 2 3}; Q2={ 2 4 3, 3 4 2, 1 3 1}; /*review of some matrix manipulation necesasry to do regression*/ /*(1) addition and substraction*/ new1=y-x; new2=y+x; print new1 new2; /*(2) multiplication and division*/ /*(2a) by a scaler z (=just one number)*/ new3=y*z; new4=y/z; print y z new3 new4; /*(2b) two matrixes*/ /*When is this multiplication possible?*/ new5=Q1*Q2; print Q1 Q2 new5; /*(2c) just very simple multiplication without doing dot products*/ new6=Q1#Q2; print Q1 Q2 new6; /*(3) Transpose*/ /*transpose means to go from [1 2 3] to [1 2 3]*/ new7=t(X); new8=t(Q1); print X new7; print Q1 new8; /*get an inverse*/ /*An inverse of matrix times the original matrix becomes an identity matrix. Identity matrix is the one with 1s in diagnal and zeros in other cells*/ /*This is just like a number: inverse of 2 is 1/2 since 2*(1/2)=1*/ new10=inv(Q2); print new10; /*test whether new10 is really an inverse of Q2 by actually trying the multiplication of the two matrices.*/ /*I used Q2 because Q1 would not work. Try it. An error message says "ERROR: (execution) Matrix should be non-singular."*/ /*This is why a regression model would not work if independent variables are highly correlated*/ new11=Q2*new10; print new11; /*finally, very interesting and amazing manipulation "Sum of squared values"*/ /*The first person who discovered this must be thrilled*/ new12=t(Y)*Y; print Y new12; /*this would be same as doing the following "ungly" procedure*/ new12b=sum(Y#Y); print Y new12b; /*also some instrumental manipulations*/ /*to know the number of colums or rows*/ new13=ncol(Q1); new14=nrow(Q1); print Q1 new13 new14; /*why is this useful?*/ /*using above, we know the number of observations in a matrix or number of variables in a matrix*/