SAS/IML -- Brief tutoring (1)

The usage of matrix operation is quite intensive in Statistics. Here, I will tell you how to do the matrix operation in SAS.

1. What is IML?

IML stands for Interactive Matrix Language. So, it is indeed one of the SAS languages. It is designed for matrix manipulation and operations. It provides you a tool to write your own customized SAS subroutine (called module), like new methodology and numerical algorithms.

2. Basic template for SAS/IML:

Similar as PROCEDURE step, the template for SAS/IML is:

PROC IML;

IML statement...............;

................;

QUIT;

NOTE: (1) we don't and can't specify DATA=XXX in first statement

            (2)we end the code block with QUIT instead of RUN. RUN in SAS/IML has special usage

3. How to assign a matrix?

Theoretically, you may use INFILE, INPUT those kind of external data access statements in SAS/IML. But I recommend you to use formal data step to read in the external file, then recall it into SAS/IML procedure (check USE statement in SAS/IML manual).

Here, we only need to deal with matrices of small size(2 by 2, 3 by 3), so I use matrix assignment directly.

Ex 1: (Create a matrix and print it out)

PROC IML;

 X={1 2 3,4 5 6,7 8 9};

 PRINT X;

QUIT;

So, basically we use curly bracket to quote the contents of matrix, and use comma to separate different rows. Besides, we use PRINT matrixname; to output contents of matrix.

You will get:

   X

1 2 3

4 5 6

7 8 9

in output window.

4. How to do the basic operation?

By basic operation I mean addition, subtraction, multiplication and division.

(1) w.r.t some constant

PROC IML;

 X={1 2 3,4 5 6,7 8 9};

 PRINT X;

 AX=X+2;

 MX=X*2;

 PRINT 'X PLUS 2' AX, 'X TIMES 2' MX;

QUIT;

 

You will get :

                    AX

X PLUS 2  3   4   5

                  6   7   8

                  9 10 11

                     MX

X TIMES 2  2   4   6

                    8 10 12

                  14 16 18

(2) w.r.t. matrix:

 

PROC IML;

 X={1 2 3,4 5 6,7 8 9};

 Y=I(3);

 XPY=X+Y;

 XTY=X*Y;

 PRINT XPY, XTY;

QUIT;

 

You will get :

 

XPY

2  2  3

4  6  6

7  8 10

 

XTY

1 2 3

4 5 6

7 8 9

Note that I(3) denotes for 3 by 3 identity matrix (diagonal terms are 1, off-diagonal terms are 0)

4. Operations: ( Inverse)

PROC IML;

 X={1 2 3,4 5 6,7 8 10};

 IX=INV(X);

 PRINT 'INVERSE OF X', IX;

QUIT;

 

INVERSE OF X

IX

-0.666667 -1.333333    1

-0.666667  3.6666667 -2

 1              -2                 1

5. How to write a module?

To be continued!