The getline
function reads from a designated file, or pipe,
and separates the input into whitespace separated tokens. The
tokens are either numbers or strings. In this example we will use
the getline
function, and RLaB piping capability to read
the output from the UNIX ps command, and sum the numbers in the 5th
column (the resident process size).
> psize = 0; > while (length (ans = getline ("|/usr/ucb/ps -aux | grep ian"))) { psize = psize + ans.[5]; } > close ("|/usr/ucb/ps -aux | grep ian"); > psize psize = 2.26e+03
The following simple example makes extensive use of the list object's capabilities. This example consists of two user-functions that were written to allow someone to index a matrix with strings, or numeric quantities that are not necessarily equal to the integer row and column numbers.
Two special qualities of lists are used in this example. The first is the ability to group together related objects; thus the matrix, and its row and column labels are copied into a list-object. The second special quality is the associative nature of the list indices. When constructing the row and column labels, we create two lists that are members of the top-level list. These sub-lists contain the row or column label as the index value, and the integer row or column number as data.
// // Create a list-object, a matrix with row and // column labels. Then the matrix can be indexed // with the labels by using lb(). // mklb = function (mat, rl, cl) { lrl = <<>>; lcl = <<>>; if (!exist (rl)) { rl = 1:mat.nr; else if (length (rl) != mat.nr) { error ("mklb: rl wrong size"); } } for (i in 1:rl.n) { lrl.[rl[i]] = i; } if (!exist (cl)) { lcl = 1:mat.nc; else if (length (cl) != mat.nc) { error ("mklb: cl wrong size"); } } for (i in 1:cl.n) { lcl.[cl[i]] = i; } return << m = mat; rl = lrl; cl = lcl >> };
the function mklb
creates a list containing matrix, row,
and column labels. Looking closely at the for-loops you will notice
that the labels values are actually the index values of the
lists lrl
and lcl
. This method is used since it
provides extremely easy access to the matrix elements in the next
function lb
.
lb = function ( mlb, rl, cl ) { // Create row indices if (!exist (rl)) { irl = 1:mlb.m.nr; // use all the rows else for (i in 1:rl.n) { irl[i] = mlb.rl.[rl[i]]; } } // Create column indices if (!exist (cl)) { icl = 1:mlb.m.nc; // use all the columns else for (i in 1:cl.n) { icl[i] = mlb.cl.[cl[i]]; } } return mlb.m[irl; icl] };
The for-loops in lb
simply loop through the specified
indices, using them as index values to the internal row and column
lists. Once the numeric vectors irl
and icl
have been
formed the specified matrix elements are easily returned.
To use the new functions you might:
> m = [1,2,3;4,5,6;7,8,9]; > ml = mklb (m, ["r1","r2","r3"], ["c1","c2","c3"]) cl m rl > lb (ml, ["r1","r3"]) 1 2 3 7 8 9 > lb (ml, ["r1","r3"], "c1") 1 7 > lb (ml, , "c2") 2 5 8