Tutorial: A Module for Linear Regression

Example: Solving a System of Linear Equations

Because the syntax of the SAS/IML language is similar to the notation used in linear algebra, it is often possible to directly translate mathematical methods from matrix-algebraic expressions into executable SAS/IML statements. For example, consider the problem of solving three simultaneous equations:

StartLayout 1st Row 1st Column 3 x 1 minus x 2 plus 2 x 3 2nd Column equals 3rd Column 8 2nd Row 1st Column 2 x 1 minus 2 x 2 plus 3 x 3 2nd Column equals 3rd Column 2 3rd Row 1st Column 4 x 1 plus x 2 minus 4 x 3 2nd Column equals 3rd Column 9 EndLayout

These equations can be written in matrix form as

Start 3 By 3 Matrix 1st Row 1st Column 3 2nd Column negative 1 3rd Column 2 2nd Row 1st Column 2 2nd Column negative 2 3rd Column 3 3rd Row 1st Column 4 2nd Column 1 3rd Column negative 4 EndMatrix Start 3 By 1 Matrix 1st Row  x 1 2nd Row  x 2 3rd Row  x 3 EndMatrix equals Start 3 By 1 Matrix 1st Row  8 2nd Row  2 3rd Row  9 EndMatrix

and can be expressed symbolically as

bold upper A bold x equals bold c

where bold upper A is the matrix of coefficients for the linear system. Because bold upper A is nonsingular, the system has a solution given by

bold x equals bold upper A Superscript negative 1 Baseline bold c

This example solves this linear system of equations.

  1. Define the matrices bold upper A and bold c. Both of these matrices are input as matrix literals; that is, you type the row and column values as discussed in Chapter 2, Understanding the SAS/IML Language.

    proc iml;
    a = {3  -1  2,
         2  -2  3,
         4   1 -4};
    c = {8, 2, 9};
    
  2. Solve the equation by using the built-in INV function and the matrix multiplication operator. The INV function returns the inverse of a square matrix and * is the operator for matrix multiplication. Consequently, the solution is computed as follows:

    x = inv(a) * c;
    print x;
    

    Figure 1: The Solution of a Linear System of Equations

    x
    3
    5
    2


  3. Equivalently, you can solve the linear system by using the more efficient SOLVE function, as shown in the following statement:

    x = solve(a, c);
    

After SAS/IML executes the statements, the rows of the vector x contain the x 1 comma x 2, and x 3 values that solve the linear system.

You can end PROC IML by using the QUIT statement:

quit;
Last updated: May 07, 2026