RANK (matrix);
The RANK function creates a new matrix that contains elements that are the ranks of the corresponding elements of the numerical argument, matrix. The rank of a missing value is a missing value. The ranks of tied values are assigned arbitrarily. (See the description of the RANKTIE function for alternate approaches.)
For example, the following statements produce the ranks of a vector:
x = {2 2 1 0 5}; r = rank(x); print r;
Provided that a vector, x
, does not contain missing values, the RANK function can be used to sort the vector, as shown in the following statements:
b = x; x[,rank(x)] = b; print x;
You can also sort a matrix by using the SORT subroutine . The SORT subroutine handles missing values in the data.
The RANK function can also be used to find anti-ranks of , as follows:
x = {2 2 1 0 5}; r = rank(x); a = r; a[,r] = 1:ncol(x); print a;
Although the RANK function ranks only the elements of numerical matrices, you can rank the elements of a character matrix by using the UNIQUE function, as demonstrated by the following statements:
/* Create RANK-like functionality for character matrices */ start rankc(x); s = unique(x); /* the unique function returns a sorted list */ idx = j(nrow(x), ncol(x)); ctr = 1; /* there can be duplicate values in x */ do i = 1 to ncol(s); /* for each unique value */ t = loc(x = s[i]); nDups = ncol(t); idx[t] = ctr : ctr+nDups-1; ctr = ctr + nDups; end; return (idx); finish; /* call the RANKC module */ x = {every good boy does fine and good and well every day}; rc = rankc(x); print rc[colnam=x]; /* Notice that ranking is in ASCII order, in which capital letters precede lower case letters. To get case-insensitive behavior, transform the matrix before comparison */ x = {"a" "b" "X" "Y" }; asciiOrder = rankc(x); alphaOrder = rankc(upcase(x)); print x, asciiOrder, alphaOrder;
Figure 25.317: Ranks of Character Matrices
There is no SAS/IML function that directly computes the linear algebraic rank of a matrix. In linear algebra, the rank of
a matrix is the maximal number of linearly independent columns (or rows). You can use the following technique to compute the
numerical rank of matrix a
:
/* Only four linearly independent columns */ A = {1 0 1 0 0, 1 0 0 1 0, 1 0 0 0 1, 0 1 1 0 0, 0 1 0 1 0, 0 1 0 0 1 }; rank = round(trace(ginv(a)*a)); print rank;
Another common technique used to examine the rank of a matrix is to look at the number of nonzero singular values in the singular value decomposition of a matrix (see the SVD call ). However, keep in mind that numerical computations might result in singular values for a rank-deficient matrix that are small but nonzero.