This chapter covers the built-in functions. Normally, no distinction is made between the built-in, and the user-functions. However, they are documented separately because custom installations, and program execution options make it possible for Rlab to run with many of the user-functions missing.
The documentation for each built-in function is nearly the same as the online help. In fact, the printed documentation is the source of the online help files.
Compute the absolute value.
abs ( A )
abs returns the absolute value of it's input, A. abs is a scalar function.
For complex values abs returns the square root of the sum of the squares of the real and imaginary parts.
Compute the arc-cosine.
acos ( A )
The trigonometric functions are scalars functions. The return value is the result of the trigonometric operation performed on the input, element-by-element.
All the trigonometric functions use the C language math library functions, so details about the ranges and error conditions can be found by examining the appropriate man pages on your system.
Check if all elements are non-zero.
all ( A )
When A is a vector (row or column):
all returns TRUE (1) if all of the elements of A are non-zero. all returns zero otherwise.
When A is a matrix:
all operates on the columns of A, returning a row-vector of ones and zeros.
any
Check if any elements are non-zero.
any ( A )
When A is a vector (row or column):
any returns TRUE (1) if any of the elements of A are non-zero. any returns FALSE (0) otherwise.
When A is a matrix:
any operates on the columns of A, returning a row-vector of ones and zeros.
all
Compute the arc-sin.
asin ( A )
RLaB trigonometric functions are designed to take scalars, and matrices as arguments. The return value is the input argument with the trigonometric operation performed element by element.
The trigonometric functions use the C language math library functions, so details about the ranges and error conditions can be found by examining the appropriate man pages on your system.
Compute the arc-tangent.
atan ( A )
RLaB trigonometric functions are designed to take scalars, and matrices as arguments. The return value is the input argument with the trigonometric operation performed element by element.
The trigonometric functions use the C language math library functions, so details about the ranges and error conditions can be found by examining the appropriate man pages on your system.
Compute the arc-tangent.
atan2 ( y , x )
RLaB trigonometric functions are designed to take scalars, and matrices as arguments. The return value is the input argument with the trigonometric operation performed element by element.
atan2 takes two arguments, which are the y, and x values used to form the tangent. All the trigonometric functions use the C language math library functions, so details about the ranges and error conditions can be found by examining the appropriate man pages on your system.
Atan2 does not operate on complex arguments.
Solution of Ax = B
by backsubstitution.
backsub ( LIST, B )
The backsub function computes the solution to the set of linear equations described by:
A * X = B
The 1st argument to backsub (LIST) is the result from `factor(A)'. The second argument to backsub is the matrix B. B can contain multiple right hand sides.
Backsub returns a matrix X which contains the solution(s) to the aforementioned equations.
Backsub utilizes the LAPACK subroutines DGETRS or ZGETRS if LIST contains LU factors or LAPACK subroutins DSYTRS or ZHETRS if LIST contains the LDL factors.
Example:
> A = [1,2,3;4,5,6;7,8,0]
1 2 3
4 5 6
7 8 0
> B = [1;2;3]
1
2
3
> X = backsub(factor(A), B)
-0.333
0.667
-3.52e-18
> A*X - B
0
0
0
factor, inv, lu, solve
Balance a matrix for equal row and column norms.
balance ( A )
Balance uses the LAPACK subroutines DGEBAL and ZGEBAL to balance the input matrix so that the row and column norms are approximately equal.
balance returns a list with elements t and ab.
Example:
> a
0 0 1 0
0 0 0 1
11 10 0 0
10 11 0 0
> </ ab ; t /> = balance(a);
> inv(t)*a*t - ab
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
Only square matrices are allowed.
Smallest integer not less than argument.
ceil ( a )
Ceil returns the smallest integer not less than the argument. If the argument is a MATRIX then the ceil operation is performed on an element-by-element basis.
floor, int
Cholesky factorization.
chol( A )
Chol computes the Cholesky factorization of the input matrix.
The input matrix must be real symmetric positive definite, or
complex Hermitian positive definite. chol() produces an upper
triangular matrix U, such that U'*U
and A
(the input) are equal.
chol use the LAPACK subroutine DPOTRF and ZPOTRF.
Identify the class of an object.
class ( A )
Class returns a string which identifies the type of the object that A represents. Valid classes are:
It is often useful to:
if(class(m) == "num")
{
# Perform numerical computation on m
}
The class of a variable can also be determined by using the class member reference (except for LISTs), like:
> zeros.class
function
show, type
Delete a variable.
clear ( A )
Clear effectively deletes a variables object from the symbol table. The effect is the variable does not show up when who() is used. The memory associated with the variable is freed.
Clear accepts up to 32 arguments, the return value is the number of objects that have been successfully cleared.
Close a file.
close ( filename )
close takes a string (filename) as input, and attempts to close the output stream associated with filename. close returns TRUE (1) if the output stream was successfully closed, FALSE (0) if the output stream could not be closed.
If you want to read the contents of a file that you have created with the write function in the present session, then be sure to close the file before using the read function.
Example:
write( "eig_output", a , vec , val );
close( "eig_output" );
read( "eig_output" );
printf, fprintf, getline, open, read, readb, readm, write, writeb, writem
Complex conjugate.
conj ( A )
Conj returns the complex conjugate of its input argument. For MATRIX arguments the conjugate is performed element by element.
imag, real
Compute the cosine.
cos ( A )
The trigonometric functions are scalars functions. The return value is the result of the trigonometric operation performed on the input, element-by-element.
All the trigonometric functions use the C language math library functions, so details about the ranges and error conditions can be found by examining the appropriate man pages on your system.
Cumulative product.
cumprod ( A )
cumprod computes the running, or cumulative product of the input, A. If the input is a rectangular matrix, then the cumulative product is performed over the columns of the matrix.
Example:
> a=1:4
a =
1 2 3 4
> cumprod (a)
1 2 6 24
> a = [1,2,3;4,5,6;7,8,9]
a =
1 2 3
4 5 6
7 8 9
> cumprod (a)
1 2 3
4 10 18
28 80 162
cumsum, prod, sum
Cumulative sum.
cumsum ( A )
cumsum computes the running, or cumulative sum of a vector or matrix. The return object is a matrix the same size as the input, A. If A is a rectangular matrix, then the cumulative sums are performed over the columns of the matrix.
Example:
> a = 1:4
a =
1 2 3 4
> cumsum(a)
1 3 6 10
> a= [1,2,3;4,5,6;7,8,9]
a =
1 2 3
4 5 6
7 8 9
> cumsum (a)
1 2 3
5 7 9
12 15 18
cumprod, prod, sum
Matrix determinant.
det ( A )
Det computes the determinant of the matrix argument.
Det uses the LAPACK functions to factor the input, and the LINPACK algorithm to calculate the determinant.
See Also inv, lu, rcond
Diagnonal matrix.
diag ( A )
diag ( A, K )
If the 1st argument, A is a 1xN matrix construct a diagonal matrix from the input. Optionally if K (scalar) is specified then create a matrix with the vector as the Kth diagonal.
If the 1st argument is a MxN matrix, construct a 1xN matrix from the diagonal elements of the input matrix. Optionally if K is specified return the vector from the Kth diagonal of the input matrix.
K < is below the main diagonal.
K > is above the main diagonal.
tril, triu
Log commands (program statements) to a file.
diary ( )
diary ( FILENAME )
The diary function echoes all input commands and Rlab output
to a diary file. If FILENAME is not specified, then a
file named: DIARY
is opened.
The diary, used without any arguments will turn on statement logging, or turn off statement logging if a diary file is already open.
Dynamically link a function.
dlopen ( FILENAME , FUNCTION_NAME )
dlopen opens a shared object, FILENAME, and creates a builtin function that points to FUNCTION_NAME. dlopen returns the newly created builtin function.
For information on how to write and compile functions that can be linked with dlopen, consult the RLaB Programmer's Guide and Reference Manual.
dlopen only exists for those platforms that support dynamic linking. As of this writing support exists for Solaris 2.x and Linux/ELF platforms.
Eigensolver.
eig ( A )
Computes the eigenvectors, and values of matrix A. eig() returns a LIST with elements `val' and `vec' which are the eigenvalues and eigenvectors. Eig checks for symmetry in A, and uses the appropriate solver.
Computes the eigenvectors, and values of A, and
B. Where A*x = lambda*B*x
. The values
and vectors are returned in a list with element names
val and vec. Eig checks for symmetry in
A and B and uses the appropriate solver.
Uses the LAPACK subroutines DSYEV/ZHEEV or DGEEV/ZGEEV.
Example:
The generalized eigenvalue problem arises quite regularly in structures. From the second order differential equations describing a lumped mass system arise $M$ and $K$, coefficient matrices representing the mass and stiffness of the various physical degress of freedom. The equations are formulated as follows:
M*dx^2/dt^2 + K*x = F
Which leads to the eigenvalue problem:
K*v = w^2*M*v
For a two degree of freedom system we might have:
> m = eye(2,2)
> k = [5,1;1,5]
> </ val ; vec /> = eig(k, m);
> // Test the solution
> k * vec[;1]
-2.83
2.83
> val[1] * m * vec[;1]
-2.83
2.83
> // Properties of the solution
> vec' * m * vec
1 -4.27e-17
-4.27e-17 1
> vec' * k * vec
4 -1.71e-16
1.23e-16 6
The eigenvalues and vectors are sometimes obtained by converting the generalized problem into a standard eigenvalue problem (this is only feasible under certain conditions).
> a = m\k
a =
5 1
1 5
> eig(a).val
val =
4 6
> eig(a).vec
vec =
-0.707 0.707
0.707 0.707
svd, schur
Return entity information.
entinfo ( VAR )
Entinfo returns the internal address, and reference count of VAR. This function is not intended for general use... so no explanation of the function's purpose, or guarentees regarding its future availability will be made.
Error handling / reporting.
error ( STRING )
The error function allows user-functions to jump back to the prompt when some sort of error has occurred. The nature of the error is up to the user. When an error is detected the user simply calls error(). If no argument is supplied, error() will print the default message. Otherwise, error prints the string supplied as an argument, and jumps back to the prompt.
Jumping "back to the prompt" means execution of the current loop or function is terminated immediately and execution of any prompt-level statements is performed.
Evaluate expressions.
eval ( S )
The eval function evaluates the statement contained in the string argument S. eval returns the result of the statement in S. eval can be used within functions and can distinguish local and argument variables from global.
Before we go any further, we should note that eval is not really a necessary part of RLaB. Users should defintely not use it a a crutch as with some other matrix programming languages. The RLaB concept of variables, and the list class are more efficient ways of dealing with function evaluations and variable variable names than eval.
Examples:
> // Evaluate a simple string.
> // Demonstrate the ability to work with function
> // arguments.
>
> x=function(s,a){return eval(s);}
<user-function>
> str = "yy = 2 + x(\"2*a\", 3.5)"
str =
yy = 2 + x("2*a", 3.5)
> z = eval(str)
z =
9
> whos();
Name Class Type Size NBytes
eps num real 1 1 16
pi num real 1 1 16
str string string 1 1 22
yy num real 1 1 16
z num real 1 1 16
Total MBytes = 0.129062
> // First create a function that will eval a matrix.
>
> evalm = function ( m )
> {
> local (mnew, i)
>
> mnew = zeros (size (m));
> for (i in 1:m.n)
> {
> mnew[i] = eval (m[i]);
> }
>
> return mnew;
> };
>
> // Then create a string matrix...
>
> mstr = ["x + 1", "x + sqrt(x)" ;
> "cos(2*x)", "sin(sqrt(x))" ]
> x = 2
x =
2
>
> m = evalm(mstr)
m =
3 3.41
-0.654 0.988
>
> // Define a second function that does eval twice
>
> eval2m = function ( m )
> {
> local (mnew, i)
>
> mnew = zeros (size (m));
> for (i in 1:m.n)
> {
> mnew[i] = eval (eval (m[i]));
> }
>
> return mnew;
> };
>
> mstr = [ "E1", "E2" ;
> "E2", "E3" ]
mstr =
E1 E2
E2 E3
> E1 = "cos(2*x) + 3";
> E2 = "tan(x)";
> E3 = "exp(x)";
> m = eval2m(mstr)
m =
2.35 -2.19
-2.19 7.39
Check the existence of a variable.
exist ( VAR )
The exist function returns TRUE (1) if VAR exists, and FALSE (0), if VAR does not exist. VAR is any valid variable name.
If you need to know if a variable exists, and if it is a function or data, then use the exist function in conjunction with the class or type functions.
class, type, who, what
Exponential function.
exp ( X )
Exp returns the value of e (the base of natural logarithms) raised to the power of X. If the argument to exp is a matrix then an element-by-element operation is performed.
Factor a square matrix.
factor ( A )
The factor function computes the LU factorization of the input matrix A. Factor returns a list with 3 elements:
if A is a general matrix:
a matrix containing the LU factors
a vector containing the pivot indices
the inverse of the condition estimate
Factor utilizes the LAPACK subroutines DGETRF, DGECON or ZGETRF, ZGECON.
if A is a symmetric matrix:
a matrix containing the block diagonal matrix D, and the multipliers used to obtain L.
a vector containing the pivot indices
the inverse of the condition estimate
Factor utilizes the LAPACK subroutines DSYTRF, DSYCON or ZHETRF, ZHECON.
The user can overide factor's choice of solution type with the optional argument TYPE.
TYPE = "g" or "G" The general solution is used.
TYPE = "s" or "S" the symmetric solution is used.
Factor returns the results in the above format, so that they may be conveniently used with backsub for repetitive solutions. The user-function lu will separate the results from factor into separate L and U matrices.
backsub, inv, lu, solve
Discrete Fourier Transform.
fft ( X )
fft ( X, N )
Fft utilizes the FFTPACK subroutine CFFTF to compute a discrete forward Fourier transform of the input.
If fft is used with a second argument, N, then the matrix X is either padded with zeros, or truncated till it is of length N (if X is a vector), or has row dimension N (if it is a matrix).
Subroutine CFFTF computes the forward complex discrete Fourier transform (the Fourier analysis). equivalently , CFFTF computes the Fourier coefficients of a complex periodic sequence.
for j=1,...,n
c(j)=the sum from k=1,...,n of
c(k)*exp(-i*(j-1)*(k-1)*2*pi/n)
where i=sqrt(-1)
The argument X must be a matrix. If X is a row, or column matrix then a vector fft is performed. If X is a MxN matrix then the N columns of X are fft'ed.
ifft
Discrete time recursive filter.
filter ( B, A, X )
filter ( B, A, X, Zi )
Filter is an implementation of the standard difference equation:
y[n] = b(1)*x[n] + b(2)*x[n-1] + ... b(nb+1)*x[n-nb]
- a(2)*y[n-1] - ... a(na+1)*y[n-na]
The filter is implemented using a method described as a "Direct Form II Transposed" filter. More for information see Chapter 6 of "Discrete-Time Signal Processing" by Oppenheim and Schafer.
The inputs to filter are:
The numerator coefficients, or zeros of the system transfer function. The coefficients are specified in a vector like:
[ b(1) , b(2) , ... b(nb) ]
The denominator coefficients, or the poles of the system transfer function. the coefficients are specified in a vector like:
[ a(1) , a(2) , ... a(na) ]
A vector of the filter inputs.
Optional] The initial delays of the filter.
The filter outputs are in a list with element names:
The filter output. y is a vector of the same dimension as X.
A vector of the final values of the filter delays.
The A(1) coefficient must be non-zero, as the other coefficients are divided by A(1).
Below is an implementation of filter() in a r-file - it is provided for informational usage only.
# # Simplistic version of RLaB's builtin function filter() # Y = filter ( b, a, x ) # Y = filter ( b, a, x, zi ) # rfilter = function ( b , a , x , zi ) { local ( b , a , x , zi ) ntotal = x.nr * x.nc; M = b.nr * b.nc; N = a.nr * a.nc; NN = max ([ M, N ]); y = zeros (x.nr, x.nc); # Fix up pole and zero vectors. # Make them the same length, this makes # filter's job much easier. if (N < NN) { a[NN] = 0; } if (M < NN) { b[NN] = 0; } # Adjust filter coefficients if (a[1] == 0) { error ("rfilter: 1st A term must be non-zero"); } a[2:NN] = a[2:NN] ./ a[1]; b = b ./ a[1]; # Create delay vectors and load inital delays. # Add an extra term to vi[] to make filter's # job a little easier. This extra term will # always be zero. v = zeros (NN, 1); vi = zeros (NN+1, 1); if (exist (zi)) { vi[1:NN] = zi; } # # Do the work... # for (n in 1:ntotal) { v[1] = b[1]*x[n] + vi[2]; y[n] = v[1]; for (k in 2:NN) { v[k] = b[k]*x[n] - a[k]*v[1] + vi[k+1]; vi[k] = v[k]; } } return << y = y; zf = v >>; };
Find non-zeros.
find ( A )
Find returns a matrix that contains the indices of the non-zero elements of the input matrix A.
A common usage for find, is the selection of matrix elements that meet certain criteria.
Example:
> a = rand(4,4)
a =
matrix columns 1 thru 4
0.647 0.665 0.655 0.299
0.333 0.0847 0.129 0.265
0.0369 0.204 0.91 0.7
0.162 0.167 0.112 0.95
> x = a[ find( a < .1 ) ]
x =
matrix columns 1 thru 2
0.0369 0.0847
Test variable for finite values.
finite ( A )
finite returns a matrix, the same size as the input (A), consisting of ones and zeros. The elements of the return matrix are 1 if the corresponding value of A is finite, or zero if the corresponding element of A is an Inf or a NaN.
Example:
> a = [1, inf(), 3; 4, 5, 6; inf(), 8, nan()]
a =
1 inf 3
4 5 6
inf 8 nan0x80000000
> finite (a)
1 0 1
1 1 1
0 1 0
isinf, isnan
Largest integral value not greater than X
floor ( X )
Floor returns the largest integer not greater than the argument. If the argument is a MATRIX then the floor operation is performed on an element-by-element basis.
ceil, int
Set the printing format.
format ( )
format ( PRECISION )
format ( WIDTH, PRECISION )
format ( [ WIDTH, PRECISION ] )
Format sets the output print format for all numeric output. If no arguments are supplied, then the output print formats are reset to the default values.
represents the precision with which numbers will be printed. For instance, if PRECISION has a value of 4, then 4 significant digits will be printed for numeric values.
represents the minimum field width of the formatted output.
Format returns a 2-element matrix contains the previous width and precision values. Subsequently, this matrix can be used to reset format.
Example:
> 123456789.123456789
1.235e+08
> format(10);
> 123456789.123456789
123456789.1
> format();
> a = rand(3,3)
a =
matrix columns 1 thru 3
1 0.3331 0.6646
0.9745 0.03694 0.08467
0.6475 0.1617 0.2041
> format(10);
> a
a =
matrix columns 1 thru 3
0.9999996424 0.3330855668 0.6646450162
0.9745196104 0.03694454208 0.08467286825
0.6474838853 0.1617118716 0.2041363865
> format(15,10);
> a
a =
matrix columns 1 thru 3
0.9999996424 0.3330855668 0.6646450162
0.9745196104 0.03694454208 0.08467286825
0.6474838853 0.1617118716 0.2041363865
Formatted printing to a file.
fprintf ( filestring, formatstring, VARi ... )
The RLaB fprintf is a limited feature version of the C-language fprintf. The features are limited because RLaB does not support all of the data types the C-language does.
The 1st string argument
determines the file to which the output is sent. If the
filename starts with a |
then a pipe is opened to the
process following the |
and the output is written to
the pipe. For example:
> fprintf("|gnuplot"; "set term X11\n plot sin(x)\n");
will create the sub-process gnuplot, and pipe the command string to it.
A valid fprintf format string.
Are any number of constants or variables that match the format string. fprintf cannot print out vector, matrix, or list objects as a whole. Valid print objects are strings, constants, and scalars.
Example:
> for (i in 1:a.n) { fprintf("stdout", "element %i: %20.10g\n", i, a[i]); }
element 1: 1.414213562
element 2: 4.242640687
element 3: 2.828427125
element 4: 5.656854249
printf, sprintf, write, read
Binary stream input.
fread ( FILENAME, NITEMS, TYPE, SWAPB )
fread reads NITEMS of type TYPE from FILENAME (a string) and returns the result in a numeric matrix.
Allowable arguments are:
Number of objects of type TYPE to read from FILENAME. If NITEMS is inf(), then fread will read from FILENAME until end-of-file is reached.
"char"
"unsigned char"
"short int"
"unsigned int"
"int"
"float"
"double"
0 Do not swap bytes in a word (default).
1 Do swap the bytes in each word.
FILES, fseek, fwrite, close, open, write
Convert floating-point number to fractional and integral components
frexp ( A )
Frexp returns a list with elements f and e Frexp splits A into a normalized fraction in the interval:
0.5 <= abs(f) <= 1
which is returned in f, and a power of 2, which is returned in e. If A is zero, then both e and f are zero.
Frexp operates on REAL matrices of any dimension.
log, log10, log2, exp, mod
Reposition a stream.
fseek ( FILENAME, OFFSET )
fseek ( FILENAME, OFFSET, OFFSET )
fseek sets the current position in FILENAME. a subsequent read will access data beginning at the new position. fseek is an interface to the C library function of the same name. OFFSET is specified in bytes.
"SEEK_SET" beginning of file (default)
"SEEK_CUR" current position
"SEEK_END" end of file
FILES, fread, open, close
Convert sparse storage to full (dense) storage.
full( A )
full converts its argument from the sparse storage format to the full, or dense, storage format.
Example:
> d = [1, 1, 10;
> 2, 4, 20;
> 3, 1, 12;
> 5, 2, 13;
> 1, 4, 3];
> s = spconvert(d)
(1, 1) 10
(1, 4) 3
(2, 4) 20
(3, 1) 12
(5, 2) 13
> f = full(s)
10 0 0 3
0 0 0 20
12 0 0 0
0 0 0 0
0 13 0 0
sparse, spconvert
Binary stream output.
fwrite ( FILENAME, TYPE, DATA )
fwrite writes DATA to the file identified by FILENAME. DATA is cast, or converted to the data type identified in TYPE. fwrite roughly mimincs the C programming language's fwrite library function.
DATA can either be a dense numeric matrix, or a string matrix. The size of the matrix does not need to be specified because the entire matrix is written.
If DATA is a string matrix, then the first character of each element is written to FILENAME, after being coerced to type TYPE.
Allowable arguments are:
"char"
"unsigned char"
"short int"
"unsigned int"
"int"
"float"
"double"
FILES, fread, fseek, close, open, write
Get an environment variable
getenv ( NAME )
Getenv searches the current environment for a variable with name NAME. The value of the environment variable is returned as a string.
Exactly how getenv behaves is depends upon the underlying operating system implementation. On UNIX system getenv will return a NULL string if the environment variable does not exist.
putenv
Get a line of input.
getline ( FN )
getline ( FN, LL )
Getline returns an N-element list which contains all of the tokens from a line in the file described by FN. The tokens are delimited by whitespace. Numbers are installed in the list as numeric scalars, everything else is installed as scalar strings.
The list elements have numeric indices, and are numbered from 1 to N. The 1st element containing the 1st token on the line, and the Nth element containing the last token on the line. The newline is not returned as a token.
Getline will also recognize everything enclosed within a pair
of "
as a string, including escape characters.
Getline will always return a list-object. When an empty-line has been read, getline returns an empty list. Getline will terminate on an End-Of-File (EOF).
The filename can be a string that specifies a sub-process (see
help FILES
), in which case getline will run the
sub-process, and read from the process's standard output.
The second, and optional argument, LL, forces getline to return the entire line (including the newline) as a string, without any parsing. If LL is <= 0, then getline will read lines as long as 512 characters. If LL > 0, then getline will read lines as long as LL characters. The return value is a single string, not a list, when LL is used. If getline encounters and EOF, while LL is being used, a numeric value of 0 is returned.
Examples:
To get input interactively:
> printf( "Enter a string and a number: " ); x = getline( "stdin" );
Enter a string and a number: test-string 1.234e5
> show(x)
name: x
class: list
n: 2
> x.[1]
test-string
> x.[2]
2 =
1.23e+05
Given a file named `test', which contains the following lines:
jcool 259 4 1075 822 vt01 S Dec 29 9:32 X :0 -p 1 -s 5
jcool 256 0 21 0 console S Dec 29 0:00 startx
jcool 261 0 338 88 console S Dec 29 0:16 twm
jcool 288 8 635 333 ? S Dec 29 2:00 emacs
jcool 287 0 408 65 console S Dec 29 0:01 xclock
> tmp = getline( "test" );
would produce a list variable named `tmp' with 16 elements: tmp.[1] would be the string "jcool" and tmp.[16] would be the number 5. The next call to getline() would read the second line in the file, and create a new list containing those elements.
The above could also have been done with:
> tmp = getline( "|ps -aux | grep jcool" );
Which would open a readable pipe to the "ps -aux | grep jcool" command and grab a line at a time from the process.
To read the entire contents of a file:
if (length (ans = getline("stdin")))
{
// do something with ans
else
// finish up
}
Since getline returns an empty list when there is no input, we can tell when to terminate the input loop by checking the length of the returned list.
Using the optional second arguemnt to getline we can get old-style Fortran formattted output. For example, we have a file filled with:
0.1285186E+000.1463163E+000.0000000E+000.0000000E+000.0000000E+000.0000000E+00
0.0000000E+000.0000000E+000.0000000E+000.0000000E+000.7322469E-010.5245288E-01
0.0000000E+00-.9399651E-010.2397120E-01-.6551484E-010.2616772E+020.5796479E-01
0.0000000E+000.2500000E+000.7788281E-010.2121489E-010.0000000E+00-.1345507E+00
0.1516225E-01-.1284981E+000.1136876E+020.3010250E-010.0000000E+00-.2500000E+00
we can do:
> lv = strtod (getline (FN, 13));
and get a vector with the numeric values for each line.
strsplt
Online Help
help
help NAME
Prints a list of available help files. Help
first prints out the help files in the default help
file directory. Next, the directories identified in
the environment variable RLAB_SEARCH_PATH
are
searched for files ending in `.r' -- rfiles. A list of
each directory's rfiles is printed on the standard
output.
Prints out the help file
identified by NAME. If NAME matches a
file in the default help directory, that file is paged
to the standard output. If no match is found, the
directories identified in the environment variable
RLAB_SEARCH_PATH
are searched for matches. The
first match is paged to the standard output. The rfile
extension (`.r') is not considered when checking for
matches.
If the user's environment does not contain
RLAB_SEARCH_PATH
, then the default search-path is
used. The default is set at compile time. Normally the default
is ".", the current working directory.
Help is a command, not an expression or statement. Therefore, it must be issued on a line by itself, and cannot occur in the midst of another statement or expression.
rfile
Find the Hessenberg form of a matrix.
hess( A )
Hess finds the Hessenberg from of a matrix. Hess takes a single matrix, A, as input, and returns a list with two elements, h, and p.
A = p * h * p' where A is the input
Hess uses the LAPACK subroutines DGEHRD, DORGHR, and ZGEHRD, ZUNGHR.
Inverse Discrete Fourier Transform
ifft ( X )
ifft ( X, N )
Ifft utilizes the FFTPACK subroutine CFFTB to compute a discrete Fourier transform of the input. The output is scaled by 1/N, so that a call to fft() followed by a call to ifft() will reproduce the original input.
If ifft is used with a second argument, N, then the matrix X is either padded with zeros, or truncated till it is of length N (if X is a vector), or has row dimension N (if it is a matrix).
Subroutine CFFTB computes the backward complex discrete Fourier transform (the Fourier synthesis). equivalently, CFFTB computes a complex periodic sequence from its Fourier coefficients.
for j=1,...,n
c(j)=the sum from k=1,...,n of
c(k)*exp(i*(j-1)*(k-1)*2*pi/n)
where i=sqrt(-1)
The argument X must be a matrix. If X is a row, or column matrix then a vector ifft is performed. If X is a MxN matrix then the N columns of X are ifft'ed.
fft
Imaginary part
imag ( A )
Imag returns the imaginary part of an A.
Example:
> z = pi + 3*pi*1j
3.14 + 9.42i
> imag(z)
9.42
conj, real
Create a variable with value of infinity.
inf ( )
Inf returns a scalar whose value is infinity, according to IEEE-754. Unlike NaN, inf == inf should return TRUE (1).
nan
Return an integer.
int ( A )
Int returns its argument after it has been "cast" to an integer. If the argument is a MATRIX then the int operation is performed on an element-by-element basis.
int has the effect of truncating the input, for example:
> int(1.1)
1
> int(1.5)
1
> int(1.999)
1
ceil, floor
Test for values of infinity.
isinf ( A )
isinf returns TRUE (1) if A is Infinity (according to IEEE-754). If A is a vector or a matrix the test is performed element-by-element, and a matrix the same size as A is returned.
Infs can usually be created by attempting to divide by zero, or using the builtin inf function.
Example:
> a = [1, 2, 3; 4, 5, inf(); 7, 8, 9]
a =
1 2 3
4 5 inf
7 8 9
> isinf (a)
0 0 0
0 0 1
0 0 0
isnan, finite
Test for NaN values.
isnan ( A )
isnan returns TRUE (1) if A is a NaN (Not A Number). If A is a vector or a matrix the test is performed element-by-element, and a matrix the same size as A is returned.
NaNs can be create by the 0/0 operation on most computers.
Example:
> a = [1, 2, 3; 4, 5, nan(); 7, 8, 9]
a =
1 2 3
4 5 nan0x80000000
7 8 9
> isnan (a)
0 0 0
0 0 1
0 0 0
inf, isinf, finite, nan
Test matrix for symmetry
issymm ( A )
Issymm returns TRUE (1) if the argument A is a symmetric (or Hermitian) matrix, and FALSE (0) if A is not symmetric (Hermitian).
Multiply floating point number by integral power of 2
ldexp ( X , EXP )
Ldexp returns a numeric matrix which contains the value(s) resulting from the operation:
X * 2^EXP
The dimensions of X and EXP must be the same. Optionally, EXP can be a scalar, independent of the size of X.
frexp
Return the length of an object.
length ( A )
The length function returns the length of vector A. It
is equivalent to max (size (A))
, when A is
numeric.
To summarize:
max (size (A))
number of characters in a string.
number of elements in list.
show, size
Load / execute the instructions in a file.
load( filename )
Load opens the file named filename and reads its contents as though a user were typing the contents at the command line. Thus a user can use load to enter data, user-functions, or execute repetitive commands saved in a file. there is no limit to the number of functions, or regular statements that can exist in a file called by load.
Immediately after the the input is read, load closes the file, so that subsequent calls to load will re-open the file.
Load requires that a complete file specification be provided. If the file is in the present working directory, then only the filename is necessary otherwise, a complete path is required.
In most cases the rfile command is simpler to use.
Example:
// load the roots() function into memory
> load( "roots.r" )
rfile
Logarithmic function.
log ( A )
Log returns the natural logarithm of it's argument. If the argument is a VECTOR or MATRIX an element-by-element log operation is performed.
Base-10 logarithm.
log10 ( A )
Log10 returns the base-10 logarithm of it's argument. If the argument is a MATRIX, an element-by-element log10 operation is performed.
log10 is not implemented yet for COMPLEX data.
Unbiased exponent.
logb ( A )
Logb returns the unbiased exponent of its REAL argument.
This function depends upon operating system support. Logb is part of the IEEE-754 standard, and should be available on most machines that implement this standard in one form or another.
frexp
Maximum function
max ( A )
max ( A, B )
Max returns the maximum value(s) contained in the matrix A. If the argument is a vector, then the largest value is returned. If A is a MxN matrix, then a row-vector of N columns is returned containing the maximum value from each column of A.
If max is used with two arguments, then max returns a matrix the same size as A and B filled with the largest elements from A and B.
When matrix elements are complex the absolute value is used for comparison purposes.
maxi, min, mini
Maximum value indices
maxi ( A )
Maxi returns the index of the maximum value contained in matrix. If the input argument (A) is a vector, then the index of the largest value is returned. If A is a MxN matrix, then a row-vector of the column indices of the largest column values of A is returned.
max, min, mini
Return an object's member names.
members ( L )
The members function takes a variable as an argument (L), and returns a string-vector containing the object's member names.
For example: x = members ($$)
will
create a row-vector and assign it to x. The row-vector
will contain the names of all the elements in the
global-symbol-table.
The members function is probably most useful when used in conjunction with for-loops. The result of members can be used as the loop index, allowing users to operate on the elements of an object. For example:
ll = << a = rand(3,3); b = rand(3,3); c = rand(3,3) >>;
for (i in members (ll)) { ll.[i] = diag(ll.[i]); }
Minimum function.
min ( A )
min ( A, B )
Min returns the minimum value(s) contained in the matrix A. If the argument is a vector, then the smallest value is returned. If A is a MxN matrix, then a row-vector of N columns is returned containing the minimum value from each column of A.
If min is used with two arguments, then min returns a matrix the same size as A and B filled with the smallest elements from A and B.
When matrix elements are complex the absolute value is used for comparison purposes.
mini, max, maxi
Minimum value indices.
mini ( A )
Mini returns the index of the minimum value contained in matrix. If the input argument (A) is a vector, then the index of the smallest value is returned. If A is a MxN matrix, then a row-vector of the column indices of the smallest column values of A is returned.
max, maxi, min
Compute the matrix norm.
mnorm ( A )
mnorm ( A , TYPE )
The first form defaults to computing the 1-norm of the input matrix. The second form allows the user to specify the desired type of matrix norm with a string argument.
M
or m
returns max(abs( A ))
1
, O
or o
return the 1-norm (default), the largest column sum (max(sum(abs(A)))).
2
returns the matrix 2-norm (largest singular value)
I
or i
returns the infinity-norm, the largest row sum (max(sum(abs(A')))).
F
, f
, E
or e
returns the Frobenius norm.
LAPACK subroutines DLANGE and ZLANGE are used to compute all norms, except the 2-norm.
Obscure feature: If TYPE is Inf (the output from
inf()
, for example), then norm will compute the
Infinity norm of the matrix A.
Example:
> a = magic(4)
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
> mnorm ( a )
34
> mnorm ( a , "m" )
16
> mnorm ( a , "1" )
34
> mnorm ( a , "2" )
34
> mnorm ( a , "i" )
34
> mnorm ( a , inf() )
34
Floating point remainder
mod( A, B )
The mod routine returns the floating point remainder of the division of A by B: zero if B is zero or if A/B would overflow; otherwise the number F with the same sign as A, such that A = iB + F for some integer i, and |f| < |B|.
When the arguments to mod are two matrices, then an element by element mod is performed. Mod works on complex number also.
mod(x,y) is equivalent to:
n = int( x/y )
mod(x,y) = x - y.*n
mod is implemented via libm.a fmod function.
Return a NaN (Not a Number)
nan ( )
Nan returns a NaN (Not a Number) according to IEEE-754. One way to determine if a variable contains a NaN is to test it against itself.
NaN == NaN
Should always return FALSE (0).
inf
Solve systems of nonlinear equations (nonlinear least squares)
nlleastsq ( feval, neq, guess )
nlleastsq is a high level interface to the MINPACK function: LMDIF1. nlleastsq is only availble as a builtin function if your Rlab installation was compiled with MINPACK enabled, and you have the MINPACK library installed on your system. From the MINAPCK documentation:
The purpose of lmdif1 is to minimize the sum of the squares of m nonlinear functions in n variables by a modification of the levenberg-marquardt algorithm. this is done by using the more general least-squares solver lmdif. the user must provide a subroutine which calculates the functions. the jacobian is then calculated by a forward-difference approximation.
The arguments to ode are:
The user-supplied function which calculates the functions, and returns a vector of the solution.
feval = function ( m, n, x, fvec, iflag )
{
/* Do something */
return fvec;
};
The number of equations.
The initial guess at the solution.
Integrate Ordinary Differential Equations.
ode ( rhsf, tstart, tend, ystart, dtout, relerr, abserr, uout )
ode integrates a system of N first order ordinary differential equations of the form:
dy(i)/dt = f(t,y(1),y(2),...,y(N))
y(i) given at t .
The arguments to ode are:
A function that evaluates dy(i)/dt
at
t
. The function takes two arguments and returns
dy/dt
. An example that generates dy/dt
for Van der Pol's equation is shown below.
vdpol = function ( t , x )
{
xp = zeros(2,1);
xp[1] = x[1] * (1 - x[2]^2) - x[2];
xp[2] = x[1];
return xp;
};
The initial values of y, y(tstart)
.
The initial value of the independent variable.
The final value of the independent variable.
The output interval. The vector y
will
be saved at tstart, increments of tstart
+ dtout, and tend. If dtout is
not specified, then the default is to store output at
101 values of the independent variable.
The relative error tolerance. Default value is 1.e-6.
The absolute error tolerance. At each step, ode requires that:
abs(local error) <= abs(y)*relerr + abserr
For each component of the local error and solution vectors. The default value is 1.e-6.
Optional. A user-supplied function that computes an arbitrary output during the integration. uout must return a row-matrix at each dtout during the integration. It is entirely up to the user what to put in the matrix. The matrix is used to build up a larger matrix of the output, with one row for each dtout. The resulting matrix is returned by ode when the integration is complete.
The Fortran source code for ode is completely explained and documented in the text, "Computer Solution of Ordinary Differential Equations: The Initial Value Problem" by L. F. Shampine and M. K. Gordon.
Example:
//
// Integrate the Van der Pol equation, and measure the effect
// of relerr and abserr on the solution.
//
vdpol = function ( t , x )
{
xp = zeros(2,1);
xp[1] = x[1] * (1 - x[2]^2) - x[2];
xp[2] = x[1];
return xp;
};
t0 = 0;
tf = 10;
x0 = [0; 0.25];
dtout = 0.05;
relerr = [1e-6, 1e-5, 1e-4, 1e-3, 1e-2, 1e-1];
abserr = relerr;
//
// Baseline
//
xbase = ode( vdpol, 0, 20, x0, 0.05, 1e-9, 1e-9);
results = zeros (relerr.n, abserr.n);
elapse = zeros (relerr.n, abserr.n);
//
// Now loop through the combinations of relerr
// and abserr, saving the results, and computing
// the maximum difference.
//
"start testing loop"
for (i in 1:abserr.n)
{
xode.[i] = <<>>;
for (j in 1:relerr.n)
{
printf("\t%i %i\n", i, j);
tic();
xode.[i].[j] = ode( vdpol, 0, 20, x0, 0.05, relerr[j], abserr[i]);
elapse[i;j] = toc();
// Save results
results[i;j] = max (max (abs (xode.[i].[j] - xbase)));
}
}
> results
results =
matrix columns 1 thru 6
1.97e-05 0.000297 0.000634 0.00815 0.078 1.44
0.000128 7.89e-05 0.000632 0.00924 0.0732 1.61
0.000647 0.000625 0.00112 0.0147 0.0995 1.46
0.00355 0.00352 0.00271 0.0118 0.0883 0.862
0.0254 0.0254 0.0254 0.104 0.218 1.72
0.513 0.513 0.513 0.589 0.467 1.82
Each row of results is a function of the absolute error (abserr) and each column is a function of the relative error (relerr).
ode4
Create a matrix filled with ones.
ones ( M , N )
ones ( A )
Create a matrix of ones. If the input is two scalars, then create a matrix of 1s with dimensions NxM.
If the input is a 2 element matrix, then create a matrix with row and column dimensions equal to A[1] and A[2] respectively. This is useful when used in conjunction with size():
ones( size( X ) )
will return a matrix of ones the same size as X
.
zeros
Open a file for reading.
open ( FILENAME, MODE )
open ( FILENAME, MODE, BUFFSIZE )
Open will open a file or a pipe for read or write operations. Open allows the user to specify the mode of operation, and optionally a buffer-size for I/O. The "normal" UNIX modes are:
read access
write access
append: open for writing at end of file, or create for writing
Buffersize is specified in bytes. If BUFFSIZE is not specified the system defaults are used.
Other operating systems may have different mode keys. Look at the API documentation for fopen on your system to find what mode values are acceptable.
close, printf, fprintf, read, readb, readm, write, writeb, writem
Formatted printing.
printf ( formatstring , VARi ... )
The RLaB printf is a limited feature version of the C-language printf(). The features are limited because RLaB does not support all of the data type the C-language does.
must be a valid printf format string
are any number of constants or variables that match the format string. printf cannot print out vector, matrix, or list objects as a whole. Valid print objects are strings, constants, and scalars.
The following shows how one might print out the annotated contents of a matrix.
for(i in 0:size(a)[0]-1)
{
for(j in 0:size(a)[1]-1)
{
printf("a[%i;%i] = %f\n", i, j, a[i;j]);
}
}
However, it would be more efficient to use:
> writem("stdout", a);
fprintf, sprintf, write, read
Product.
prod ( A )
Compute the product of the elements of A (if A is a vector). If A is a matrix return a row vector containing the product of each column.
Change or add an environment variable.
putenv ( STRING )
putenv takes a single argument, STRING, of the form:
"NAME=VALUE"
putenv make the value of the environment variable NAME
equal
to VALUE
by altering an existing variable or creating a new
one.
Exactly how putenv behaves is depends upon the underlying operating system implementation.
On most Unix systems putenv will return non-zero if an error occurred, and zero otherwise.
getenv
QR decomposition
qr ( A )
qr ( A, "p"
)
Qr computes the QR decomposition of the input matrix A such that:
A = Q * R
or
A*p = Q * R
Qr returns a list containing elements q and
r. Optionally, qr can take a second argument,
"p"
which tells qr to perform column pivoting when
computing q and r. The permutation matrix
p is returned in the same list as q and
r.
Qr utilizes LAPACK subroutines DGEQRF and DORGQR for REAL inputs, and ZGEQRF and ZUNGQR for COMPLEX inputs. When column pivoting is requested the LAPACK subroutines DGEQPF, and ZGEQPF are used.
Quit, terminate an Rlab session.
quit
The statement quit
causes RLaB to stop execution
immediately. Quit is an executable statement, that is, it is
not built into the parser, it only takes effect when executed.
This allows users to embed a quit statement in a branch of a
conditional statement.
RLaB can also be stopped by a ctrl-d (hold down the control key while typing `d').
Random number generator.
rand ( )
rand ( nrow, ncol )
rand ( DTYPE, D1 )
rand ( DTYPE, D1, D2 )
produces a random scalar.
produces a randomly generated MATRIX with row dimension X, and column dimension Y.
changes the distribution used when generating random numbers. The value of DTYPE determines the subsequent parameters.
Types of distributions:
rand ( "beta" , A , B )
Sets the generator to return a random deviate from the beta
distribution with parameters A
and B
. The
density of the beta is
x^(a-1) * (1-x)^(b-1) / B(a,b) for 0 < x < 1
rand ( "chi" , DF )
Sets the generator to return a random deviate from the
distribution of a chi-square with DF
degrees of freedom
random variable.
rand ( "exp" , AV )
Sets the generator to return a random deviate from an
exponential distribution with mean AV
.
rand ( "f" , DFN DFD )
Sets the generator to return a random deviate from the F
(variance ratio) distribution with DFN
degrees of
freedom in the numerator and DFD
degrees of freedom in
the denominator.
rand ( "gamma" , A , R )
Sets the generator to return a random deviate from the gamma distribution whose density is:
(A**R)/Gamma(R) * X**(R-1) * Exp(-A*X)
rand ( "nchi" , DF , XNONC )
Sets the generator to return a random deviate from the
distribution of a noncentral chi-square with DF
degrees
of freedom and noncentrality parameter XNONC
.
rand ( "nf" , DFN , DFD, XNONC )
Sets the generator to return a random deviate from the
noncentral F (variance ratio) distribution with DFN
degrees of freedom in the numerator, and DFD
degrees of
freedom in the denominator, and noncentrality parameter
XNONC
.
rand ( "normal" , AV , SD )
Sets the generator to return a random deviate from a normal distribution with mean, AV, and standard deviation, SD.
rand ( "uniform" , LOW , HIGH )
Sets the generator to return a uniform double between
LOW
and HIGH
.
rand ( "bin" , N , P )
Returns a single random deviate from a binomial distribution
whose number of trials is N
and whose probability of an
event in each trial is P
.
rand ( "poisson" , AV )
Sets the generator to return a random deviate from a
Poisson distribution with mean AV
.
rand ( "default" )
Resets the random number generator to the default generator, which generates a distributed random variable in the interval 0 -> 1. The interval endpoints are not returned.
> rand()
0.368
> rand(4)
vector elements 1 thru 4
0.983 0.535 0.766 0.646
> rand(3,3)
matrix columns 1 thru 3
0.767 0.152 0.347
0.78 0.625 0.917
0.823 0.315 0.52
> rand("norm", 10.0, 2.0 );
> rand(10)
vector elements 1 thru 5
9.86 11.8 12.1 7.35 8.76
vector elements 6 thru 10
10.5 7.44 11.1 6.93 9.87
rand uses the RANLIB library, authored by B. W. Brown and J. Lovato under grant CA-16672 from the National Cancer Institute.
srand
Condition number.
rcond( A )
Rcond computes an estimate of the condition number of the input matrix, A. rcond() uses the LAPACK routines DGECON, or ZGECON.
Probably the most published way to compute the condition of a matrix is:
Kcond = ||A|| * ||inv(A)||
Another method is to use the 1st and last singular values of A:
Kcond = sigma(1)/sigma(n)
rcond computes an ESTIMATE of the condition number without computing all of the columns of inv(A). For more information see the LAPACK User's Guide.
See Also inv, det, lu
Read data from a file.
read ( FILENAME )
read ( FILENAME, LIST )
read reads the file identified by the FILENAME. The file is opened with read access, and all of the contents are read. The file identified by the 1st argument must contain data that is in RLaB binary format. The entities in the file are installed in the global symbol table, overwriting any existing entities. Upon completion the file is closed.
Example:
read ("bunch_of_data_in_a_file");
The second form of the read function allows the data in the file to be read into list variable LIST. The global-symbol-table is untouched (except for LIST).
Example:
read ("bunch_of_data", X);
The contents of the file bunch_of_data
are read and
stored in the list variable X
. Except for the
creation/modification of the variable X
, the
global-symbol-table is unchanged.
Read will read most numeric matrices written by MATLAB's save command. Read will not read MATLAB text matrices, or sparse matrices, or matrices written with reduced precision (integer format). Read will not read Cray, or VAX binaries. Read will read big and little endian binaries - this includes binaries written from PCs, DEC Risc, Macintosh, Sun, and Apollo.
FILES, close, getline, read, readm, writem
Read ASCII data from a file.
read_ascii ( FILENAME )
read_ascii ( FILENAME, LIST )
read_ascii reads the file identified by the FILENAME. The file is opened with read access, and all of the contents are read. The file identified by the 1st argument must contain data that is in RLaB ASCII format. The entities in the file are installed in the global symbol table, overwriting any existing entities. Upon completion the file is closed.
Example:
read_ascii ("bunch_of_data_in_a_file");
The second form of the read function allows the data in the file to be read into list variable LIST. The global-symbol-table is untouched (except for LIST).
Example:
read_ascii ("bunch_of_data", X);
The contents of the file bunch_of_data
are read and
stored in the list variable X
. Except for the
creation/modification of the variable X
, the
global-symbol-table is unchanged.
write_ascii, FILES, close, getline, read, readm, writem
Read ASCII matrices from a file.
readm ( FILENAME )
readm ( FILENAME, [ NR,NC ] )
readm ( FILENAME, NROW )
Readm reads a generic matrix of data from the file denoted by the string argument FILENAME. The return value is the newly created matrix. The second, and optional, argument is a two-element matrix that specifies the size of the matrix to read.
If the matrix size is not specified, then the matrix is filled row-wise with the input data. Otherwise (if the size is specified), the matrix if filled column-wise, as the input is read.
The file format is generic ASCII. The rows of the matrix are separated by newlines, and the columns are separated by whitespace. Unnecessary newlines, either before, or after the data will confuse readm, and will probably result in an error message. Only one matrix can be stored in a file. If you need to store more than one matrix in a file, use write, and read.
Readm can only read in numeric matrices. The result of reading in string matrices is undefined.
Example:
1 2 3 4
5 6 7 8
9 10 11 12
The above values in a file called "test" would be read in like:
> a = readm("test")
a =
matrix columns 1 thru 4
1 2 3 4
5 6 7 8
9 10 11 12
Readm exists to read in data from other programs. In many cases a simple awk script will filter the other programs output into one or more columns of data. readm will read the data into the matrix, then the matrix can be reshaped if necessary.
Notes:
Readm has no idea how many rows are in the matrix it is reading. This is because readm can work with pipes and process output where it gets the matrix as a stream. Readm uses a heuristic to guess how many rows of the matrix to allocate at one time. A second, optional argument, NROW can be specified if the heuristic does not yield the performance you desire. The heuristic is purposely memory conservative.
readm ( "filename" , NROW )
reshape, getline, open, read, write, writem
Specify program dependencies/requirements.
require NAME
The require command takes Rfile names as operands, and checks
the workspace for a function variable called NAME. If
that function exists, then no action is taken. If the function
does not exist, then the file NAME.r
is loaded.
More than one NAME can be given on the same line. Continuations are not allowed.
NAME can contain the `.r' extension that distinguishes Rfiles (by convention), or NAME can omit the `.r' extension. In either case a workspace variable without the `.r' extension is checked for.
Example:
> require roots poly.r bode
The require command syntax is identical to the rfile command, with the obvious exception of the initial keyword.
The rules for searching the user's RLAB2_PATH
are the
same as those used with the rfile command.
rfile, load
Reshape a matrix
reshape ( A, nrow, ncol )
Reshape does what its name implies, it reshapes the input matrix so that the return value has the number of rows and columns specified by the last two arguments. Reshape will not reshape the matrix if the product of the new row and column dimensions does not equal the product of the existing row and column dimensions.
Examples:
m = [1,2,3;4,5,6;7,8,9];
mrow = reshape(m, 1, 9); // converts m to a row matrix
mcol = reshape(m, 9, 1); // converts m to a column matrix
Load an rfile.
rfile
rfile NAME
Prints a list of all the files with a `.r'
suffix. The list is compiled by searching the
directories contained in the environment variable
RLAB2__PATH
.
Loads the contents of the file denoted by NAME into the workspace. The NAME argument is NOT a string, and does not have to include the `.r' suffix.
Allowable names for rfiles are filenames that start with:
A digit, or a letter (a-z or A-Z).and contain:
digits, letters, and/or-
,_
,.
You may not be able to use all the possible filenames allowed by the host operating system.
If the user's environment does not contain RLAB2_PATH
,
then the default search-path is used. The default is set at
compile time. Normally the default is ".", the current working
directory.
Rfile is a command, not an expression or statement. Therefore, it must be issued on a line by itself, and cannot occur in the midst of another statement or expression. The rfile command cannot be continued across lines (no continuations).
The command `rfile NAME' can be used more than once. Each time the command is issued the file `NAME.r' is loaded.
The rfile command tries to be friendly. If you give it a string without the `.r' extension, it will automatically add one for you. If you give is a string with the `.r' extension, it will leave it alone.
The contents of the named file can be any valid RLaB commands or functions. There is no limit to the number of functions that a file can contain. Additionally, a mixture of commands, and function definitions can be included in the same file.
Example:
> rfile roots.r poly bode
help, load, require
Round to the nearest integer.
round ( A )
Round returns the nearest integer value to its floating point argument X as a double-precision floating point number. The returned value is rounded according to the currently set machine rounding mode. If round-to-nearest (the default mode) is set and the difference between the function argument and the rounded result is exactly 0.5, then the result will be rounded to the nearest even integer.
Round uses the libm.a function rint. If your machine does not have rint, then the supplied rint is used.
ceil, int, floor
Schur decomposition.
schur ( A )
The schur function returns a list containing elements t and z, such that:
A = z * t * z'
If A is real, the t is in "Real-Schur" form. The
"Real-Schur" form is block upper-triangular with 1-by-1 and
2-by-2 diagonal blocks; each 2-by-2 diagonal block has its
diagonal elements equal and its off-diagonal elements of
opposite sign. The eigenvalues of the 2-by-2 block:
[a, b; c, a]
are: a +/- sqrt(b*c)
schur uses the LAPACK subroutines DGEES, and ZGEES.
Return the sign of A
sign ( A )
For real scalar argument, sign returns:
1 if A > 0
0 if A == 0
-1 if A < 0
For a complex scalar sign returns:
A ./ abs (A)
sign performs its operation on real and complex matrices in an element by element fashion.
Compute the sin.
sin ( A )
RLaB trigonometric functions are designed to take scalars, and matrices as arguments. The return value is the input argument with the trigonometric operation performed element by element.
All the trigonometric functions use the C language math library functions, so details about the ranges and error conditions can be found by examining the appropriate man pages on your system.
Return the size of an object.
size ( A )
The size function returns the size of the argument.
size returns a matrix whose 1st element is the number of rows, and whose 2nd element is the number of columns.
size returns a matrix whose 1st element is the number of rows, and whose 2nd element is the number of columns. If the length of a particular string is desired, then the length function must be used.
size returns the number of elements in the list.
length, show
Return the size of an object in bytes.
sizeof ( A )
The sizeof function returns the number of bytes of data in the argument A.
size, who, whos
Put RLaB to sleep.
sleep ( sleepval )
Sleep is an interface to the POSIX.1 sleep system function. The argument, sleepval specifies the number of seconds the process should sleep for.
The return value is either zero or the number of seconds left to sleep (if the sleep has been interrupted).
Solve linear equations.
solve ( A, B )
solve ( A, B, TYPE )
Solve solves a system of linear equations:
A * X = B
is the coefficient matrix.
is the right hand side.
is the solution.
B can contain multiple right-hand-sides, one in each column. Solve returns a matrix of the solutions, X, where each column of the solution corresponds to a column of B.
Solve uses the LAPACK subroutines DGETRF, and ZGETRF if A is general.
Solve uses the LAPACK subroutines DSYTRF, and ZHETRF if A is symmetric.
The third and optional argument, TYPE allows the user to overide the symmetry check, and force the solve to use either the general or the symmetric solver.
TYPE = "g" or "G": The general solution is used.
TYPE = "s" or "S": The symmetric solution is used.
backsub, inv, factor, lu, rcond
Sort an object.
sort ( A )
If A is a vector (either row or column):
Then sort returns a list, containing the sorted values and indices. List element names are `val' and `ind'.
If A is a matrix (m > 2):
Then sort returns a list, containing a matrix with the sorted columns of A, and a matrix containing the sorted indices of A.
Numerical matrices are sorted in ascending numerical value. Complex matrices are sorted by absolute value. String matrices are sorted alphabetically (using strcmp()).
The sort function uses a simplistic version of qsort.
Convert full (dense) storage to sparse storage
sparse ( A )
sparse converts its argument from a dense storage format to the sparse storage format. If the argument is already sparse, then it is condensed (any non-zeros are removed). The sparse storage format is commonly referred to as sparse row-wise storage. Only the non-zero elements of the matrix are stored in a row-wise fashion. Row-wise storage is used for several reasons:
A*x
is a very common operation,
efficiently performed with row-wise storage.
Rlab does not attempt to out-smart the user by automatically converting sparse matrices to dense matrices, or vice-versa. Even if the user explicitly fills the a sparse matrix so that the number of non-zeros is equal to the full size of the matrix, the sparse storage format is retained.
Certain operations on sparse matrices will return dense matrices. For instance, the cosine operation on a sparse matrix will create a dense matrix with ones where there used to be zeros.
Sparse matrices are printed differently than full, or dense matrices. Only the non-zero elements are printed, along with their row and column values. For example:
> a = [0, 1, 0;
> 2, 0, 0;
> 0, 0, 3];
> s = sparse(a)
(1, 2) 1
(2, 1) 2
(3, 3) 3
Convert a full column matrix to sparse storage.
spconvert ( A )
spconvert converts its argument to, or from, the sparse storage format. If the argument is a 3 (or 4) column full matrix, the argument is converted to sparse storage format. The 1st two columns are taken as the row and column indices for the elements in the third column. The rows of the input matrix do not have to be in any particular order. If there are duplicate elements (same row and column number), then they are summed.
If the argument is a sparse matrix, then it is converted to a full matrix with 3 columns. The first two columns being the row and column indices of each non-zero element, and the third column in the element value (columns 3 and 4 if the matrix is complex).
Example:
Create a sparse matrix of zeros with 1000 rows, and 1000 columns
> s = spconvert ([ 1000, 1000, 0 ])
(1000, 1000) 0
> show(s);
nr : 1000
nc : 1000
n : 1e+06
nnz : 1
class : num
type : real
storage : sparse
Factor a sparse coefficient matrix.
spfactor ( A, DIAG_PIVOT, PERMV )
Factor a general (non-symmetric) sparse coefficient matrix into L and U factors.
specifies the diagonal-pivoting threshold.
is the permutation vector.
is the solution vector/matrix.
To be finished later...
solve, sparse, spsolve, backsub, factor
Formatted printing to a string.
sprintf ( stringvar, formatstr, VARi ... )
The RLaB sprintf is a limited feature version of the C-language sprintf. The features are limited because RLaB does not support all of the data types the C-language does.
The output of sprintf is written to this variable.
A valid sprintf format string.
Are any number of constants or variables that match the format string. sprintf cannot print out vector, matrix, or list objects as a whole. Valid print objects are strings, constants, and scalars.
printf, fprintf, write, read
Solve sparse linear equations.
spsolve ( A, B, DIAG_PIVOT, PERMV )
Solve solves a system of sparse linear equations:
A * X = B
is the coefficient matrix.
is the right hand side.
specifies the diagonal-pivoting threshold.
is the permutation vector.
is the solution vector/matrix.
To be finished later...
solve, backsub, factor
Write a sparse matrix to file.
spwrite ( FILENAME , SPM )
spwrite ( FILENAME , SPM , FORMAT )
The spwrite function takes at least two arguments. The 1st argument is the string that identifies the file to write to. The file is opened with write permission, destroying any pre-existing contents. The file closed after the matrix is written.
The default format for the sparse matrix is the internal storage format: compressed row-wise storage. See the Rlab Reference Manual for more explanation of this storage format.
A third, and optional argument, is a string specifying either
the default, or an optional output format. The value of the
string can be either "sparse"
(default) or
"graph"
. The graph output is a file suitable for use
with the Metis or Chaco graph partitioning/re-ordering
software.
write
Compute the square root.
sqrt ( A )
Sqrt returns the square-root of it's argument. If the argument is a matrix, then an element-by-element square-root operation is performed.
sqrt(-1)
will produce 1i
.
Seed the random number generator.
srand ( )
srand ( A )
srand ( SEED )
Srand sets the seed for the random number generator.
srand()
sets the seed to the original value (the last
value given to srand, or the default value, 1).
srand( "clock" )
' sets the seed based upon the machines
clock value. This provides users a way of picking a unique
seed each time.
Srand uses the RANLIB subroutine SETALL.
rand
Split a string.
strsplt ( STR )
strsplt ( STR, FW )
Strsplt returns a row matrix that contains a single character string as each element. The resulting matrix has as many columns as the input argument had characters.
Example:
> smat = strsplt( "string" )
smat =
s t r i n g
> show(smat)
name: smat
class: matrix
type: string
nr: 1
nc: 6
The second, and optional, argument to strsplt, FW forces strsplt to split STR into FW length strings.
FW can also be a string, or a string matrix, specifying the field separators that strsplt will use:
> str = "this;is;a;sem-colon;separated string;with numbers;1.234"
this;is;a;sem-colon;separated string;with numbers;1.234
> strsplt(str,";")
this is a sem-colon
separated string with numbers 1.234
getline
String to decimal conversion.
strtod ( STR )
The strtod functions converts its argument, STR, from string class to numeric class. Strtod stands for STRing TO Decimal.
Strtod will return a NaN (Not a Number) if it cannot recognize a string, or an element of a string matrix, as a number.
String to integer conversion.
strtol ( STR , BASE )
The strtol functions converts its argument, STR, from string class to numeric class. Strtol stands for STRing TO Long-int.
The second (optional) argument BASE, specifies the conversion base. Valid values for BASE are between 2 and 32. BASE defaults to 10 if not specified.
Strtol will return a NaN (Not a Number) if it cannot recognize a string, or an element of a string matrix, as a number.
Sum the elements of a matrix.
sum ( A )
Sum computes the sum of a matrix. The return object is a row matrix which contains the sum of each column of the input.
If the input is a vector (row-matrix) then the sum of the elements is returned.
Singular Value Decomposition
svd ( A )
svd ( A, TYPE )
Computes the singular values of the input matrix A, as well as the right and left singular vectors in various forms. Where:
A = U * diag (sigma) * Vt
The output is a list containing the three afore-mentioned objects (u, sigma, vt). Various forms of the right and left singular vectors can be computed, depending upon the value of the second, optional, string argument TYPE:
S
A minimal version of U
, and
Vt
are returned. This is the default.
A
The full U
, and Vt
are
returned.
N
U
and Vt
are not computed,
empty U
and Vt
are returned.
The LAPACK subroutine DGESVD, or ZGESVD is used to perform the computation.
Example:
> A = [0.96, 1.72; 2.28, 0.96];
> Asvd = svd(A)
sigma u vt
> Asvd.vt
matrix columns 1 thru 2
-0.8 -0.6
0.6 -0.8
> Asvd.u
matrix columns 1 thru 2
-0.6 -0.8
-0.8 0.6
> Asvd.sigma
vector elements 1 thru 2
3 1
> check = Asvd.u * diag(Asvd.sigma) * Asvd.vt
check =
matrix columns 1 thru 2
0.96 1.72
2.28 0.96
Solve the Sylvester matrix equation
sylv ( A , B , C )
sylv ( A , C )
Sylv solves the Sylvester matrix equation:
A*X + X*B = -C
or
A*X + X*A' = -C (Lyapunov equation)
A and B must both be upper quasi-triangular (if real), or triangular (if complex).
If A and or B are not upper quasi-triangular/triangular, then it is usually easier to use lyap. Lyap performs a Schur decomposition on A and B before using sylv.
Sylv uses the LAPACK functions DTRSYL, or ZTRSYL.
Execute operating system commands.
system ( COMMAND )
The system function behaves like the the UNIX system call. The string argument to system, COMMAND, is passed directly to the bourne-shell for execution. The program waits until the system call is finished.
Example:
> system( "vi test.r" )
will allow the user to edit (create) the file
test.r
. When the vi process is finished the user will
be back at the RLaB prompt.
> rfile test
will then load the result of the vi process.
Compute the tangent.
tan ( A )
RLaB trigonometric functions are designed to take scalars, and matrices as arguments. The return value is the input argument with the trigonometric operation performed element by element.
All the trigonometric functions use the C language math library functions, so details about the ranges and error conditions can be found by examining the appropriate man pages on your system.
Start the timer.
tic ( )
Tic internally marks the time at which it was invoked. To measure elapsed time, use tic in conjunction with toc.
Example:
tic();
a = rand(100,100);
eig(a);
toc()
The above would measure the time spent generating the 100x100 random matrix, and calculating the eigenvectors and values.
toc
Generate temporary file name.
tmpnam ( )
tmpnam returns a string that is not the name of an existing file. tmpnam generates a different name each time it is called. The string tmpnam returns can be used a a filename with RLaB's file I/O functions.
open, close, read, write, fprintf
Measure time elapsed since tic.
toc ( )
Toc reports the time (in seconds) elapsed since the last call to tic.
See also: tic
Return the type of an object.
type ( A )
Type returns a string that describes the type of element contained in object A. The valid types for an object vary according to the class of the object
If a list object has a string member with name type
,
then the type function will report the contents of that
member.
class, show
Compute the vector P norm.
vpnorm ( V , P )
vpnorm
computes the vector P-norm of V. The
second argument is required, and specifies the value of
P.
A small Rlab program demonstrating the P-norm computation is
provided below. However, vpnorm
is implemented as a
builtin function for maximum efficiency.
pnorm = function ( V , P ) { return (sum ( V.^P )).^(1/P); }
Write object(s) to file in ASCII format.
write_ascii ( FILENAME , A , b , ... )
The write_ascii function takes at least two arguments. The 1st argument is the string that identifies the file to write to. The file is opened with write permission, destroying any pre-existing contents. The file is left open so that subsequent writes will append to the file, and not destroy the contents.
The arguments after the file name are the objects that will be written. All objects are written in RLaB ASCII format.
Example:
write_ascii ( "filename", a , b , c );
Will open the file named filename
in write mode, and
write the contents of the variables a
, b
, and
c
.
close, read, read_ascii
Write a matrix in ASCII format.
writem ( "filename"
, A )
Writem is the counterpart to readm. Writem writes the matrix A to the file denoted by the 1st argument in a generic format.
The format used is:
line 1: value[1;1] ... value[1;ncol] \n
line nrow: value[nrow;1] ... value[nrow;ncol] \n
Writem will write real and complex numeric matrices, as well as string matrices even though readm can only read real numeric matrices. Complex matrices are written as a single 2*nrow by ncolumn real matrix. Sparse matrices are written as triplets (row column value) for each element of the matrix.
Writem does not close the file after writing A. The file is left open for further writes if necessary. Close can be called to explicitly close the file.
close, getline, open, readm, write
Create a matrix of zeros
zeros ( nrow, ncol )
zeros ( [ nrow, ncol ] )
Zeros returns a matrix with all zero elements. If the arguments are two scalars, then zeros returns a matrix with dimensions nrowxncol.
If the argument is a MATRIX, then zeros returns a matrix with dimensions m[1] by m[2].
Examples:
> Z = zeros( 3 , 3 );
> A = rand([10,4]);
> B = zeros( size(A) )
size