Empty subscripts: How to fill rows and columns of a matrix

February 18, 2013

(This article was originally published at The DO Loop, and syndicated at StatsBlogs.)

Suppose that you have a SAS/IML matrix and you want to set each element of a submatrix to zero (or any other value). There is a simple syntax that accomplishes this task.

If you subscript a matrix and do not specify a row, it means "use all rows." So, for example, you can assign zeros to the third column of a matrix by using the following syntax:

proc iml;
x = j(3, 5, 1);   /* create 3 x 5 matrix of ones             */
x[ , 3] = 0;      /* assign zeros to third column (all rows) */
print x;

In the same way, if you do not specify a column, it means "use all columns." So, for example, you can assign zeros to the second row of a matrix by using the following syntax:

x[2, ] = 0;       /* assign zeros to second row (all columns) */

Of course, you can extend these examples by assigning nonconstant vectors to rows or columns:

x[3, ] = 1:5;     /* assign {1 2 3 4 5} to third row */

But here's a cool tip that many SAS/IML programmers do not know: you can fill the entire matrix by skipping the rows and the columns! For example, to assign zeros to entire matrix (regardless of dimensions), use the following syntax:

x[ , ] = 0;       /* assign zero to all elements */
print x;

I don't see this syntax used very often. It is never used on the right-hand side of an assignment because the expression t = x is easier and clearer than t = x[ , ]. However, when assigning values into a pre-allocated matrix, it is an efficient alternative to x = j(nrow(x), ncol(x), 0) or x[1:nrow(x), 1:ncol(x)] = 0. The "double empty" technique also preserves any matrix attributes that you might have assigned by using the MATTRIB statement, whereas using the J function deletes the old matrix and creates a new one.

Do you have a favorite SAS/IML syntax that is tricky or seldom-used? Share it in a comment!

tags: Getting Started

Please comment on the article here: The DO Loop

Tags: ,