# HG changeset patch # User jwe # Date 940327722 0 # Node ID bfe1573bd2ae4f3bb5ca07a02a0c6046e290bd6c # Parent 58950f032a06f2c3cea095d255da3dddd7687db0 [project @ 1999-10-19 10:06:07 by jwe] diff --git a/doc/interpreter/Makefile.in b/doc/interpreter/Makefile.in --- a/doc/interpreter/Makefile.in +++ b/doc/interpreter/Makefile.in @@ -18,21 +18,22 @@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_DATA = @INSTALL_DATA@ -SOURCES = +SOURCES = arith.txi audio.txi basics.txi bugs.txi control.txi \ + cp-idx.txi data.txi diffeq.txi emacs.txi errors.txi \ + eval.txi expr.txi fn-idx.txi func.txi gpl.txi \ + grammar.txi image.txi install.txi intro.txi io.txi \ + linalg.txi matrix.txi nonlin.txi numbers.txi octave.txi \ + op-idx.txi optim.txi plot.txi poly.txi preface.txi \ + quad.txi set.txi signal.txi stats.txi stmt.txi \ + strings.txi struct.txi system.txi tips.txi var.txi \ + vr-idx.txi -TEXINFO = arith.texi audio.texi basics.texi bugs.texi control.texi \ - cp-idx.texi data.texi diffeq.texi emacs.texi errors.texi \ - eval.texi expr.texi fn-idx.texi func.texi gpl.texi \ - grammar.texi image.texi install.texi intro.texi io.texi \ - linalg.texi matrix.texi nonlin.texi numbers.texi octave.texi \ - op-idx.texi optim.texi plot.texi poly.texi preface.texi \ - quad.texi set.texi signal.texi stats.texi stmt.texi \ - strings.texi struct.texi system.texi tips.texi var.texi \ - vr-idx.texi + +TEXINFO = $(SOURCES:.txi=.texi) FORMATTED = octave.dvi octave.ps octave.info octave.info-[0-9]* octave_*.html -DISTFILES = Makefile.in dir octave.1 $(TEXINFO) $(FORMATTED) +DISTFILES = Makefile.in dir octave.1 $(SOURCES) $(TEXINFO) $(FORMATTED) ifeq ($(wildcard octave.info), ) BINDISTFILES = $(addprefix $(srcdir)/, octave.1 $(FORMATTED)) @@ -55,13 +56,21 @@ all: octave.info octave.dvi octave.ps octave_toc.html .PHONY: all +$(TEXINFO): munge-texi + +%.texi : %.txi + ./munge-texi \ + -d $(TOPDIR)/src/DOCSTRINGS \ + -d $(TOPDIR)/scripts/DOCSTRINGS < $< > $@.t + $(top_srcdir)/move-if-change $@.t $@ + octave.info: $(TEXINFO) ../conf.texi - -makeinfo -I$(srcdir) -I$(srcdir)/.. $(srcdir)/octave.texi + -makeinfo -I$(srcdir) -I$(srcdir)/.. octave.texi octave.dvi: $(TEXINFO) ../conf.texi -TEXINPUTS="$(srcdir):$(srcdir)/..:$(TEXINPUTS):"; \ export TEXINPUTS; \ - $(TEXI2DVI) $(srcdir)/octave.texi + $(TEXI2DVI) octave.texi octave.ps: octave.dvi -dvips -o octave.ps octave.dvi @@ -82,7 +91,7 @@ octave_toc.html: -texi2html -expandinfo -split_chapter -I$(srcdir)/.. \ - $(srcdir)/octave.texi + octave.texi check: all .PHONY: check diff --git a/doc/interpreter/arith.texi b/doc/interpreter/arith.texi deleted file mode 100644 --- a/doc/interpreter/arith.texi +++ /dev/null @@ -1,861 +0,0 @@ -@c Copyright (C) 1996, 1997 John W. Eaton -@c This is part of the Octave manual. -@c For copying conditions, see the file gpl.texi. - -@node Arithmetic, Linear Algebra, Matrix Manipulation, Top -@chapter Arithmetic - -Unless otherwise noted, all of the functions described in this chapter -will work for real and complex scalar or matrix arguments. - -@menu -* Utility Functions:: -* Complex Arithmetic:: -* Trigonometry:: -* Sums and Products:: -* Special Functions:: -* Mathematical Constants:: -@end menu - -@node Utility Functions, Complex Arithmetic, Arithmetic, Arithmetic -@section Utility Functions - -The following functions are available for working with complex numbers. -Each expects a single argument. They are called @dfn{mapping functions} -because when given a matrix argument, they apply the given function to -each element of the matrix. - -@deftypefn {Mapping Function} {} ceil (@var{x}) -Return the smallest integer not less than @var{x}. If @var{x} is -complex, return @code{ceil (real (@var{x})) + ceil (imag (@var{x})) * I}. -@end deftypefn - -@deftypefn {Mapping Function} {} exp (@var{x}) -Compute the exponential of @var{x}. To compute the matrix exponential, -see @ref{Linear Algebra}. -@end deftypefn - -@deftypefn {Mapping Function} {} fix (@var{x}) -Truncate @var{x} toward zero. If @var{x} is complex, return -@code{fix (real (@var{x})) + fix (imag (@var{x})) * I}. -@end deftypefn - -@deftypefn {Mapping Function} {} floor (@var{x}) -Return the largest integer not greater than @var{x}. If @var{x} is -complex, return @code{floor (real (@var{x})) + floor (imag (@var{x})) * I}. -@end deftypefn - -@deftypefn {Mapping Function} {} gcd (@var{x}, @code{...}) -Compute the greatest common divisor of the elements of @var{x}, or the -list of all the arguments. For example, - -@example -gcd (a1, ..., ak) -@end example - -@noindent -is the same as - -@example -gcd ([a1, ..., ak]) -@end example - -An optional second return value, @var{v} -contains an integer vector such that - -@example -g = v(1) * a(k) + ... + v(k) * a(k) -@end example -@end deftypefn - -@deftypefn {Mapping Function} {} lcm (@var{x}, @code{...}) -Compute the least common multiple of the elements elements of @var{x}, or -the list of all the arguments. For example, - -@example -lcm (a1, ..., ak) -@end example - -@noindent -is the same as - -@example -lcm ([a1, ..., ak]). -@end example -@end deftypefn - -@deftypefn {Mapping Function} {} log (@var{x}) -Compute the natural logarithm of @var{x}. To compute the matrix logarithm, -see @ref{Linear Algebra}. -@end deftypefn - -@deftypefn {Mapping Function} {} log10 (@var{x}) -Compute the base-10 logarithm of @var{x}. -@end deftypefn - -@deftypefn {Mapping Function} {@var{y} =} log2 (@var{x}) -@deftypefnx {Mapping Function} {[@var{f}, @var{e}]} log2 (@var{x}) -Compute the base-2 logarithm of @var{x}. With two outputs, returns -@var{f} and @var{e} such that -@iftex -@tex - $1/2 <= |f| < 1$ and $x = f \cdot 2^e$. -@end tex -@end iftex -@ifinfo - 1/2 <= abs(f) < 1 and x = f * 2^e. -@end ifinfo -@end deftypefn - -@deftypefn {Loadable Function} {} max (@var{x}) -For a vector argument, return the maximum value. For a matrix argument, -return the maximum value from each column, as a row vector. Thus, - -@example -max (max (@var{x})) -@end example - -@noindent -returns the largest element of @var{x}. - -For complex arguments, the magnitude of the elements are used for -comparison. -@end deftypefn - -@deftypefn {Loadable Function} {} min (@var{x}) -Like @code{max}, but return the minimum value. -@end deftypefn - -@deftypefn {Function File} {} nextpow2 (@var{x}) -If @var{x} is a scalar, returns the first integer @var{n} such that -@iftex -@tex - $2^n \ge |x|$. -@end tex -@end iftex -@ifinfo - 2^n >= abs (x). -@end ifinfo - -If @var{x} is a vector, return @code{nextpow2 (length (@var{x}))}. -@end deftypefn - -@deftypefn {Mapping Function} {} pow2 (@var{x}) -@deftypefnx {Mapping Function} {} pow2 (@var{f}, @var{e}) -With one argument, computes -@iftex -@tex - $2^x$ -@end tex -@end iftex -@ifinfo - 2 .^ x -@end ifinfo -for each element of @var{x}. With two arguments, returns -@iftex -@tex - $f \cdot 2^e$. -@end tex -@end iftex -@ifinfo - f .* (2 .^ e). -@end ifinfo -@end deftypefn - -@deftypefn {Mapping Function} {} rem (@var{x}, @var{y}) -Return the remainder of @code{@var{x} / @var{y}}, computed using the -expression - -@example -x - y .* fix (x ./ y) -@end example - -An error message is printed if the dimensions of the arguments do not -agree, or if either of the arguments is complex. -@end deftypefn - -@deftypefn {Mapping Function} {} round (@var{x}) -Return the integer nearest to @var{x}. If @var{x} is complex, return -@code{round (real (@var{x})) + round (imag (@var{x})) * I}. -@end deftypefn - -@deftypefn {Mapping Function} {} sign (@var{x}) -Compute the @dfn{signum} function, which is defined as -@iftex -@tex -$$ -{\rm sign} (@var{x}) = \cases{1,&$x>0$;\cr 0,&$x=0$;\cr -1,&$x<0$.\cr} -$$ -@end tex -@end iftex -@ifinfo - -@example - -1, x < 0; -sign (x) = 0, x = 0; - 1, x > 0. -@end example -@end ifinfo - -For complex arguments, @code{sign} returns @code{x ./ abs (@var{x})}. -@end deftypefn - -@deftypefn {Mapping Function} {} sqrt (@var{x}) -Compute the square root of @var{x}. If @var{x} is negative, a complex -result is returned. To compute the matrix square root, see -@ref{Linear Algebra}. -@end deftypefn - -@deftypefn {Mapping Function} {} xor (@var{x}, @var{y}) -Return the `exclusive or' of the entries of @var{x} and @var{y}. -For boolean expressions @var{x} and @var{y}, -@code{xor (@var{x}, @var{y})} is true if and only if @var{x} or @var{y} -is true, but not if both @var{x} and @var{y} are true. -@end deftypefn - -@node Complex Arithmetic, Trigonometry, Utility Functions, Arithmetic -@section Complex Arithmetic - -The following functions are available for working with complex -numbers. Each expects a single argument. Given a matrix they work on -an element by element basis. In the descriptions of the following -functions, -@iftex -@tex -$z$ is the complex number $x + iy$, where $i$ is defined as -$\sqrt{-1}$. -@end tex -@end iftex -@ifinfo -@var{z} is the complex number @var{x} + @var{i}@var{y}, where @var{i} is -defined as @code{sqrt (-1)}. -@end ifinfo - -@deftypefn {Mapping Function} {} abs (@var{z}) -Compute the magnitude of @var{z}, defined as -@iftex -@tex -$|z| = \sqrt{x^2 + y^2}$. -@end tex -@end iftex -@ifinfo -|@var{z}| = @code{sqrt (x^2 + y^2)}. -@end ifinfo - -For example, - -@example -@group -abs (3 + 4i) - @result{} 5 -@end group -@end example -@end deftypefn - -@deftypefn {Mapping Function} {} arg (@var{z}) -@deftypefnx {Mapping Function} {} angle (@var{z}) -Compute the argument of @var{z}, defined as -@iftex -@tex -$\theta = \tan^{-1}(y/x)$. -@end tex -@end iftex -@ifinfo -@var{theta} = @code{atan (@var{y}/@var{x})}. -@end ifinfo - -@noindent -in radians. - -For example, - -@example -@group -arg (3 + 4i) - @result{} 0.92730 -@end group -@end example -@end deftypefn - -@deftypefn {Mapping Function} {} conj (@var{z}) -Return the complex conjugate of @var{z}, defined as -@iftex -@tex -$\bar{z} = x - iy$. -@end tex -@end iftex -@ifinfo -@code{conj (@var{z})} = @var{x} - @var{i}@var{y}. -@end ifinfo -@end deftypefn - -@deftypefn {Mapping Function} {} imag (@var{z}) -Return the imaginary part of @var{z} as a real number. -@end deftypefn - -@deftypefn {Mapping Function} {} real (@var{z}) -Return the real part of @var{z}. -@end deftypefn - -@node Trigonometry, Sums and Products, Complex Arithmetic, Arithmetic -@section Trigonometry - -Octave provides the following trigonometric functions. Angles are -specified in radians. To convert from degrees to radians multipy by -@iftex -@tex -$\pi/180$ -@end tex -@end iftex -@ifinfo -@code{pi/180} -@end ifinfo - (e.g. @code{sin (30 * pi/180)} returns the sine of 30 degrees). - -@deftypefn {Mapping Function} {} sin (@var{z}) -@deftypefnx {Mapping Function} {} cos (@var{z}) -@deftypefnx {Mapping Function} {} tan (@var{z}) -@deftypefnx {Mapping Function} {} sec (@var{z}) -@deftypefnx {Mapping Function} {} csc (@var{z}) -@deftypefnx {Mapping Function} {} cot (@var{z}) -The ordinary trigonometric functions. -@end deftypefn - -@deftypefn {Mapping Function} {} asin (@var{z}) -@deftypefnx {Mapping Function} {} acos (@var{z}) -@deftypefnx {Mapping Function} {} atan (@var{z}) -@deftypefnx {Mapping Function} {} asec (@var{z}) -@deftypefnx {Mapping Function} {} acsc (@var{z}) -@deftypefnx {Mapping Function} {} acot (@var{z}) -The ordinary inverse trigonometric functions. -@end deftypefn - -@deftypefn {Mapping Function} {} sinh (@var{z}) -@deftypefnx {Mapping Function} {} cosh (@var{z}) -@deftypefnx {Mapping Function} {} tanh (@var{z}) -@deftypefnx {Mapping Function} {} sech (@var{z}) -@deftypefnx {Mapping Function} {} csch (@var{z}) -@deftypefnx {Mapping Function} {} coth (@var{z}) -Hyperbolic trigonometric functions. -@end deftypefn - -@deftypefn {Mapping Function} {} asinh (@var{z}) -@deftypefnx {Mapping Function} {} acosh (@var{z}) -@deftypefnx {Mapping Function} {} atanh (@var{z}) -@deftypefnx {Mapping Function} {} asech (@var{z}) -@deftypefnx {Mapping Function} {} acsch (@var{z}) -@deftypefnx {Mapping Function} {} acoth (@var{z}) -Inverse hyperbolic trigonometric functions. -@end deftypefn - -Each of these functions expect a single argument. For matrix arguments, -they work on an element by element basis. For example, - -@example -@group -sin ([1, 2; 3, 4]) - @result{} 0.84147 0.90930 - 0.14112 -0.75680 -@end group -@end example - -@deftypefn {Mapping Function} {} atan2 (@var{y}, @var{x}) -Return the arctangent of @var{y}/@var{x}. The signs of the arguments -are used to determine the quadrant of the result, which is in the range -@iftex -@tex -$\pi$ to $-\pi$. -@end tex -@end iftex -@ifinfo -@code{pi} to -@code{pi}. -@end ifinfo -@end deftypefn - -@node Sums and Products, Special Functions, Trigonometry, Arithmetic -@section Sums and Products - -@deftypefn {Built-in Function} {} sum (@var{x}) -For a vector argument, return the sum of all the elements. For a matrix -argument, return the sum of the elements in each column, as a row -vector. The sum of an empty matrix is 0 if it has no columns, or a -vector of zeros if it has no rows (@pxref{Empty Matrices}). -@end deftypefn - -@deftypefn {Built-in Function} {} prod (@var{x}) -For a vector argument, return the product of all the elements. For a -matrix argument, return the product of the elements in each column, as a -row vector. The product of an empty matrix is 1 if it has no columns, -or a vector of ones if it has no rows (@pxref{Empty Matrices}). -@end deftypefn - -@deftypefn {Built-in Function} {} cumsum (@var{x}) -Return the cumulative sum of each column of @var{x}. For example, - -@example -@group -cumsum ([1, 2; 3, 4]) - @result{} 1 2 - 4 6 -@end group -@end example -@end deftypefn - -@deftypefn {Built-in Function} {} cumprod (@var{x}) -Return the cumulative product of each column of @var{x}. For example, - -@example -@group -cumprod ([1, 2; 3, 4]) - @result{} 1 2 - 3 8 -@end group -@end example -@end deftypefn - -@deftypefn {Built-in Function} {} sumsq (@var{x}) -For a vector argument, return the sum of the squares of all the -elements. For a matrix argument, return the sum of the squares of the -elements in each column, as a row vector. -@end deftypefn - -@node Special Functions, Mathematical Constants, Sums and Products, Arithmetic -@section Special Functions - -@deftypefn {Mapping Function} {} besseli (@var{alpha}, @var{x}) -@deftypefnx {Mapping Function} {} besselj (@var{alpha}, @var{x}) -@deftypefnx {Mapping Function} {} besselk (@var{alpha}, @var{x}) -@deftypefnx {Mapping Function} {} bessely (@var{alpha}, @var{x}) -Compute Bessel functions of the following types: - -@table @code -@item besselj -Bessel functions of the first kind. - -@item bessely -Bessel functions of the second kind. - -@item besseli -Modified Bessel functions of the first kind. - -@item besselk -Modified Bessel functions of the second kind. -@end table - -The second argument, @var{x}, must be a real matrix, vector, or scalar. - -The first argument, @var{alpha}, must be greater than or equal to zero. -If @var{alpha} is a range, it must have an increment equal to one. - -If @var{alpha} is a scalar, the result is the same size as @var{x}. - -If @var{alpha} is a range, @var{x} must be a vector or scalar, and the -result is a matrix with @code{length(@var{x})} rows and -@code{length(@var{alpha})} columns. -@end deftypefn - -@deftypefn {Mapping Function} {} beta (@var{a}, @var{b}) -Return the Beta function, -@iftex -@tex -$$ - B (a, b) = {\Gamma (a) \Gamma (b) \over \Gamma (a + b)}. -$$ -@end tex -@end iftex -@ifinfo - -@example -beta (a, b) = gamma (a) * gamma (b) / gamma (a + b). -@end example -@end ifinfo -@end deftypefn - -@deftypefn {Mapping Function} {} betai (@var{a}, @var{b}, @var{x}) -Return the incomplete Beta function, -@iftex -@tex -$$ - \beta (a, b, x) = B (a, b)^{-1} \int_0^x t^{(a-z)} (1-t)^{(b-1)} dt. -$$ -@end tex -@end iftex -@ifinfo - -@smallexample - x - / -betai (a, b, x) = beta (a, b)^(-1) | t^(a-1) (1-t)^(b-1) dt. - / - t=0 -@end smallexample -@end ifinfo - -If x has more than one component, both @var{a} and @var{b} must be -scalars. If @var{x} is a scalar, @var{a} and @var{b} must be of -compatible dimensions. -@end deftypefn - -@deftypefn {Mapping Function} {} bincoeff (@var{n}, @var{k}) -Return the binomial coefficient of @var{n} and @var{k}, defined as -@iftex -@tex -$$ - {n \choose k} = {n (n-1) (n-2) \cdots (n-k+1) \over k!} -$$ -@end tex -@end iftex -@ifinfo - -@example -@group - / \ - | n | n (n-1) (n-2) ... (n-k+1) - | | = ------------------------- - | k | k! - \ / -@end group -@end example -@end ifinfo - -For example, - -@example -@group -bincoeff (5, 2) - @result{} 10 -@end group -@end example -@end deftypefn - -@deftypefn {Mapping Function} {} erf (@var{z}) -Computes the error function, -@iftex -@tex -$$ - {\rm erf} (z) = {2 \over \sqrt{\pi}}\int_0^z e^{-t^2} dt -$$ -@end tex -@end iftex -@ifinfo - -@smallexample - z - / -erf (z) = (2/sqrt (pi)) | e^(-t^2) dt - / - t=0 -@end smallexample -@end ifinfo -@end deftypefn - -@deftypefn {Mapping Function} {} erfc (@var{z}) -Computes the complementary error function, -@iftex -@tex -$1 - {\rm erf} (z)$. -@end tex -@end iftex -@ifinfo -@code{1 - erf (@var{z})}. -@end ifinfo -@end deftypefn - -@deftypefn {Mapping Function} {} erfinv (@var{z}) -Computes the inverse of the error function, -@end deftypefn - -@deftypefn {Mapping Function} {} gamma (@var{z}) -Computes the Gamma function, -@iftex -@tex -$$ - \Gamma (z) = \int_0^\infty t^{z-1} e^{-t} dt. -$$ -@end tex -@end iftex -@ifinfo - -@example - infinity - / -gamma (z) = | t^(z-1) exp (-t) dt. - / - t=0 -@end example -@end ifinfo -@end deftypefn - -@deftypefn {Mapping Function} {} gammai (@var{a}, @var{x}) -Computes the incomplete gamma function, -@iftex -@tex -$$ - \gamma (a, x) = {\displaystyle\int_0^x e^{-t} t^{a-1} dt \over \Gamma (a)} -$$ -@end tex -@end iftex -@ifinfo - -@smallexample - x - 1 / -gammai (a, x) = --------- | exp (-t) t^(a-1) dt - gamma (a) / - t=0 -@end smallexample -@end ifinfo - -If @var{a} is scalar, then @code{gammai (@var{a}, @var{x})} is returned -for each element of @var{x} and vice versa. - -If neither @var{a} nor @var{x} is scalar, the sizes of @var{a} and -@var{x} must agree, and @var{gammai} is applied element-by-element. -@end deftypefn - -@deftypefn {Mapping Function} {} lgamma (@var{a}, @var{x}) -@deftypefnx {Mapping Function} {} gammaln (@var{a}, @var{x}) -Return the natural logarithm of the gamma function. -@end deftypefn - -@deftypefn {Function File} {} cross (@var{x}, @var{y}) -Computes the vector cross product of the two 3-dimensional vectors -@var{x} and @var{y}. For example, - -@example -@group -cross ([1,1,0], [0,1,1]) - @result{} [ 1; -1; 1 ] -@end group -@end example -@end deftypefn - -@deftypefn {Function File} {} commutation_matrix (@var{m}, @var{n}) -Return the commutation matrix -@iftex -@tex - $K_{m,n}$ -@end tex -@end iftex -@ifinfo - K(m,n) -@end ifinfo - which is the unique -@iftex -@tex - $m n \times m n$ -@end tex -@end iftex -@ifinfo - @var{m}*@var{n} by @var{m}*@var{n} -@end ifinfo - matrix such that -@iftex -@tex - $K_{m,n} \cdot {\rm vec} (A) = {\rm vec} (A^T)$ -@end tex -@end iftex -@ifinfo - @var{K}(@var{m},@var{n}) * vec (@var{A}) = vec (@var{A}') -@end ifinfo - for all -@iftex -@tex - $m\times n$ -@end tex -@end iftex -@ifinfo - @var{m} by @var{n} -@end ifinfo - matrices -@iftex -@tex - $A$. -@end tex -@end iftex -@ifinfo - @var{A}. -@end ifinfo - -If only one argument @var{m} is given, -@iftex -@tex - $K_{m,m}$ -@end tex -@end iftex -@ifinfo - K(m,m) -@end ifinfo - is returned. - -See Magnus and Neudecker (1988), Matrix differential calculus with -applications in statistics and econometrics. -@end deftypefn - -@deftypefn {Function File} {} duplication_matrix (@var{n}) -Return the duplication matrix -@iftex -@tex - $D_n$ -@end tex -@end iftex -@ifinfo - @var{D}_@var{n} -@end ifinfo - which is the unique -@iftex -@tex - $n^2 \times n(n+1)/2$ -@end tex -@end iftex -@ifinfo - @var{n}^2 by @var{n}*(@var{n}+1)/2 -@end ifinfo - matrix such that -@iftex -@tex - $D_n * {\rm vech} (A) = {\rm vec} (A)$ -@end tex -@end iftex -@ifinfo - @var{D}_@var{n} \cdot vech (@var{A}) = vec (@var{A}) -@end ifinfo - for all symmetric -@iftex -@tex - $n \times n$ -@end tex -@end iftex -@ifinfo - @var{n} by @var{n} -@end ifinfo - matrices -@iftex -@tex - $A$. -@end tex -@end iftex -@ifinfo - @var{A}. -@end ifinfo - -See Magnus and Neudecker (1988), Matrix differential calculus with -applications in statistics and econometrics. -@end deftypefn - -@node Mathematical Constants, , Special Functions, Arithmetic -@section Mathematical Constants - -@defvr {Built-in Variable} I -@defvrx {Built-in Variable} J -@defvrx {Built-in Variable} i -@defvrx {Built-in Variable} j -A pure imaginary number, defined as -@iftex -@tex - $\sqrt{-1}$. -@end tex -@end iftex -@ifinfo - @code{sqrt (-1)}. -@end ifinfo -The @code{I} and @code{J} forms are true constants, and cannot be -modified. The @code{i} and @code{j} forms are like ordinary variables, -and may be used for other purposes. However, unlike other variables, -they once again assume their special predefined values if they are -cleared @xref{Status of Variables}. -@end defvr - -@defvr {Built-in Variable} Inf -@defvrx {Built-in Variable} inf -Infinity. This is the result of an operation like 1/0, or an operation -that results in a floating point overflow. -@end defvr - -@defvr {Built-in Variable} NaN -@defvrx {Built-in Variable} nan -Not a number. This is the result of an operation like -@iftex -@tex -$0/0$, or $\infty - \infty$, -@end tex -@end iftex -@ifinfo -0/0, or @samp{Inf - Inf}, -@end ifinfo -or any operation with a NaN. - -Note that NaN always compares not equal to NaN. This behavior is -specified by the IEEE standard for floating point arithmetic. To -find NaN values, you must use the @code{isnan} function. -@end defvr - -@defvr {Built-in Variable} pi -The ratio of the circumference of a circle to its diameter. -Internally, @code{pi} is computed as @samp{4.0 * atan (1.0)}. -@end defvr - -@defvr {Built-in Variable} e -The base of natural logarithms. The constant -@iftex -@tex - $e$ -@end tex -@end iftex -@ifinfo - @var{e} -@end ifinfo - satisfies the equation -@iftex -@tex - $\log (e) = 1$. -@end tex -@end iftex -@ifinfo - @code{log} (@var{e}) = 1. -@end ifinfo -@end defvr - -@defvr {Built-in Variable} eps -The machine precision. More precisely, @code{eps} is the largest -relative spacing between any two adjacent numbers in the machine's -floating point system. This number is obviously system-dependent. On -machines that support 64 bit IEEE floating point arithmetic, @code{eps} -is approximately -@ifinfo - 2.2204e-16. -@end ifinfo -@iftex -@tex - $2.2204\times10^{-16}$. -@end tex -@end iftex -@end defvr - -@defvr {Built-in Variable} realmax -The largest floating point number that is representable. The actual -value is system-dependent. On machines that support 64 bit IEEE -floating point arithmetic, @code{realmax} is approximately -@ifinfo - 1.7977e+308 -@end ifinfo -@iftex -@tex - $1.7977\times10^{308}$. -@end tex -@end iftex -@end defvr - -@defvr {Built-in Variable} realmin -The smallest floating point number that is representable. The actual -value is system-dependent. On machines that support 64 bit IEEE -floating point arithmetic, @code{realmin} is approximately -@ifinfo - 2.2251e-308 -@end ifinfo -@iftex -@tex - $2.2251\times10^{-308}$. -@end tex -@end iftex -@end defvr diff --git a/doc/interpreter/arith.txi b/doc/interpreter/arith.txi new file mode 100644 --- /dev/null +++ b/doc/interpreter/arith.txi @@ -0,0 +1,861 @@ +@c Copyright (C) 1996, 1997 John W. Eaton +@c This is part of the Octave manual. +@c For copying conditions, see the file gpl.texi. + +@node Arithmetic, Linear Algebra, Matrix Manipulation, Top +@chapter Arithmetic + +Unless otherwise noted, all of the functions described in this chapter +will work for real and complex scalar or matrix arguments. + +@menu +* Utility Functions:: +* Complex Arithmetic:: +* Trigonometry:: +* Sums and Products:: +* Special Functions:: +* Mathematical Constants:: +@end menu + +@node Utility Functions, Complex Arithmetic, Arithmetic, Arithmetic +@section Utility Functions + +The following functions are available for working with complex numbers. +Each expects a single argument. They are called @dfn{mapping functions} +because when given a matrix argument, they apply the given function to +each element of the matrix. + +@deftypefn {Mapping Function} {} ceil (@var{x}) +Return the smallest integer not less than @var{x}. If @var{x} is +complex, return @code{ceil (real (@var{x})) + ceil (imag (@var{x})) * I}. +@end deftypefn + +@deftypefn {Mapping Function} {} exp (@var{x}) +Compute the exponential of @var{x}. To compute the matrix exponential, +see @ref{Linear Algebra}. +@end deftypefn + +@deftypefn {Mapping Function} {} fix (@var{x}) +Truncate @var{x} toward zero. If @var{x} is complex, return +@code{fix (real (@var{x})) + fix (imag (@var{x})) * I}. +@end deftypefn + +@deftypefn {Mapping Function} {} floor (@var{x}) +Return the largest integer not greater than @var{x}. If @var{x} is +complex, return @code{floor (real (@var{x})) + floor (imag (@var{x})) * I}. +@end deftypefn + +@deftypefn {Mapping Function} {} gcd (@var{x}, @code{...}) +Compute the greatest common divisor of the elements of @var{x}, or the +list of all the arguments. For example, + +@example +gcd (a1, ..., ak) +@end example + +@noindent +is the same as + +@example +gcd ([a1, ..., ak]) +@end example + +An optional second return value, @var{v} +contains an integer vector such that + +@example +g = v(1) * a(k) + ... + v(k) * a(k) +@end example +@end deftypefn + +@deftypefn {Mapping Function} {} lcm (@var{x}, @code{...}) +Compute the least common multiple of the elements elements of @var{x}, or +the list of all the arguments. For example, + +@example +lcm (a1, ..., ak) +@end example + +@noindent +is the same as + +@example +lcm ([a1, ..., ak]). +@end example +@end deftypefn + +@deftypefn {Mapping Function} {} log (@var{x}) +Compute the natural logarithm of @var{x}. To compute the matrix logarithm, +see @ref{Linear Algebra}. +@end deftypefn + +@deftypefn {Mapping Function} {} log10 (@var{x}) +Compute the base-10 logarithm of @var{x}. +@end deftypefn + +@deftypefn {Mapping Function} {@var{y} =} log2 (@var{x}) +@deftypefnx {Mapping Function} {[@var{f}, @var{e}]} log2 (@var{x}) +Compute the base-2 logarithm of @var{x}. With two outputs, returns +@var{f} and @var{e} such that +@iftex +@tex + $1/2 <= |f| < 1$ and $x = f \cdot 2^e$. +@end tex +@end iftex +@ifinfo + 1/2 <= abs(f) < 1 and x = f * 2^e. +@end ifinfo +@end deftypefn + +@deftypefn {Loadable Function} {} max (@var{x}) +For a vector argument, return the maximum value. For a matrix argument, +return the maximum value from each column, as a row vector. Thus, + +@example +max (max (@var{x})) +@end example + +@noindent +returns the largest element of @var{x}. + +For complex arguments, the magnitude of the elements are used for +comparison. +@end deftypefn + +@deftypefn {Loadable Function} {} min (@var{x}) +Like @code{max}, but return the minimum value. +@end deftypefn + +@deftypefn {Function File} {} nextpow2 (@var{x}) +If @var{x} is a scalar, returns the first integer @var{n} such that +@iftex +@tex + $2^n \ge |x|$. +@end tex +@end iftex +@ifinfo + 2^n >= abs (x). +@end ifinfo + +If @var{x} is a vector, return @code{nextpow2 (length (@var{x}))}. +@end deftypefn + +@deftypefn {Mapping Function} {} pow2 (@var{x}) +@deftypefnx {Mapping Function} {} pow2 (@var{f}, @var{e}) +With one argument, computes +@iftex +@tex + $2^x$ +@end tex +@end iftex +@ifinfo + 2 .^ x +@end ifinfo +for each element of @var{x}. With two arguments, returns +@iftex +@tex + $f \cdot 2^e$. +@end tex +@end iftex +@ifinfo + f .* (2 .^ e). +@end ifinfo +@end deftypefn + +@deftypefn {Mapping Function} {} rem (@var{x}, @var{y}) +Return the remainder of @code{@var{x} / @var{y}}, computed using the +expression + +@example +x - y .* fix (x ./ y) +@end example + +An error message is printed if the dimensions of the arguments do not +agree, or if either of the arguments is complex. +@end deftypefn + +@deftypefn {Mapping Function} {} round (@var{x}) +Return the integer nearest to @var{x}. If @var{x} is complex, return +@code{round (real (@var{x})) + round (imag (@var{x})) * I}. +@end deftypefn + +@deftypefn {Mapping Function} {} sign (@var{x}) +Compute the @dfn{signum} function, which is defined as +@iftex +@tex +$$ +{\rm sign} (@var{x}) = \cases{1,&$x>0$;\cr 0,&$x=0$;\cr -1,&$x<0$.\cr} +$$ +@end tex +@end iftex +@ifinfo + +@example + -1, x < 0; +sign (x) = 0, x = 0; + 1, x > 0. +@end example +@end ifinfo + +For complex arguments, @code{sign} returns @code{x ./ abs (@var{x})}. +@end deftypefn + +@deftypefn {Mapping Function} {} sqrt (@var{x}) +Compute the square root of @var{x}. If @var{x} is negative, a complex +result is returned. To compute the matrix square root, see +@ref{Linear Algebra}. +@end deftypefn + +@deftypefn {Mapping Function} {} xor (@var{x}, @var{y}) +Return the `exclusive or' of the entries of @var{x} and @var{y}. +For boolean expressions @var{x} and @var{y}, +@code{xor (@var{x}, @var{y})} is true if and only if @var{x} or @var{y} +is true, but not if both @var{x} and @var{y} are true. +@end deftypefn + +@node Complex Arithmetic, Trigonometry, Utility Functions, Arithmetic +@section Complex Arithmetic + +The following functions are available for working with complex +numbers. Each expects a single argument. Given a matrix they work on +an element by element basis. In the descriptions of the following +functions, +@iftex +@tex +$z$ is the complex number $x + iy$, where $i$ is defined as +$\sqrt{-1}$. +@end tex +@end iftex +@ifinfo +@var{z} is the complex number @var{x} + @var{i}@var{y}, where @var{i} is +defined as @code{sqrt (-1)}. +@end ifinfo + +@deftypefn {Mapping Function} {} abs (@var{z}) +Compute the magnitude of @var{z}, defined as +@iftex +@tex +$|z| = \sqrt{x^2 + y^2}$. +@end tex +@end iftex +@ifinfo +|@var{z}| = @code{sqrt (x^2 + y^2)}. +@end ifinfo + +For example, + +@example +@group +abs (3 + 4i) + @result{} 5 +@end group +@end example +@end deftypefn + +@deftypefn {Mapping Function} {} arg (@var{z}) +@deftypefnx {Mapping Function} {} angle (@var{z}) +Compute the argument of @var{z}, defined as +@iftex +@tex +$\theta = \tan^{-1}(y/x)$. +@end tex +@end iftex +@ifinfo +@var{theta} = @code{atan (@var{y}/@var{x})}. +@end ifinfo + +@noindent +in radians. + +For example, + +@example +@group +arg (3 + 4i) + @result{} 0.92730 +@end group +@end example +@end deftypefn + +@deftypefn {Mapping Function} {} conj (@var{z}) +Return the complex conjugate of @var{z}, defined as +@iftex +@tex +$\bar{z} = x - iy$. +@end tex +@end iftex +@ifinfo +@code{conj (@var{z})} = @var{x} - @var{i}@var{y}. +@end ifinfo +@end deftypefn + +@deftypefn {Mapping Function} {} imag (@var{z}) +Return the imaginary part of @var{z} as a real number. +@end deftypefn + +@deftypefn {Mapping Function} {} real (@var{z}) +Return the real part of @var{z}. +@end deftypefn + +@node Trigonometry, Sums and Products, Complex Arithmetic, Arithmetic +@section Trigonometry + +Octave provides the following trigonometric functions. Angles are +specified in radians. To convert from degrees to radians multipy by +@iftex +@tex +$\pi/180$ +@end tex +@end iftex +@ifinfo +@code{pi/180} +@end ifinfo + (e.g. @code{sin (30 * pi/180)} returns the sine of 30 degrees). + +@deftypefn {Mapping Function} {} sin (@var{z}) +@deftypefnx {Mapping Function} {} cos (@var{z}) +@deftypefnx {Mapping Function} {} tan (@var{z}) +@deftypefnx {Mapping Function} {} sec (@var{z}) +@deftypefnx {Mapping Function} {} csc (@var{z}) +@deftypefnx {Mapping Function} {} cot (@var{z}) +The ordinary trigonometric functions. +@end deftypefn + +@deftypefn {Mapping Function} {} asin (@var{z}) +@deftypefnx {Mapping Function} {} acos (@var{z}) +@deftypefnx {Mapping Function} {} atan (@var{z}) +@deftypefnx {Mapping Function} {} asec (@var{z}) +@deftypefnx {Mapping Function} {} acsc (@var{z}) +@deftypefnx {Mapping Function} {} acot (@var{z}) +The ordinary inverse trigonometric functions. +@end deftypefn + +@deftypefn {Mapping Function} {} sinh (@var{z}) +@deftypefnx {Mapping Function} {} cosh (@var{z}) +@deftypefnx {Mapping Function} {} tanh (@var{z}) +@deftypefnx {Mapping Function} {} sech (@var{z}) +@deftypefnx {Mapping Function} {} csch (@var{z}) +@deftypefnx {Mapping Function} {} coth (@var{z}) +Hyperbolic trigonometric functions. +@end deftypefn + +@deftypefn {Mapping Function} {} asinh (@var{z}) +@deftypefnx {Mapping Function} {} acosh (@var{z}) +@deftypefnx {Mapping Function} {} atanh (@var{z}) +@deftypefnx {Mapping Function} {} asech (@var{z}) +@deftypefnx {Mapping Function} {} acsch (@var{z}) +@deftypefnx {Mapping Function} {} acoth (@var{z}) +Inverse hyperbolic trigonometric functions. +@end deftypefn + +Each of these functions expect a single argument. For matrix arguments, +they work on an element by element basis. For example, + +@example +@group +sin ([1, 2; 3, 4]) + @result{} 0.84147 0.90930 + 0.14112 -0.75680 +@end group +@end example + +@deftypefn {Mapping Function} {} atan2 (@var{y}, @var{x}) +Return the arctangent of @var{y}/@var{x}. The signs of the arguments +are used to determine the quadrant of the result, which is in the range +@iftex +@tex +$\pi$ to $-\pi$. +@end tex +@end iftex +@ifinfo +@code{pi} to -@code{pi}. +@end ifinfo +@end deftypefn + +@node Sums and Products, Special Functions, Trigonometry, Arithmetic +@section Sums and Products + +@deftypefn {Built-in Function} {} sum (@var{x}) +For a vector argument, return the sum of all the elements. For a matrix +argument, return the sum of the elements in each column, as a row +vector. The sum of an empty matrix is 0 if it has no columns, or a +vector of zeros if it has no rows (@pxref{Empty Matrices}). +@end deftypefn + +@deftypefn {Built-in Function} {} prod (@var{x}) +For a vector argument, return the product of all the elements. For a +matrix argument, return the product of the elements in each column, as a +row vector. The product of an empty matrix is 1 if it has no columns, +or a vector of ones if it has no rows (@pxref{Empty Matrices}). +@end deftypefn + +@deftypefn {Built-in Function} {} cumsum (@var{x}) +Return the cumulative sum of each column of @var{x}. For example, + +@example +@group +cumsum ([1, 2; 3, 4]) + @result{} 1 2 + 4 6 +@end group +@end example +@end deftypefn + +@deftypefn {Built-in Function} {} cumprod (@var{x}) +Return the cumulative product of each column of @var{x}. For example, + +@example +@group +cumprod ([1, 2; 3, 4]) + @result{} 1 2 + 3 8 +@end group +@end example +@end deftypefn + +@deftypefn {Built-in Function} {} sumsq (@var{x}) +For a vector argument, return the sum of the squares of all the +elements. For a matrix argument, return the sum of the squares of the +elements in each column, as a row vector. +@end deftypefn + +@node Special Functions, Mathematical Constants, Sums and Products, Arithmetic +@section Special Functions + +@deftypefn {Mapping Function} {} besseli (@var{alpha}, @var{x}) +@deftypefnx {Mapping Function} {} besselj (@var{alpha}, @var{x}) +@deftypefnx {Mapping Function} {} besselk (@var{alpha}, @var{x}) +@deftypefnx {Mapping Function} {} bessely (@var{alpha}, @var{x}) +Compute Bessel functions of the following types: + +@table @code +@item besselj +Bessel functions of the first kind. + +@item bessely +Bessel functions of the second kind. + +@item besseli +Modified Bessel functions of the first kind. + +@item besselk +Modified Bessel functions of the second kind. +@end table + +The second argument, @var{x}, must be a real matrix, vector, or scalar. + +The first argument, @var{alpha}, must be greater than or equal to zero. +If @var{alpha} is a range, it must have an increment equal to one. + +If @var{alpha} is a scalar, the result is the same size as @var{x}. + +If @var{alpha} is a range, @var{x} must be a vector or scalar, and the +result is a matrix with @code{length(@var{x})} rows and +@code{length(@var{alpha})} columns. +@end deftypefn + +@deftypefn {Mapping Function} {} beta (@var{a}, @var{b}) +Return the Beta function, +@iftex +@tex +$$ + B (a, b) = {\Gamma (a) \Gamma (b) \over \Gamma (a + b)}. +$$ +@end tex +@end iftex +@ifinfo + +@example +beta (a, b) = gamma (a) * gamma (b) / gamma (a + b). +@end example +@end ifinfo +@end deftypefn + +@deftypefn {Mapping Function} {} betai (@var{a}, @var{b}, @var{x}) +Return the incomplete Beta function, +@iftex +@tex +$$ + \beta (a, b, x) = B (a, b)^{-1} \int_0^x t^{(a-z)} (1-t)^{(b-1)} dt. +$$ +@end tex +@end iftex +@ifinfo + +@smallexample + x + / +betai (a, b, x) = beta (a, b)^(-1) | t^(a-1) (1-t)^(b-1) dt. + / + t=0 +@end smallexample +@end ifinfo + +If x has more than one component, both @var{a} and @var{b} must be +scalars. If @var{x} is a scalar, @var{a} and @var{b} must be of +compatible dimensions. +@end deftypefn + +@deftypefn {Mapping Function} {} bincoeff (@var{n}, @var{k}) +Return the binomial coefficient of @var{n} and @var{k}, defined as +@iftex +@tex +$$ + {n \choose k} = {n (n-1) (n-2) \cdots (n-k+1) \over k!} +$$ +@end tex +@end iftex +@ifinfo + +@example +@group + / \ + | n | n (n-1) (n-2) ... (n-k+1) + | | = ------------------------- + | k | k! + \ / +@end group +@end example +@end ifinfo + +For example, + +@example +@group +bincoeff (5, 2) + @result{} 10 +@end group +@end example +@end deftypefn + +@deftypefn {Mapping Function} {} erf (@var{z}) +Computes the error function, +@iftex +@tex +$$ + {\rm erf} (z) = {2 \over \sqrt{\pi}}\int_0^z e^{-t^2} dt +$$ +@end tex +@end iftex +@ifinfo + +@smallexample + z + / +erf (z) = (2/sqrt (pi)) | e^(-t^2) dt + / + t=0 +@end smallexample +@end ifinfo +@end deftypefn + +@deftypefn {Mapping Function} {} erfc (@var{z}) +Computes the complementary error function, +@iftex +@tex +$1 - {\rm erf} (z)$. +@end tex +@end iftex +@ifinfo +@code{1 - erf (@var{z})}. +@end ifinfo +@end deftypefn + +@deftypefn {Mapping Function} {} erfinv (@var{z}) +Computes the inverse of the error function, +@end deftypefn + +@deftypefn {Mapping Function} {} gamma (@var{z}) +Computes the Gamma function, +@iftex +@tex +$$ + \Gamma (z) = \int_0^\infty t^{z-1} e^{-t} dt. +$$ +@end tex +@end iftex +@ifinfo + +@example + infinity + / +gamma (z) = | t^(z-1) exp (-t) dt. + / + t=0 +@end example +@end ifinfo +@end deftypefn + +@deftypefn {Mapping Function} {} gammai (@var{a}, @var{x}) +Computes the incomplete gamma function, +@iftex +@tex +$$ + \gamma (a, x) = {\displaystyle\int_0^x e^{-t} t^{a-1} dt \over \Gamma (a)} +$$ +@end tex +@end iftex +@ifinfo + +@smallexample + x + 1 / +gammai (a, x) = --------- | exp (-t) t^(a-1) dt + gamma (a) / + t=0 +@end smallexample +@end ifinfo + +If @var{a} is scalar, then @code{gammai (@var{a}, @var{x})} is returned +for each element of @var{x} and vice versa. + +If neither @var{a} nor @var{x} is scalar, the sizes of @var{a} and +@var{x} must agree, and @var{gammai} is applied element-by-element. +@end deftypefn + +@deftypefn {Mapping Function} {} lgamma (@var{a}, @var{x}) +@deftypefnx {Mapping Function} {} gammaln (@var{a}, @var{x}) +Return the natural logarithm of the gamma function. +@end deftypefn + +@deftypefn {Function File} {} cross (@var{x}, @var{y}) +Computes the vector cross product of the two 3-dimensional vectors +@var{x} and @var{y}. For example, + +@example +@group +cross ([1,1,0], [0,1,1]) + @result{} [ 1; -1; 1 ] +@end group +@end example +@end deftypefn + +@deftypefn {Function File} {} commutation_matrix (@var{m}, @var{n}) +Return the commutation matrix +@iftex +@tex + $K_{m,n}$ +@end tex +@end iftex +@ifinfo + K(m,n) +@end ifinfo + which is the unique +@iftex +@tex + $m n \times m n$ +@end tex +@end iftex +@ifinfo + @var{m}*@var{n} by @var{m}*@var{n} +@end ifinfo + matrix such that +@iftex +@tex + $K_{m,n} \cdot {\rm vec} (A) = {\rm vec} (A^T)$ +@end tex +@end iftex +@ifinfo + @var{K}(@var{m},@var{n}) * vec (@var{A}) = vec (@var{A}') +@end ifinfo + for all +@iftex +@tex + $m\times n$ +@end tex +@end iftex +@ifinfo + @var{m} by @var{n} +@end ifinfo + matrices +@iftex +@tex + $A$. +@end tex +@end iftex +@ifinfo + @var{A}. +@end ifinfo + +If only one argument @var{m} is given, +@iftex +@tex + $K_{m,m}$ +@end tex +@end iftex +@ifinfo + K(m,m) +@end ifinfo + is returned. + +See Magnus and Neudecker (1988), Matrix differential calculus with +applications in statistics and econometrics. +@end deftypefn + +@deftypefn {Function File} {} duplication_matrix (@var{n}) +Return the duplication matrix +@iftex +@tex + $D_n$ +@end tex +@end iftex +@ifinfo + @var{D}_@var{n} +@end ifinfo + which is the unique +@iftex +@tex + $n^2 \times n(n+1)/2$ +@end tex +@end iftex +@ifinfo + @var{n}^2 by @var{n}*(@var{n}+1)/2 +@end ifinfo + matrix such that +@iftex +@tex + $D_n * {\rm vech} (A) = {\rm vec} (A)$ +@end tex +@end iftex +@ifinfo + @var{D}_@var{n} \cdot vech (@var{A}) = vec (@var{A}) +@end ifinfo + for all symmetric +@iftex +@tex + $n \times n$ +@end tex +@end iftex +@ifinfo + @var{n} by @var{n} +@end ifinfo + matrices +@iftex +@tex + $A$. +@end tex +@end iftex +@ifinfo + @var{A}. +@end ifinfo + +See Magnus and Neudecker (1988), Matrix differential calculus with +applications in statistics and econometrics. +@end deftypefn + +@node Mathematical Constants, , Special Functions, Arithmetic +@section Mathematical Constants + +@defvr {Built-in Variable} I +@defvrx {Built-in Variable} J +@defvrx {Built-in Variable} i +@defvrx {Built-in Variable} j +A pure imaginary number, defined as +@iftex +@tex + $\sqrt{-1}$. +@end tex +@end iftex +@ifinfo + @code{sqrt (-1)}. +@end ifinfo +The @code{I} and @code{J} forms are true constants, and cannot be +modified. The @code{i} and @code{j} forms are like ordinary variables, +and may be used for other purposes. However, unlike other variables, +they once again assume their special predefined values if they are +cleared @xref{Status of Variables}. +@end defvr + +@defvr {Built-in Variable} Inf +@defvrx {Built-in Variable} inf +Infinity. This is the result of an operation like 1/0, or an operation +that results in a floating point overflow. +@end defvr + +@defvr {Built-in Variable} NaN +@defvrx {Built-in Variable} nan +Not a number. This is the result of an operation like +@iftex +@tex +$0/0$, or $\infty - \infty$, +@end tex +@end iftex +@ifinfo +0/0, or @samp{Inf - Inf}, +@end ifinfo +or any operation with a NaN. + +Note that NaN always compares not equal to NaN. This behavior is +specified by the IEEE standard for floating point arithmetic. To +find NaN values, you must use the @code{isnan} function. +@end defvr + +@defvr {Built-in Variable} pi +The ratio of the circumference of a circle to its diameter. +Internally, @code{pi} is computed as @samp{4.0 * atan (1.0)}. +@end defvr + +@defvr {Built-in Variable} e +The base of natural logarithms. The constant +@iftex +@tex + $e$ +@end tex +@end iftex +@ifinfo + @var{e} +@end ifinfo + satisfies the equation +@iftex +@tex + $\log (e) = 1$. +@end tex +@end iftex +@ifinfo + @code{log} (@var{e}) = 1. +@end ifinfo +@end defvr + +@defvr {Built-in Variable} eps +The machine precision. More precisely, @code{eps} is the largest +relative spacing between any two adjacent numbers in the machine's +floating point system. This number is obviously system-dependent. On +machines that support 64 bit IEEE floating point arithmetic, @code{eps} +is approximately +@ifinfo + 2.2204e-16. +@end ifinfo +@iftex +@tex + $2.2204\times10^{-16}$. +@end tex +@end iftex +@end defvr + +@defvr {Built-in Variable} realmax +The largest floating point number that is representable. The actual +value is system-dependent. On machines that support 64 bit IEEE +floating point arithmetic, @code{realmax} is approximately +@ifinfo + 1.7977e+308 +@end ifinfo +@iftex +@tex + $1.7977\times10^{308}$. +@end tex +@end iftex +@end defvr + +@defvr {Built-in Variable} realmin +The smallest floating point number that is representable. The actual +value is system-dependent. On machines that support 64 bit IEEE +floating point arithmetic, @code{realmin} is approximately +@ifinfo + 2.2251e-308 +@end ifinfo +@iftex +@tex + $2.2251\times10^{-308}$. +@end tex +@end iftex +@end defvr diff --git a/doc/interpreter/audio.texi b/doc/interpreter/audio.texi deleted file mode 100644 --- a/doc/interpreter/audio.texi +++ /dev/null @@ -1,98 +0,0 @@ -@c Copyright (C) 1996, 1997 John W. Eaton -@c Written by Kurt Hornik on 1996/05/14 -@c This is part of the Octave manual. -@c For copying conditions, see the file gpl.texi. - -@node Audio Processing, System Utilities, Image Processing, Top -@chapter Audio Processing - -Octave provides a few functions for dealing with audio data. An audio -`sample' is a single output value from an A/D converter, i.e., a small -integer number (usually 8 or 16 bits), and audio data is just a series -of such samples. It can be characterized by three parameters: the -sampling rate (measured in samples per second or Hz, e.g. 8000 or -44100), the number of bits per sample (e.g. 8 or 16), and the number of -channels (1 for mono, 2 for stereo, etc.). - -There are many different formats for representing such data. Currently, -only the two most popular, @emph{linear encoding} and @emph{mu-law -encoding}, are supported by Octave. There is an excellent FAQ on audio -formats by Guido van Rossum which can be found at any -FAQ ftp site, in particular in the directory -@file{/pub/usenet/news.answers/audio-fmts} of the archive site -@code{rtfm.mit.edu}. - -Octave simply treats audio data as vectors of samples (non-mono data are -not supported yet). It is assumed that audio files using linear -encoding have one of the extensions @file{lin} or @file{raw}, and that -files holding data in mu-law encoding end in @file{au}, @file{mu}, or -@file{snd}. - -@deftypefn {Function File} {} lin2mu (@var{x}) -If the vector @var{x} represents mono audio data in 8- or 16-bit -linear encoding, @code{lin2mu (@var{x})} is the corresponding mu-law -encoding. -@end deftypefn - -@deftypefn {Function File} {} mu2lin (@var{x}, @var{bps}) -If the vector @var{x} represents mono audio data in mu-law encoding, -@code{mu2lin} converts it to linear encoding. The optional argument -@var{bps} specifies whether the input data uses 8 bit per sample -(default) or 16 bit. -@end deftypefn - -@deftypefn {Function File} {} loadaudio (@var{name}, @var{ext}, @var{bps}) -Loads audio data from the file @file{@var{name}.@var{ext}} into the -vector @var{x}. - -The extension @var{ext} determines how the data in the audio file is -interpreted; the extensions @file{lin} (default) and @file{raw} -correspond to linear, the extensions @file{au}, @file{mu}, or @file{snd} -to mu-law encoding. - -The argument @var{bps} can be either 8 (default) or 16, and specifies -the number of bits per sample used in the audio file. -@end deftypefn - -@deftypefn {Function File} {} saveaudio (@var{name}, @var{x}, @var{ext}, @var{bps}) -Saves a vector @var{x} of audio data to the file -@file{@var{name}.@var{ext}}. The optional parameters @var{ext} and -@var{bps} determine the encoding and the number of bits per sample used -in the audio file (see @code{loadaudio}); defaults are @file{lin} and -8, respectively. -@end deftypefn - -The following functions for audio I/O require special A/D hardware and -operating system support. It is assumed that audio data in linear -encoding can be played and recorded by reading from and writing to -@file{/dev/dsp}, and that similarly @file{/dev/audio} is used for mu-law -encoding. These file names are system-dependent. Improvements so that -these functions will work without modification on a wide variety of -hardware are welcome. - -@deftypefn {Function File} {} playaudio (@var{name}, @var{ext}) -@deftypefnx {Function File} {} playaudio (@var{x}) -Plays the audio file @file{@var{name}.@var{ext}} or the audio data -stored in the vector @var{x}. -@end deftypefn - -@deftypefn {Function File} {} record (@var{sec}, @var{sampling_rate}) -Records @var{sec} seconds of audio input into the vector @var{x}. The -default value for @var{sampling_rate} is 8000 samples per second, or -8kHz. The program waits until the user types @key{RET} and then -immediately starts to record. -@end deftypefn - -@deftypefn {Function File} {} setaudio (@var{type}) -@deftypefnx {Function File} {} setaudio (@var{type}, @var{value}) -Set or display various properties of your mixer hardware. - -For example, if @code{vol} corresponds to the volume property, you can -set it to 50 (percent) by @code{setaudio ("vol", 50)}. - -This is an simple experimental program to control the audio hardware -settings. It assumes that there is a @code{mixer} program which can be -used as @code{mixer @var{type} @var{value}}, and simply executes -@code{system ("mixer @var{type} @var{value}")}. Future releases might -get rid of this assumption by using the @code{fcntl} interface. -@end deftypefn diff --git a/doc/interpreter/audio.txi b/doc/interpreter/audio.txi new file mode 100644 --- /dev/null +++ b/doc/interpreter/audio.txi @@ -0,0 +1,98 @@ +@c Copyright (C) 1996, 1997 John W. Eaton +@c Written by Kurt Hornik on 1996/05/14 +@c This is part of the Octave manual. +@c For copying conditions, see the file gpl.texi. + +@node Audio Processing, System Utilities, Image Processing, Top +@chapter Audio Processing + +Octave provides a few functions for dealing with audio data. An audio +`sample' is a single output value from an A/D converter, i.e., a small +integer number (usually 8 or 16 bits), and audio data is just a series +of such samples. It can be characterized by three parameters: the +sampling rate (measured in samples per second or Hz, e.g. 8000 or +44100), the number of bits per sample (e.g. 8 or 16), and the number of +channels (1 for mono, 2 for stereo, etc.). + +There are many different formats for representing such data. Currently, +only the two most popular, @emph{linear encoding} and @emph{mu-law +encoding}, are supported by Octave. There is an excellent FAQ on audio +formats by Guido van Rossum which can be found at any +FAQ ftp site, in particular in the directory +@file{/pub/usenet/news.answers/audio-fmts} of the archive site +@code{rtfm.mit.edu}. + +Octave simply treats audio data as vectors of samples (non-mono data are +not supported yet). It is assumed that audio files using linear +encoding have one of the extensions @file{lin} or @file{raw}, and that +files holding data in mu-law encoding end in @file{au}, @file{mu}, or +@file{snd}. + +@deftypefn {Function File} {} lin2mu (@var{x}) +If the vector @var{x} represents mono audio data in 8- or 16-bit +linear encoding, @code{lin2mu (@var{x})} is the corresponding mu-law +encoding. +@end deftypefn + +@deftypefn {Function File} {} mu2lin (@var{x}, @var{bps}) +If the vector @var{x} represents mono audio data in mu-law encoding, +@code{mu2lin} converts it to linear encoding. The optional argument +@var{bps} specifies whether the input data uses 8 bit per sample +(default) or 16 bit. +@end deftypefn + +@deftypefn {Function File} {} loadaudio (@var{name}, @var{ext}, @var{bps}) +Loads audio data from the file @file{@var{name}.@var{ext}} into the +vector @var{x}. + +The extension @var{ext} determines how the data in the audio file is +interpreted; the extensions @file{lin} (default) and @file{raw} +correspond to linear, the extensions @file{au}, @file{mu}, or @file{snd} +to mu-law encoding. + +The argument @var{bps} can be either 8 (default) or 16, and specifies +the number of bits per sample used in the audio file. +@end deftypefn + +@deftypefn {Function File} {} saveaudio (@var{name}, @var{x}, @var{ext}, @var{bps}) +Saves a vector @var{x} of audio data to the file +@file{@var{name}.@var{ext}}. The optional parameters @var{ext} and +@var{bps} determine the encoding and the number of bits per sample used +in the audio file (see @code{loadaudio}); defaults are @file{lin} and +8, respectively. +@end deftypefn + +The following functions for audio I/O require special A/D hardware and +operating system support. It is assumed that audio data in linear +encoding can be played and recorded by reading from and writing to +@file{/dev/dsp}, and that similarly @file{/dev/audio} is used for mu-law +encoding. These file names are system-dependent. Improvements so that +these functions will work without modification on a wide variety of +hardware are welcome. + +@deftypefn {Function File} {} playaudio (@var{name}, @var{ext}) +@deftypefnx {Function File} {} playaudio (@var{x}) +Plays the audio file @file{@var{name}.@var{ext}} or the audio data +stored in the vector @var{x}. +@end deftypefn + +@deftypefn {Function File} {} record (@var{sec}, @var{sampling_rate}) +Records @var{sec} seconds of audio input into the vector @var{x}. The +default value for @var{sampling_rate} is 8000 samples per second, or +8kHz. The program waits until the user types @key{RET} and then +immediately starts to record. +@end deftypefn + +@deftypefn {Function File} {} setaudio (@var{type}) +@deftypefnx {Function File} {} setaudio (@var{type}, @var{value}) +Set or display various properties of your mixer hardware. + +For example, if @code{vol} corresponds to the volume property, you can +set it to 50 (percent) by @code{setaudio ("vol", 50)}. + +This is an simple experimental program to control the audio hardware +settings. It assumes that there is a @code{mixer} program which can be +used as @code{mixer @var{type} @var{value}}, and simply executes +@code{system ("mixer @var{type} @var{value}")}. Future releases might +get rid of this assumption by using the @code{fcntl} interface. +@end deftypefn diff --git a/doc/interpreter/basics.texi b/doc/interpreter/basics.texi deleted file mode 100644 --- a/doc/interpreter/basics.texi +++ /dev/null @@ -1,1130 +0,0 @@ -@c Copyright (C) 1996, 1997 John W. Eaton -@c This is part of the Octave manual. -@c For copying conditions, see the file gpl.texi. - -@node Getting Started, Data Types, Introduction, Top -@chapter Getting Started - -This chapter explains some of Octave's basic features, including how to -start an Octave session, get help at the command prompt, edit the -command line, and write Octave programs that can be executed as commands -from your shell. - -@menu -* Invoking Octave:: -* Quitting Octave:: -* Getting Help:: -* Command Line Editing:: -* Errors:: -* Executable Octave Programs:: -* Comments:: -@end menu - -@node Invoking Octave, Quitting Octave, Getting Started, Getting Started -@section Invoking Octave - -Normally, Octave is used interactively by running the program -@samp{octave} without any arguments. Once started, Octave reads -commands from the terminal until you tell it to exit. - -You can also specify the name of a file on the command line, and Octave -will read and execute the commands from the named file and then exit -when it is finished. - -You can further control how Octave starts by using the command-line -options described in the next section, and Octave itself can remind you -of the options available. Type @samp{octave --help} to display all -available options and briefly describe their use (@samp{octave -h} is a -shorter equivalent). - -@menu -* Command Line Options:: -* Startup Files:: -@end menu - -@node Command Line Options, Startup Files, Invoking Octave, Invoking Octave -@subsection Command Line Options -@cindex Octave command options -@cindex command options -@cindex options, Octave command - -Here is a complete list of all the command line options that Octave -accepts. - -@table @code -@item --debug -@itemx -d -@cindex @code{--debug} -@cindex @code{-d} -Enter parser debugging mode. Using this option will cause Octave's -parser to print a lot of information about the commands it reads, and is -probably only useful if you are actually trying to debug the parser. - -@item --echo-commands -@itemx -x -@cindex @code{--echo-commands} -@cindex @code{-x} -Echo commands as they are executed. - -@item --exec-path @var{path} -@cindex @code{--exec-path @var{path}} -Specify the path to search for programs to run. The value of @var{path} -specified on the command line will override any value of -@code{OCTAVE_EXEC_PATH} found in the environment, but not any commands -in the system or user startup files that set the built-in variable -@code{EXEC_PATH}. - -@item --help -@itemx -h -@itemx -? -@cindex @code{--help} -@cindex @code{-h} -@cindex @code{-?} -Print short help message and exit. - -@item --info-file @var{filename} -@cindex @code{--info-file @var{filename}} -Specify the name of the info file to use. The value of @var{filename} -specified on the command line will override any value of -@code{OCTAVE_INFO_FILE} found in the environment, but not any commands -in the system or user startup files that set the built-in variable -@code{INFO_FILE}. - -@item --info-program @var{program} -@cindex @code{--info-program @var{program}} -Specify the name of the info program to use. The value of @var{program} -specified on the command line will override any value of -@code{OCTAVE_INFO_PROGRAM} found in the environment, but not any -commands in the system or user startup files that set the built-in -variable @code{INFO_PROGRAM}. - -@item --interactive -@itemx -i -@cindex @code{--interactive} -@cindex @code{-i} -Force interactive behavior. This can be useful for running Octave via a -remote shell command or inside an Emacs shell buffer. For another way -to run Octave within Emacs, see @ref{Emacs}. - -@item --no-init-file -@cindex @code{--no-init-file} -Don't read the @file{~/.octaverc} or @file{.octaverc} files. - -@item --no-line-editing -@cindex @code{--no-line-editing} -Disable command-line editing. - -@item --no-site-file -@cindex @code{--no-site-file} -Don't read the site-wide @file{octaverc} file. - -@item --norc -@itemx -f -@cindex @code{--norc} -@cindex @code{-f} -Don't read any of the system or user initialization files at startup. -This is equivalent to using both of the options @code{--no-init-file} -and @code{--no-site-file}. - -@item --path @var{path} -@itemx -p @var{path} -@cindex @code{--path @var{path}} -@cindex @code{-p @var{path}} -Specify the path to search for function files. The value of @var{path} -specified on the command line will override any value of -@code{OCTAVE_PATH} found in the environment, but not any commands in the -system or user startup files that set the built-in variable @code{LOADPATH}. - -@item --silent -@itemx --quiet -@itemx -q -@cindex @code{--silent} -@cindex @code{--quiet} -@cindex @code{-q} -Don't print the usual greeting and version message at startup. - -@item --traditional -@itemx --braindead -@cindex @code{--traditional} -@cindex @code{--braindead} -Set initial values for user-preference variables to the following -values for compatibility with @sc{Matlab}. - -@example -PS1 = ">> " -PS2 = "" -beep_on_error = 1 -default_save_format = "mat-binary" -define_all_return_values = 1 -do_fortran_indexing = 1 -crash_dumps_octave_core = 0 -empty_list_elements_ok = 1 -implicit_str_to_num_ok = 1 -ok_to_lose_imaginary_part = 1 -page_screen_output = 0 -prefer_column_vectors = 0 -print_empty_dimensions = 0 -treat_neg_dim_as_zero = 1 -warn_function_name_clash = 0 -whitespace_in_literal_matrix = "traditional" -@end example - -@item --verbose -@itemx -V -@cindex @code{--verbose} -@cindex @code{-V} -Turn on verbose output. - -@item --version -@itemx -v -@cindex @code{--version} -@cindex @code{-v} -Print the program version number and exit. - -@item @var{file} -Execute commands from @var{file}. -@end table - -Octave also includes several built-in variables that contain information -about the command line, including the number of arguments and all of the -options. - -@defvr {Built-in Variable} argv -The command line arguments passed to Octave are available in this -variable. For example, if you invoked Octave using the command - -@example -octave --no-line-editing --silent -@end example - -@noindent -@code{argv} would be a list of strings with the elements -@code{--no-line-editing} and @code{--silent}. - -If you write an executable Octave script, @code{argv} will contain the -list of arguments passed to the script. @pxref{Executable Octave Programs}. -@end defvr - -@defvr {Built-in Variable} program_invocation_name -@defvrx {Built-in Variable} program_name -When Octave starts, the value of the built-in variable -@code{program_invocation_name} is automatically set to the name that was -typed at the shell prompt to run Octave, and the value of -@code{program_name} is automatically set to the final component of -@code{program_invocation_name}. For example, if you typed -@samp{@value{OCTAVEHOME}/bin/octave} to start Octave, -@code{program_invocation_name} would have the value -@code{"@value{OCTAVEHOME}/bin/octave"}, and @code{program_name} would -have the value @code{"octave"}. - -If executing a script from the command line (e.g., @code{octave foo.m}) -or using an executable Octave script, the program name is set to the -name of the script. @xref{Executable Octave Programs} for an example of -how to create an executable Octave script. -@end defvr - -Here is an example of using these variables to reproduce Octave's -command line. - -@example -printf ("%s", program_name); -for i = 1:nargin - printf (" %s", argv(i)); -endfor -printf ("\n"); -@end example - -@noindent -@xref{Index Expressions} for an explanation of how to properly index -arrays of strings and substrings in Octave, and @xref{Defining Functions} -for information about the variable @code{nargin}. - -@node Startup Files, , Command Line Options, Invoking Octave -@subsection Startup Files -@cindex initialization -@cindex startup - -When Octave starts, it looks for commands to execute from the following -files: - -@cindex startup files - -@table @code -@item @var{octave-home}/share/octave/site/m/startup/octaverc -Where @var{octave-home} is the directory in which all of Octave is -installed (the default is @file{@value{OCTAVEHOME}}). This file is -provided so that changes to the default Octave environment can be made -globally for all users at your site for all versions of Octave you have -installed. Some care should be taken when making changes to this file, -since all users of Octave at your site will be affected. - -@item @var{octave-home}/share/octave/@var{version}/m/startup/octaverc -Where @var{octave-home} is the directory in which all of Octave is -installed (the default is @file{@value{OCTAVEHOME}}), and @var{version} -is the version number of Octave. This file is provided so that changes -to the default Octave environment can be made globally for all users for -a particular version of Octave. Some care should be taken when making -changes to this file, since all users of Octave at your site will be -affected. - -@item ~/.octaverc -@cindex @code{~/.octaverc} -This file is normally used to make personal changes to the default -Octave environment. - -@item .octaverc -@cindex @code{.octaverc} -This file can be used to make changes to the default Octave environment -for a particular project. Octave searches for this file in the current -directory after it reads @file{~/.octaverc}. Any use of the @code{cd} -command in the @file{~/.octaverc} file will affect the directory that -Octave searches for the file @file{.octaverc}. - -If you start Octave in your home directory, commands from from the file -@file{~/.octaverc} will only be executed once. -@end table - -A message will be displayed as each of the startup files is read if you -invoke Octave with the @code{--verbose} option but without the -@code{--silent} option. - -Startup files may contain any valid Octave commands, including function -definitions. - -@node Quitting Octave, Getting Help, Invoking Octave, Getting Started -@section Quitting Octave -@cindex exiting octave -@cindex quitting octave - -@deftypefn {Built-in Function} {} exit (@var{status}) -@deftypefnx {Built-in Function} {} quit (@var{status}) -Exit the current Octave session. If the optional integer value -@var{status} is supplied, pass that value to the operating system as the -Octave's exit status. -@end deftypefn - -@deftypefn {Built-in Function} {} atexit (@var{fcn}) -Register function to be called when Octave exits. For example, - -@example -@group -function print_flops_at_exit () - printf ("\n%s\n", system ("fortune")); - fflush (stdout); -endfunction -atexit ("print_flops_at_exit"); -@end group -@end example - -@noindent -will print a message when Octave exits. -@end deftypefn - -@node Getting Help, Command Line Editing, Quitting Octave, Getting Started -@section Commands for Getting Help -@cindex on-line help -@cindex help, on-line - -The entire text of this manual is available from the Octave prompt -via the command @kbd{help -i}. In addition, the documentation for -individual user-written functions and variables is also available via -the @kbd{help} command. This section describes the commands used for -reading the manual and the documentation strings for user-supplied -functions and variables. @xref{Function Files}, for more information -about how to document the functions you write. - -@deffn {Command} help -Octave's @code{help} command can be used to print brief usage-style -messages, or to display information directly from an on-line version of -the printed manual, using the GNU Info browser. If invoked without any -arguments, @code{help} prints a list of all the available operators, -functions, and built-in variables. If the first argument is @code{-i}, -the @code{help} command searches the index of the on-line version of -this manual for the given topics. - -For example, the command @kbd{help help} prints a short message -describing the @code{help} command, and @kbd{help -i help} starts the -GNU Info browser at this node in the on-line version of the manual. - -Once the GNU Info browser is running, help for using it is available -using the command @kbd{C-h}. -@end deffn - -The help command can give you information about operators, but not the -comma and semicolons that are used as command separators. To get help -for those, you must type @kbd{help comma} or @kbd{help semicolon}. - -@defvr {Built-in Variable} INFO_FILE -The variable @code{INFO_FILE} names the location of the Octave info file. -The default value is @code{"@var{octave-home}/info/octave.info"}, where -@var{octave-home} is the directory where all of Octave is installed. -@end defvr - -@defvr {Built-in Variable} INFO_PROGRAM -The variable @code{INFO_PROGRAM} names the info program to run. Its -initial value is -@code{"@var{octave-home}/libexec/octave/@var{version}/exec/@var{arch}/info"}, -where @var{octave-home} is the directory where all of Octave is -installed, @var{version} is the Octave version number, and @var{arch} is -the machine type. The value of @code{INFO_PROGRAM} can be overridden by -the environment variable @code{OCTAVE_INFO_PROGRAM}, or the command line -argument @code{--info-program NAME}, or by setting the value of the -built-in variable @code{INFO_PROGRAM} in a startup script. -@end defvr - -@defvr {Built-in Variable} suppress_verbose_help_message -If the value of @code{suppress_verbose_help_message} is nonzero, Octave -will not add additional help information to the end of the output from -the @code{help} command and usage messages for built-in commands. -@end defvr - -@node Command Line Editing, Errors, Getting Help, Getting Started -@section Command Line Editing -@cindex command-line editing -@cindex editing the command line - -Octave uses the GNU readline library to provide an extensive set of -command-line editing and history features. Only the most common -features are described in this manual. Please see The GNU Readline -Library manual for more information. - -To insert printing characters (letters, digits, symbols, etc.), simply -type the character. Octave will insert the character at the cursor and -advance the cursor forward. - -Many of the command-line editing functions operate using control -characters. For example, the character @kbd{Control-a} moves the cursor -to the beginning of the line. To type @kbd{C-a}, hold down @key{CTRL} -and then press @key{a}. In the following sections, control characters -such as @kbd{Control-a} are written as @kbd{C-a}. - -Another set of command-line editing functions use Meta characters. On -some terminals, you type @kbd{M-u} by holding down @key{META} and -pressing @key{u}. If your terminal does not have a @key{META} key, you -can still type Meta charcters using two-character sequences starting -with @kbd{ESC}. Thus, to enter @kbd{M-u}, you could type -@key{ESC}@key{u}. The @kbd{ESC} character sequences are also allowed on -terminals with real Meta keys. In the following sections, Meta -characters such as @kbd{Meta-u} are written as @kbd{M-u}. - -@menu -* Cursor Motion:: -* Killing and Yanking:: -* Commands For Text:: -* Commands For Completion:: -* Commands For History:: -* Customizing the Prompt:: -* Diary and Echo Commands:: -@end menu - -@node Cursor Motion, Killing and Yanking, Command Line Editing, Command Line Editing -@subsection Cursor Motion - -The following commands allow you to position the cursor. - -@table @kbd -@item C-b -Move back one character. - -@item C-f -Move forward one character. - -@item @key{DEL} -Delete the character to the left of the cursor. - -@item C-d -Delete the character underneath the cursor. - -@item M-f -Move forward a word. - -@item M-b -Move backward a word. - -@item C-a -Move to the start of the line. - -@item C-e -Move to the end of the line. - -@item C-l -Clear the screen, reprinting the current line at the top. - -@item C-_ -@itemx C-/ -Undo the last thing that you did. You can undo all the way back to an -empty line. - -@item M-r -Undo all changes made to this line. This is like typing the `undo' -command enough times to get back to the beginning. -@end table - -The above table describes the most basic possible keystrokes that you need -in order to do editing of the input line. On most terminals, you can -also use the arrow keys in place of @kbd{C-f} and @kbd{C-b} to move -forward and backward. - -Notice how @kbd{C-f} moves forward a character, while @kbd{M-f} moves -forward a word. It is a loose convention that control keystrokes -operate on characters while meta keystrokes operate on words. - -There is also a function available so that you can clear the screen from -within Octave programs. - -@cindex clearing the screen - -@deftypefn {Built-in Function} {} clc () -@deftypefnx {Built-in Function} {} home () -Clear the terminal screen and move the cursor to the upper left corner. -@end deftypefn - -@node Killing and Yanking, Commands For Text, Cursor Motion, Command Line Editing -@subsection Killing and Yanking - -@dfn{Killing} text means to delete the text from the line, but to save -it away for later use, usually by @dfn{yanking} it back into the line. -If the description for a command says that it `kills' text, then you can -be sure that you can get the text back in a different (or the same) -place later. - -Here is the list of commands for killing text. - -@table @kbd -@item C-k -Kill the text from the current cursor position to the end of the line. - -@item M-d -Kill from the cursor to the end of the current word, or if between -words, to the end of the next word. - -@item M-@key{DEL} -Kill from the cursor to the start of the previous word, or if between -words, to the start of the previous word. - -@item C-w -Kill from the cursor to the previous whitespace. This is different than -@kbd{M-@key{DEL}} because the word boundaries differ. -@end table - -And, here is how to @dfn{yank} the text back into the line. Yanking -means to copy the most-recently-killed text from the kill buffer. - -@table @kbd -@item C-y -Yank the most recently killed text back into the buffer at the cursor. - -@item M-y -Rotate the kill-ring, and yank the new top. You can only do this if -the prior command is @kbd{C-y} or @kbd{M-y}. -@end table - -When you use a kill command, the text is saved in a @dfn{kill-ring}. -Any number of consecutive kills save all of the killed text together, so -that when you yank it back, you get it in one clean sweep. The kill -ring is not line specific; the text that you killed on a previously -typed line is available to be yanked back later, when you are typing -another line. - -@node Commands For Text, Commands For Completion, Killing and Yanking, Command Line Editing -@subsection Commands For Changing Text - -The following commands can be used for entering characters that would -otherwise have a special meaning (e.g., @kbd{TAB}, @kbd{C-q}, etc.), or -for quickly correcting typing mistakes. - -@table @kbd -@item C-q -@itemx C-v -Add the next character that you type to the line verbatim. This is -how to insert things like @kbd{C-q} for example. - -@item M-@key{TAB} -Insert a tab character. - -@item C-t -Drag the character before the cursor forward over the character at the -cursor, also moving the cursor forward. If the cursor is at the end of -the line, then transpose the two characters before it. - -@item M-t -Drag the word behind the cursor past the word in front of the cursor -moving the cursor over that word as well. - -@item M-u -Uppercase the characters following the cursor to the end of the current -(or following) word, moving the cursor to the end of the word. - -@item M-l -Lowecase the characters following the cursor to the end of the current -(or following) word, moving the cursor to the end of the word. - -@item M-c -Uppercase the character following the cursor (or the beginning of the -next word if the cursor is between words), moving the cursor to the end -of the word. -@end table - -@node Commands For Completion, Commands For History, Commands For Text, Command Line Editing -@subsection Letting Readline Type For You -@cindex command completion - -The following commands allow Octave to complete command and variable -names for you. - -@table @kbd -@item @key{TAB} -Attempt to do completion on the text before the cursor. Octave can -complete the names of commands and variables. - -@item M-? -List the possible completions of the text before the cursor. -@end table - -@defvr {Built-in Variable} completion_append_char -The value of @code{completion_append_char} is used as the character to -append to successful command-line completion attempts. The default -value is @code{" "} (a single space). -@end defvr - -@deftypefn {Built-in Function} {} completion_matches (@var{hint}) -Generate possible completions given @var{hint}. - -This function is provided for the benefit of programs like Emacs which -might be controlling Octave and handling user input. The current -command number is not incremented when this function is called. This is -a feature, not a bug. -@end deftypefn - -@node Commands For History, Customizing the Prompt, Commands For Completion, Command Line Editing -@subsection Commands For Manipulating The History -@cindex command history -@cindex input history -@cindex history of commands - -Octave normally keeps track of the commands you type so that you can -recall previous commands to edit or execute them again. When you exit -Octave, the most recent commands you have typed, up to the number -specified by the variable @code{history_size}, are saved in a file. -When Octave starts, it loads an initial list of commands from the file -named by the variable @code{history_file}. - -Here are the commands for simple browsing and searching the history -list. - -@table @kbd -@item @key{LFD} -@itemx @key{RET} -Accept the line regardless of where the cursor is. If this line is -non-empty, add it to the history list. If this line was a history -line, then restore the history line to its original state. - -@item C-p -Move `up' through the history list. - -@item C-n -Move `down' through the history list. - -@item M-< -Move to the first line in the history. - -@item M-> -Move to the end of the input history, i.e., the line you are entering! - -@item C-r -Search backward starting at the current line and moving `up' through -the history as necessary. This is an incremental search. - -@item C-s -Search forward starting at the current line and moving `down' through -the history as necessary. -@end table - -On most terminals, you can also use the arrow keys in place of @kbd{C-p} -and @kbd{C-n} to move through the history list. - -In addition to the keyboard commands for moving through the history -list, Octave provides three functions for viewing, editing, and -re-running chunks of commands from the history list. - -@deffn {Command} history options -If invoked with no arguments, @code{history} displays a list of commands -that you have executed. Valid options are: - -@table @code -@item -w @var{file} -Write the current history to the file @var{file}. If the name is -omitted, use the default history file (normally @file{~/.octave_hist}). - -@item -r @var{file} -Read the file @var{file}, replacing the current history list with its -contents. If the name is omitted, use the default history file -(normally @file{~/.octave_hist}). - -@item @var{N} -Only display the most recent @var{N} lines of history. - -@item -q -Don't number the displayed lines of history. This is useful for cutting -and pasting commands if you are using the X Window System. -@end table - -For example, to display the five most recent commands that you have -typed without displaying line numbers, use the command -@kbd{history -q 5}. -@end deffn - -@deffn {Command} edit_history options -If invoked with no arguments, @code{edit_history} allows you to edit the -history list using the editor named by the variable @code{EDITOR}. The -commands to be edited are first copied to a temporary file. When you -exit the editor, Octave executes the commands that remain in the file. -It is often more convenient to use @code{edit_history} to define functions -rather than attempting to enter them directly on the command line. -By default, the block of commands is executed as soon as you exit the -editor. To avoid executing any commands, simply delete all the lines -from the buffer before exiting the editor. - -The @code{edit_history} command takes two optional arguments specifying -the history numbers of first and last commands to edit. For example, -the command - -@example -edit_history 13 -@end example - -@noindent -extracts all the commands from the 13th through the last in the history -list. The command - -@example -edit_history 13 169 -@end example - -@noindent -only extracts commands 13 through 169. Specifying a larger number for -the first command than the last command reverses the list of commands -before placing them in the buffer to be edited. If both arguments are -omitted, the previous command in the history list is used. -@end deffn - -@deffn {Command} run_history -Similar to @code{edit_history}, except that the editor is not invoked, -and the commands are simply executed as they appear in the history list. -@end deffn - -@defvr {Built-in Variable} EDITOR -A string naming the editor to use with the @code{edit_history} command. -If the environment variable @code{EDITOR} is set when Octave starts, its -value is used as the default. Otherwise, @code{EDITOR} is set to -@code{"emacs"}. -@end defvr - -@defvr {Built-in Variable} history_file -This variable specifies the name of the file used to store command -history. The default value is @code{"~/.octave_hist"}, but may be -overridden by the environment variable @code{OCTAVE_HISTFILE}. -@end defvr - -@defvr {Built-in Variable} history_size -This variable specifies how many entries to store in the history file. -The default value is @code{1024}, but may be overridden by the -environment variable @code{OCTAVE_HISTSIZE}. -@end defvr - -@defvr {Built-in Variable} saving_history -If the value of @code{saving_history} is nonzero, command entered -on the command line are saved in the file specified by the variable -@code{history_file}. -@end defvr - -@node Customizing the Prompt, Diary and Echo Commands, Commands For History, Command Line Editing -@subsection Customizing the Prompt -@cindex prompt customization -@cindex customizing the prompt - -The following variables are available for customizing the appearance of -the command-line prompts. Octave allows the prompt to be customized by -inserting a number of backslash-escaped special characters that are -decoded as follows: - -@table @samp -@item \t -The time. - -@item \d -The date. - -@item \n -Begins a new line by printing the equivalent of a carriage return -followed by a line feed. - -@item \s -The name of the program (usually just @samp{octave}). - -@item \w -The current working directory. - -@item \W -The basename of the current working directory. - -@item \u -The username of the current user. - -@item \h -The hostname, up to the first `.'. - -@item \H -The hostname. - -@item \# -The command number of this command, counting from when Octave starts. - -@item \! -The history number of this command. This differs from @samp{\#} by the -number of commands in the history list when Octave starts. - -@item \$ -If the effective UID is 0, a @samp{#}, otherwise a @samp{$}. - -@item \nnn -The character whose character code in octal is @var{nnn}. - -@item \\ -A backslash. -@end table - -@defvr {Built-in Variable} PS1 -The primary prompt string. When executing interactively, Octave -displays the primary prompt @code{PS1} when it is ready to read a -command. - -The default value of @code{PS1} is @code{"\s:\#> "}. To change it, use a -command like - -@example -octave:13> PS1 = "\\u@@\\H> " -@end example - -@noindent -which will result in the prompt @samp{boris@@kremvax> } for the user -@samp{boris} logged in on the host @samp{kremvax.kgb.su}. Note that two -backslashes are required to enter a backslash into a string. -@xref{Strings}. -@end defvr - -@defvr {Built-in Variable} PS2 -The secondary prompt string, which is printed when Octave is -expecting additional input to complete a command. For example, when -defining a function over several lines, Octave will print the value of -@code{PS1} at the beginning of each line after the first. The default -value of @code{PS2} is @code{"> "}. -@end defvr - -@defvr {Built-in Variable} PS4 -If Octave is invoked with the @code{--echo-input} option, the value of -@code{PS4} is printed before each line of input that is echoed. The -default value of @code{PS4} is @code{"+ "}. @xref{Invoking Octave}, for -a description of @code{--echo-input}. -@end defvr - -@node Diary and Echo Commands, , Customizing the Prompt, Command Line Editing -@subsection Diary and Echo Commands -@cindex diary of commands and output -@cindex command and ouput logs -@cindex logging commands and output -@cindex echoing executing commands -@cindex command echoing - -Octave's diary feature allows you to keep a log of all or part of an -interactive session by recording the input you type and the output that -Octave produces in a separate file. - -@deffn {Command} diary options -Create a list of all commands @emph{and} the output they produce, mixed -together just as you see them on your terminal. Valid options are: - -@table @code -@item on -Start recording your session in a file called @file{diary} in your -current working directory. - -@item off -Stop recording your session in the diary file. - -@item @var{file} -Record your session in the file named @var{file}. -@end table - -Without any arguments, @code{diary} toggles the current diary state. -@end deffn - -Sometimes it is useful to see the commands in a function or script as -they are being evaluated. This can be especially helpful for debugging -some kinds of problems. - -@deffn {Command} echo options -Control whether commands are displayed as they are executed. Valid -options are: - -@table @code -@item on -Enable echoing of commands as they are executed in script files. - -@item off -Disable echoing of commands as they are executed in script files. - -@item on all -Enable echoing of commands as they are executed in script files and -functions. - -@item off all -Disable echoing of commands as they are executed in script files and -functions. -@end table - -@noindent -If invoked without any arguments, @code{echo} toggles the current echo -state. -@end deffn - -@defvr {Built-in Variable} echo_executing_commands -This variable may also be used to control the echo state. It may be -the sum of the following values: - -@table @asis -@item 1 -Echo commands read from script files. - -@item 2 -Echo commands from functions. - -@item 4 -Echo commands read from command line. -@end table - -More than one state can be active at once. For example, a value of 3 is -equivalent to the command @kbd{echo on all}. - -The value of @code{echo_executing_commands} is set by the @kbd{echo} -command and the command line option @code{--echo-input}. -@end defvr - -@node Errors, Executable Octave Programs, Command Line Editing, Getting Started -@section How Octave Reports Errors -@cindex error messages -@cindex messages, error - -Octave reports two kinds of errors for invalid programs. - -A @dfn{parse error} occurs if Octave cannot understand something you -have typed. For example, if you misspell a keyword, - -@example -octave:13> functon y = f (x) y = x^2; endfunction -@end example - -@noindent -Octave will respond immediately with a message like this: - -@example -parse error: - - functon y = f (x) y = x^2; endfunction - ^ -@end example - -@noindent -For most parse errors, Octave uses a caret (@samp{^}) to mark the point -on the line where it was unable to make sense of your input. In this -case, Octave generated an error message because the keyword -@code{function} was misspelled. Instead of seeing @samp{function f}, -Octave saw two consecutive variable names, which is invalid in this -context. It marked the error at @code{y} because the first name by -itself was accepted as valid input. - -Another class of error message occurs at evaluation time. These -errors are called @dfn{run-time errors}, or sometimes -@dfn{evaluation errors} because they occur when your program is being -@dfn{run}, or @dfn{evaluated}. For example, if after correcting the -mistake in the previous function definition, you type - -@example -octave:13> f () -@end example - -@noindent -Octave will respond with - -@example -@group -error: `x' undefined near line 1 column 24 -error: evaluating expression near line 1, column 24 -error: evaluating assignment expression near line 1, column 22 -error: called from `f' -@end group -@end example - -This error message has several parts, and gives you quite a bit of -information to help you locate the source of the error. The messages -are generated from the point of the innermost error, and provide a -traceback of enclosing expressions and function calls. - -In the example above, the first line indicates that a variable named -@samp{x} was found to be undefined near line 1 and column 24 of some -function or expression. For errors occurring within functions, lines -are counted from the beginning of the file containing the function -definition. For errors occurring at the top level, the line number -indicates the input line number, which is usually displayed in the -prompt string. - -The second and third lines in the example indicate that the error -occurred within an assignment expression, and the last line of the error -message indicates that the error occurred within the function @code{f}. -If the function @code{f} had been called from another function, for -example, @code{g}, the list of errors would have ended with one more -line: - -@example -error: called from `g' -@end example - -These lists of function calls usually make it fairly easy to trace the -path your program took before the error occurred, and to correct the -error before trying again. - -@node Executable Octave Programs, Comments, Errors, Getting Started -@section Executable Octave Programs -@cindex executable scripts -@cindex scripts -@cindex self contained programs -@cindex program, self contained -@cindex @samp{#!} - -Once you have learned Octave, you may want to write self-contained -Octave scripts, using the @samp{#!} script mechanism. You can do this -on GNU systems and on many Unix systems @footnote{The @samp{#!} -mechanism works on Unix systems derived from Berkeley Unix, System V -Release 4, and some System V Release 3 systems.} - -For example, you could create a text file named @file{hello}, containing -the following lines: - -@example -@group -#! @var{octave-interpreter-name} -qf -# a sample Octave program -printf ("Hello, world!\n"); -@end group -@end example - -@noindent -(where @var{octave-interpreter-name} should be replaced with the full -file name for your Octave binary). After making this file executable -(with the @code{chmod} command), you can simply type: - -@example -hello -@end example - -@noindent -at the shell, and the system will arrange to run Octave as if you had -typed: - -@example -octave hello -@end example - -The line beginning with @samp{#!} lists the full file name of an -interpreter to be run, and an optional initial command line argument to -pass to that interpreter. The operating system then runs the -interpreter with the given argument and the full argument list of the -executed program. The first argument in the list is the full file name -of the Octave program. The rest of the argument list will either be -options to Octave, or data files, or both. The @samp{-qf} option is -usually specified in stand-alone Octave programs to prevent them from -printing the normal startup message, and to keep them from behaving -differently depending on the contents of a particular user's -@file{~/.octaverc} file. @xref{Invoking Octave}. Note that some -operating systems may place a limit on the number of characters that are -recognized after @samp{#!}. - -Self-contained Octave scripts are useful when you want to write a -program which users can invoke without knowing that the program is -written in the Octave language. - -If you invoke an executable Octave script with command line arguments, -the arguments are available in the built-in variable @code{argv}. -@xref{Command Line Options}. For example, the following program will -reproduce the command line that is used to execute it. - -@example -@group -#! /bin/octave -qf -printf ("%s", program_name); -for i = 1:nargin - printf (" %s", argv(i,:)); -endfor -printf ("\n"); -@end group -@end example - -@node Comments, , Executable Octave Programs, Getting Started -@section Comments in Octave Programs -@cindex @samp{#} -@cindex @samp{%} -@cindex comments -@cindex use of comments -@cindex documenting Octave programs -@cindex programs - -A @dfn{comment} is some text that is included in a program for the sake -of human readers, and that is not really part of the program. Comments -can explain what the program does, and how it works. Nearly all -programming languages have provisions for comments, because programs are -typically hard to understand without them. - -In the Octave language, a comment starts with either the sharp sign -character, @samp{#}, or the percent symbol @samp{%} and continues to the -end of the line. The Octave interpreter ignores the rest of a -line following a sharp sign or percent symbol. For example, we could -have put the following into the function @code{f}: - -@example -@group -function xdot = f (x, t) - -# usage: f (x, t) -# -# This function defines the right hand -# side functions for a set of nonlinear -# differential equations. - - r = 0.25; - @dots{} -endfunction -@end group -@end example - -The @code{help} command (@pxref{Getting Help}) is able to find the first -block of comments in a function (even those that are composed directly -on the command line). This means that users of Octave can use the same -commands to get help for built-in functions, and for functions that you -have defined. For example, after defining the function @code{f} above, -the command @kbd{help f} produces the output - -@example -@group - usage: f (x, t) - - This function defines the right hand - side functions for a set of nonlinear - differential equations. -@end group -@end example - -Although it is possible to put comment lines into keyboard-composed -throw-away Octave programs, it usually isn't very useful, because the -purpose of a comment is to help you or another person understand the -program at a later time. - diff --git a/doc/interpreter/basics.txi b/doc/interpreter/basics.txi new file mode 100644 --- /dev/null +++ b/doc/interpreter/basics.txi @@ -0,0 +1,1130 @@ +@c Copyright (C) 1996, 1997 John W. Eaton +@c This is part of the Octave manual. +@c For copying conditions, see the file gpl.texi. + +@node Getting Started, Data Types, Introduction, Top +@chapter Getting Started + +This chapter explains some of Octave's basic features, including how to +start an Octave session, get help at the command prompt, edit the +command line, and write Octave programs that can be executed as commands +from your shell. + +@menu +* Invoking Octave:: +* Quitting Octave:: +* Getting Help:: +* Command Line Editing:: +* Errors:: +* Executable Octave Programs:: +* Comments:: +@end menu + +@node Invoking Octave, Quitting Octave, Getting Started, Getting Started +@section Invoking Octave + +Normally, Octave is used interactively by running the program +@samp{octave} without any arguments. Once started, Octave reads +commands from the terminal until you tell it to exit. + +You can also specify the name of a file on the command line, and Octave +will read and execute the commands from the named file and then exit +when it is finished. + +You can further control how Octave starts by using the command-line +options described in the next section, and Octave itself can remind you +of the options available. Type @samp{octave --help} to display all +available options and briefly describe their use (@samp{octave -h} is a +shorter equivalent). + +@menu +* Command Line Options:: +* Startup Files:: +@end menu + +@node Command Line Options, Startup Files, Invoking Octave, Invoking Octave +@subsection Command Line Options +@cindex Octave command options +@cindex command options +@cindex options, Octave command + +Here is a complete list of all the command line options that Octave +accepts. + +@table @code +@item --debug +@itemx -d +@cindex @code{--debug} +@cindex @code{-d} +Enter parser debugging mode. Using this option will cause Octave's +parser to print a lot of information about the commands it reads, and is +probably only useful if you are actually trying to debug the parser. + +@item --echo-commands +@itemx -x +@cindex @code{--echo-commands} +@cindex @code{-x} +Echo commands as they are executed. + +@item --exec-path @var{path} +@cindex @code{--exec-path @var{path}} +Specify the path to search for programs to run. The value of @var{path} +specified on the command line will override any value of +@code{OCTAVE_EXEC_PATH} found in the environment, but not any commands +in the system or user startup files that set the built-in variable +@code{EXEC_PATH}. + +@item --help +@itemx -h +@itemx -? +@cindex @code{--help} +@cindex @code{-h} +@cindex @code{-?} +Print short help message and exit. + +@item --info-file @var{filename} +@cindex @code{--info-file @var{filename}} +Specify the name of the info file to use. The value of @var{filename} +specified on the command line will override any value of +@code{OCTAVE_INFO_FILE} found in the environment, but not any commands +in the system or user startup files that set the built-in variable +@code{INFO_FILE}. + +@item --info-program @var{program} +@cindex @code{--info-program @var{program}} +Specify the name of the info program to use. The value of @var{program} +specified on the command line will override any value of +@code{OCTAVE_INFO_PROGRAM} found in the environment, but not any +commands in the system or user startup files that set the built-in +variable @code{INFO_PROGRAM}. + +@item --interactive +@itemx -i +@cindex @code{--interactive} +@cindex @code{-i} +Force interactive behavior. This can be useful for running Octave via a +remote shell command or inside an Emacs shell buffer. For another way +to run Octave within Emacs, see @ref{Emacs}. + +@item --no-init-file +@cindex @code{--no-init-file} +Don't read the @file{~/.octaverc} or @file{.octaverc} files. + +@item --no-line-editing +@cindex @code{--no-line-editing} +Disable command-line editing. + +@item --no-site-file +@cindex @code{--no-site-file} +Don't read the site-wide @file{octaverc} file. + +@item --norc +@itemx -f +@cindex @code{--norc} +@cindex @code{-f} +Don't read any of the system or user initialization files at startup. +This is equivalent to using both of the options @code{--no-init-file} +and @code{--no-site-file}. + +@item --path @var{path} +@itemx -p @var{path} +@cindex @code{--path @var{path}} +@cindex @code{-p @var{path}} +Specify the path to search for function files. The value of @var{path} +specified on the command line will override any value of +@code{OCTAVE_PATH} found in the environment, but not any commands in the +system or user startup files that set the built-in variable @code{LOADPATH}. + +@item --silent +@itemx --quiet +@itemx -q +@cindex @code{--silent} +@cindex @code{--quiet} +@cindex @code{-q} +Don't print the usual greeting and version message at startup. + +@item --traditional +@itemx --braindead +@cindex @code{--traditional} +@cindex @code{--braindead} +Set initial values for user-preference variables to the following +values for compatibility with @sc{Matlab}. + +@example +PS1 = ">> " +PS2 = "" +beep_on_error = 1 +default_save_format = "mat-binary" +define_all_return_values = 1 +do_fortran_indexing = 1 +crash_dumps_octave_core = 0 +empty_list_elements_ok = 1 +implicit_str_to_num_ok = 1 +ok_to_lose_imaginary_part = 1 +page_screen_output = 0 +prefer_column_vectors = 0 +print_empty_dimensions = 0 +treat_neg_dim_as_zero = 1 +warn_function_name_clash = 0 +whitespace_in_literal_matrix = "traditional" +@end example + +@item --verbose +@itemx -V +@cindex @code{--verbose} +@cindex @code{-V} +Turn on verbose output. + +@item --version +@itemx -v +@cindex @code{--version} +@cindex @code{-v} +Print the program version number and exit. + +@item @var{file} +Execute commands from @var{file}. +@end table + +Octave also includes several built-in variables that contain information +about the command line, including the number of arguments and all of the +options. + +@defvr {Built-in Variable} argv +The command line arguments passed to Octave are available in this +variable. For example, if you invoked Octave using the command + +@example +octave --no-line-editing --silent +@end example + +@noindent +@code{argv} would be a list of strings with the elements +@code{--no-line-editing} and @code{--silent}. + +If you write an executable Octave script, @code{argv} will contain the +list of arguments passed to the script. @pxref{Executable Octave Programs}. +@end defvr + +@defvr {Built-in Variable} program_invocation_name +@defvrx {Built-in Variable} program_name +When Octave starts, the value of the built-in variable +@code{program_invocation_name} is automatically set to the name that was +typed at the shell prompt to run Octave, and the value of +@code{program_name} is automatically set to the final component of +@code{program_invocation_name}. For example, if you typed +@samp{@value{OCTAVEHOME}/bin/octave} to start Octave, +@code{program_invocation_name} would have the value +@code{"@value{OCTAVEHOME}/bin/octave"}, and @code{program_name} would +have the value @code{"octave"}. + +If executing a script from the command line (e.g., @code{octave foo.m}) +or using an executable Octave script, the program name is set to the +name of the script. @xref{Executable Octave Programs} for an example of +how to create an executable Octave script. +@end defvr + +Here is an example of using these variables to reproduce Octave's +command line. + +@example +printf ("%s", program_name); +for i = 1:nargin + printf (" %s", argv(i)); +endfor +printf ("\n"); +@end example + +@noindent +@xref{Index Expressions} for an explanation of how to properly index +arrays of strings and substrings in Octave, and @xref{Defining Functions} +for information about the variable @code{nargin}. + +@node Startup Files, , Command Line Options, Invoking Octave +@subsection Startup Files +@cindex initialization +@cindex startup + +When Octave starts, it looks for commands to execute from the following +files: + +@cindex startup files + +@table @code +@item @var{octave-home}/share/octave/site/m/startup/octaverc +Where @var{octave-home} is the directory in which all of Octave is +installed (the default is @file{@value{OCTAVEHOME}}). This file is +provided so that changes to the default Octave environment can be made +globally for all users at your site for all versions of Octave you have +installed. Some care should be taken when making changes to this file, +since all users of Octave at your site will be affected. + +@item @var{octave-home}/share/octave/@var{version}/m/startup/octaverc +Where @var{octave-home} is the directory in which all of Octave is +installed (the default is @file{@value{OCTAVEHOME}}), and @var{version} +is the version number of Octave. This file is provided so that changes +to the default Octave environment can be made globally for all users for +a particular version of Octave. Some care should be taken when making +changes to this file, since all users of Octave at your site will be +affected. + +@item ~/.octaverc +@cindex @code{~/.octaverc} +This file is normally used to make personal changes to the default +Octave environment. + +@item .octaverc +@cindex @code{.octaverc} +This file can be used to make changes to the default Octave environment +for a particular project. Octave searches for this file in the current +directory after it reads @file{~/.octaverc}. Any use of the @code{cd} +command in the @file{~/.octaverc} file will affect the directory that +Octave searches for the file @file{.octaverc}. + +If you start Octave in your home directory, commands from from the file +@file{~/.octaverc} will only be executed once. +@end table + +A message will be displayed as each of the startup files is read if you +invoke Octave with the @code{--verbose} option but without the +@code{--silent} option. + +Startup files may contain any valid Octave commands, including function +definitions. + +@node Quitting Octave, Getting Help, Invoking Octave, Getting Started +@section Quitting Octave +@cindex exiting octave +@cindex quitting octave + +@deftypefn {Built-in Function} {} exit (@var{status}) +@deftypefnx {Built-in Function} {} quit (@var{status}) +Exit the current Octave session. If the optional integer value +@var{status} is supplied, pass that value to the operating system as the +Octave's exit status. +@end deftypefn + +@deftypefn {Built-in Function} {} atexit (@var{fcn}) +Register function to be called when Octave exits. For example, + +@example +@group +function print_flops_at_exit () + printf ("\n%s\n", system ("fortune")); + fflush (stdout); +endfunction +atexit ("print_flops_at_exit"); +@end group +@end example + +@noindent +will print a message when Octave exits. +@end deftypefn + +@node Getting Help, Command Line Editing, Quitting Octave, Getting Started +@section Commands for Getting Help +@cindex on-line help +@cindex help, on-line + +The entire text of this manual is available from the Octave prompt +via the command @kbd{help -i}. In addition, the documentation for +individual user-written functions and variables is also available via +the @kbd{help} command. This section describes the commands used for +reading the manual and the documentation strings for user-supplied +functions and variables. @xref{Function Files}, for more information +about how to document the functions you write. + +@deffn {Command} help +Octave's @code{help} command can be used to print brief usage-style +messages, or to display information directly from an on-line version of +the printed manual, using the GNU Info browser. If invoked without any +arguments, @code{help} prints a list of all the available operators, +functions, and built-in variables. If the first argument is @code{-i}, +the @code{help} command searches the index of the on-line version of +this manual for the given topics. + +For example, the command @kbd{help help} prints a short message +describing the @code{help} command, and @kbd{help -i help} starts the +GNU Info browser at this node in the on-line version of the manual. + +Once the GNU Info browser is running, help for using it is available +using the command @kbd{C-h}. +@end deffn + +The help command can give you information about operators, but not the +comma and semicolons that are used as command separators. To get help +for those, you must type @kbd{help comma} or @kbd{help semicolon}. + +@defvr {Built-in Variable} INFO_FILE +The variable @code{INFO_FILE} names the location of the Octave info file. +The default value is @code{"@var{octave-home}/info/octave.info"}, where +@var{octave-home} is the directory where all of Octave is installed. +@end defvr + +@defvr {Built-in Variable} INFO_PROGRAM +The variable @code{INFO_PROGRAM} names the info program to run. Its +initial value is +@code{"@var{octave-home}/libexec/octave/@var{version}/exec/@var{arch}/info"}, +where @var{octave-home} is the directory where all of Octave is +installed, @var{version} is the Octave version number, and @var{arch} is +the machine type. The value of @code{INFO_PROGRAM} can be overridden by +the environment variable @code{OCTAVE_INFO_PROGRAM}, or the command line +argument @code{--info-program NAME}, or by setting the value of the +built-in variable @code{INFO_PROGRAM} in a startup script. +@end defvr + +@defvr {Built-in Variable} suppress_verbose_help_message +If the value of @code{suppress_verbose_help_message} is nonzero, Octave +will not add additional help information to the end of the output from +the @code{help} command and usage messages for built-in commands. +@end defvr + +@node Command Line Editing, Errors, Getting Help, Getting Started +@section Command Line Editing +@cindex command-line editing +@cindex editing the command line + +Octave uses the GNU readline library to provide an extensive set of +command-line editing and history features. Only the most common +features are described in this manual. Please see The GNU Readline +Library manual for more information. + +To insert printing characters (letters, digits, symbols, etc.), simply +type the character. Octave will insert the character at the cursor and +advance the cursor forward. + +Many of the command-line editing functions operate using control +characters. For example, the character @kbd{Control-a} moves the cursor +to the beginning of the line. To type @kbd{C-a}, hold down @key{CTRL} +and then press @key{a}. In the following sections, control characters +such as @kbd{Control-a} are written as @kbd{C-a}. + +Another set of command-line editing functions use Meta characters. On +some terminals, you type @kbd{M-u} by holding down @key{META} and +pressing @key{u}. If your terminal does not have a @key{META} key, you +can still type Meta charcters using two-character sequences starting +with @kbd{ESC}. Thus, to enter @kbd{M-u}, you could type +@key{ESC}@key{u}. The @kbd{ESC} character sequences are also allowed on +terminals with real Meta keys. In the following sections, Meta +characters such as @kbd{Meta-u} are written as @kbd{M-u}. + +@menu +* Cursor Motion:: +* Killing and Yanking:: +* Commands For Text:: +* Commands For Completion:: +* Commands For History:: +* Customizing the Prompt:: +* Diary and Echo Commands:: +@end menu + +@node Cursor Motion, Killing and Yanking, Command Line Editing, Command Line Editing +@subsection Cursor Motion + +The following commands allow you to position the cursor. + +@table @kbd +@item C-b +Move back one character. + +@item C-f +Move forward one character. + +@item @key{DEL} +Delete the character to the left of the cursor. + +@item C-d +Delete the character underneath the cursor. + +@item M-f +Move forward a word. + +@item M-b +Move backward a word. + +@item C-a +Move to the start of the line. + +@item C-e +Move to the end of the line. + +@item C-l +Clear the screen, reprinting the current line at the top. + +@item C-_ +@itemx C-/ +Undo the last thing that you did. You can undo all the way back to an +empty line. + +@item M-r +Undo all changes made to this line. This is like typing the `undo' +command enough times to get back to the beginning. +@end table + +The above table describes the most basic possible keystrokes that you need +in order to do editing of the input line. On most terminals, you can +also use the arrow keys in place of @kbd{C-f} and @kbd{C-b} to move +forward and backward. + +Notice how @kbd{C-f} moves forward a character, while @kbd{M-f} moves +forward a word. It is a loose convention that control keystrokes +operate on characters while meta keystrokes operate on words. + +There is also a function available so that you can clear the screen from +within Octave programs. + +@cindex clearing the screen + +@deftypefn {Built-in Function} {} clc () +@deftypefnx {Built-in Function} {} home () +Clear the terminal screen and move the cursor to the upper left corner. +@end deftypefn + +@node Killing and Yanking, Commands For Text, Cursor Motion, Command Line Editing +@subsection Killing and Yanking + +@dfn{Killing} text means to delete the text from the line, but to save +it away for later use, usually by @dfn{yanking} it back into the line. +If the description for a command says that it `kills' text, then you can +be sure that you can get the text back in a different (or the same) +place later. + +Here is the list of commands for killing text. + +@table @kbd +@item C-k +Kill the text from the current cursor position to the end of the line. + +@item M-d +Kill from the cursor to the end of the current word, or if between +words, to the end of the next word. + +@item M-@key{DEL} +Kill from the cursor to the start of the previous word, or if between +words, to the start of the previous word. + +@item C-w +Kill from the cursor to the previous whitespace. This is different than +@kbd{M-@key{DEL}} because the word boundaries differ. +@end table + +And, here is how to @dfn{yank} the text back into the line. Yanking +means to copy the most-recently-killed text from the kill buffer. + +@table @kbd +@item C-y +Yank the most recently killed text back into the buffer at the cursor. + +@item M-y +Rotate the kill-ring, and yank the new top. You can only do this if +the prior command is @kbd{C-y} or @kbd{M-y}. +@end table + +When you use a kill command, the text is saved in a @dfn{kill-ring}. +Any number of consecutive kills save all of the killed text together, so +that when you yank it back, you get it in one clean sweep. The kill +ring is not line specific; the text that you killed on a previously +typed line is available to be yanked back later, when you are typing +another line. + +@node Commands For Text, Commands For Completion, Killing and Yanking, Command Line Editing +@subsection Commands For Changing Text + +The following commands can be used for entering characters that would +otherwise have a special meaning (e.g., @kbd{TAB}, @kbd{C-q}, etc.), or +for quickly correcting typing mistakes. + +@table @kbd +@item C-q +@itemx C-v +Add the next character that you type to the line verbatim. This is +how to insert things like @kbd{C-q} for example. + +@item M-@key{TAB} +Insert a tab character. + +@item C-t +Drag the character before the cursor forward over the character at the +cursor, also moving the cursor forward. If the cursor is at the end of +the line, then transpose the two characters before it. + +@item M-t +Drag the word behind the cursor past the word in front of the cursor +moving the cursor over that word as well. + +@item M-u +Uppercase the characters following the cursor to the end of the current +(or following) word, moving the cursor to the end of the word. + +@item M-l +Lowecase the characters following the cursor to the end of the current +(or following) word, moving the cursor to the end of the word. + +@item M-c +Uppercase the character following the cursor (or the beginning of the +next word if the cursor is between words), moving the cursor to the end +of the word. +@end table + +@node Commands For Completion, Commands For History, Commands For Text, Command Line Editing +@subsection Letting Readline Type For You +@cindex command completion + +The following commands allow Octave to complete command and variable +names for you. + +@table @kbd +@item @key{TAB} +Attempt to do completion on the text before the cursor. Octave can +complete the names of commands and variables. + +@item M-? +List the possible completions of the text before the cursor. +@end table + +@defvr {Built-in Variable} completion_append_char +The value of @code{completion_append_char} is used as the character to +append to successful command-line completion attempts. The default +value is @code{" "} (a single space). +@end defvr + +@deftypefn {Built-in Function} {} completion_matches (@var{hint}) +Generate possible completions given @var{hint}. + +This function is provided for the benefit of programs like Emacs which +might be controlling Octave and handling user input. The current +command number is not incremented when this function is called. This is +a feature, not a bug. +@end deftypefn + +@node Commands For History, Customizing the Prompt, Commands For Completion, Command Line Editing +@subsection Commands For Manipulating The History +@cindex command history +@cindex input history +@cindex history of commands + +Octave normally keeps track of the commands you type so that you can +recall previous commands to edit or execute them again. When you exit +Octave, the most recent commands you have typed, up to the number +specified by the variable @code{history_size}, are saved in a file. +When Octave starts, it loads an initial list of commands from the file +named by the variable @code{history_file}. + +Here are the commands for simple browsing and searching the history +list. + +@table @kbd +@item @key{LFD} +@itemx @key{RET} +Accept the line regardless of where the cursor is. If this line is +non-empty, add it to the history list. If this line was a history +line, then restore the history line to its original state. + +@item C-p +Move `up' through the history list. + +@item C-n +Move `down' through the history list. + +@item M-< +Move to the first line in the history. + +@item M-> +Move to the end of the input history, i.e., the line you are entering! + +@item C-r +Search backward starting at the current line and moving `up' through +the history as necessary. This is an incremental search. + +@item C-s +Search forward starting at the current line and moving `down' through +the history as necessary. +@end table + +On most terminals, you can also use the arrow keys in place of @kbd{C-p} +and @kbd{C-n} to move through the history list. + +In addition to the keyboard commands for moving through the history +list, Octave provides three functions for viewing, editing, and +re-running chunks of commands from the history list. + +@deffn {Command} history options +If invoked with no arguments, @code{history} displays a list of commands +that you have executed. Valid options are: + +@table @code +@item -w @var{file} +Write the current history to the file @var{file}. If the name is +omitted, use the default history file (normally @file{~/.octave_hist}). + +@item -r @var{file} +Read the file @var{file}, replacing the current history list with its +contents. If the name is omitted, use the default history file +(normally @file{~/.octave_hist}). + +@item @var{N} +Only display the most recent @var{N} lines of history. + +@item -q +Don't number the displayed lines of history. This is useful for cutting +and pasting commands if you are using the X Window System. +@end table + +For example, to display the five most recent commands that you have +typed without displaying line numbers, use the command +@kbd{history -q 5}. +@end deffn + +@deffn {Command} edit_history options +If invoked with no arguments, @code{edit_history} allows you to edit the +history list using the editor named by the variable @code{EDITOR}. The +commands to be edited are first copied to a temporary file. When you +exit the editor, Octave executes the commands that remain in the file. +It is often more convenient to use @code{edit_history} to define functions +rather than attempting to enter them directly on the command line. +By default, the block of commands is executed as soon as you exit the +editor. To avoid executing any commands, simply delete all the lines +from the buffer before exiting the editor. + +The @code{edit_history} command takes two optional arguments specifying +the history numbers of first and last commands to edit. For example, +the command + +@example +edit_history 13 +@end example + +@noindent +extracts all the commands from the 13th through the last in the history +list. The command + +@example +edit_history 13 169 +@end example + +@noindent +only extracts commands 13 through 169. Specifying a larger number for +the first command than the last command reverses the list of commands +before placing them in the buffer to be edited. If both arguments are +omitted, the previous command in the history list is used. +@end deffn + +@deffn {Command} run_history +Similar to @code{edit_history}, except that the editor is not invoked, +and the commands are simply executed as they appear in the history list. +@end deffn + +@defvr {Built-in Variable} EDITOR +A string naming the editor to use with the @code{edit_history} command. +If the environment variable @code{EDITOR} is set when Octave starts, its +value is used as the default. Otherwise, @code{EDITOR} is set to +@code{"emacs"}. +@end defvr + +@defvr {Built-in Variable} history_file +This variable specifies the name of the file used to store command +history. The default value is @code{"~/.octave_hist"}, but may be +overridden by the environment variable @code{OCTAVE_HISTFILE}. +@end defvr + +@defvr {Built-in Variable} history_size +This variable specifies how many entries to store in the history file. +The default value is @code{1024}, but may be overridden by the +environment variable @code{OCTAVE_HISTSIZE}. +@end defvr + +@defvr {Built-in Variable} saving_history +If the value of @code{saving_history} is nonzero, command entered +on the command line are saved in the file specified by the variable +@code{history_file}. +@end defvr + +@node Customizing the Prompt, Diary and Echo Commands, Commands For History, Command Line Editing +@subsection Customizing the Prompt +@cindex prompt customization +@cindex customizing the prompt + +The following variables are available for customizing the appearance of +the command-line prompts. Octave allows the prompt to be customized by +inserting a number of backslash-escaped special characters that are +decoded as follows: + +@table @samp +@item \t +The time. + +@item \d +The date. + +@item \n +Begins a new line by printing the equivalent of a carriage return +followed by a line feed. + +@item \s +The name of the program (usually just @samp{octave}). + +@item \w +The current working directory. + +@item \W +The basename of the current working directory. + +@item \u +The username of the current user. + +@item \h +The hostname, up to the first `.'. + +@item \H +The hostname. + +@item \# +The command number of this command, counting from when Octave starts. + +@item \! +The history number of this command. This differs from @samp{\#} by the +number of commands in the history list when Octave starts. + +@item \$ +If the effective UID is 0, a @samp{#}, otherwise a @samp{$}. + +@item \nnn +The character whose character code in octal is @var{nnn}. + +@item \\ +A backslash. +@end table + +@defvr {Built-in Variable} PS1 +The primary prompt string. When executing interactively, Octave +displays the primary prompt @code{PS1} when it is ready to read a +command. + +The default value of @code{PS1} is @code{"\s:\#> "}. To change it, use a +command like + +@example +octave:13> PS1 = "\\u@@\\H> " +@end example + +@noindent +which will result in the prompt @samp{boris@@kremvax> } for the user +@samp{boris} logged in on the host @samp{kremvax.kgb.su}. Note that two +backslashes are required to enter a backslash into a string. +@xref{Strings}. +@end defvr + +@defvr {Built-in Variable} PS2 +The secondary prompt string, which is printed when Octave is +expecting additional input to complete a command. For example, when +defining a function over several lines, Octave will print the value of +@code{PS1} at the beginning of each line after the first. The default +value of @code{PS2} is @code{"> "}. +@end defvr + +@defvr {Built-in Variable} PS4 +If Octave is invoked with the @code{--echo-input} option, the value of +@code{PS4} is printed before each line of input that is echoed. The +default value of @code{PS4} is @code{"+ "}. @xref{Invoking Octave}, for +a description of @code{--echo-input}. +@end defvr + +@node Diary and Echo Commands, , Customizing the Prompt, Command Line Editing +@subsection Diary and Echo Commands +@cindex diary of commands and output +@cindex command and ouput logs +@cindex logging commands and output +@cindex echoing executing commands +@cindex command echoing + +Octave's diary feature allows you to keep a log of all or part of an +interactive session by recording the input you type and the output that +Octave produces in a separate file. + +@deffn {Command} diary options +Create a list of all commands @emph{and} the output they produce, mixed +together just as you see them on your terminal. Valid options are: + +@table @code +@item on +Start recording your session in a file called @file{diary} in your +current working directory. + +@item off +Stop recording your session in the diary file. + +@item @var{file} +Record your session in the file named @var{file}. +@end table + +Without any arguments, @code{diary} toggles the current diary state. +@end deffn + +Sometimes it is useful to see the commands in a function or script as +they are being evaluated. This can be especially helpful for debugging +some kinds of problems. + +@deffn {Command} echo options +Control whether commands are displayed as they are executed. Valid +options are: + +@table @code +@item on +Enable echoing of commands as they are executed in script files. + +@item off +Disable echoing of commands as they are executed in script files. + +@item on all +Enable echoing of commands as they are executed in script files and +functions. + +@item off all +Disable echoing of commands as they are executed in script files and +functions. +@end table + +@noindent +If invoked without any arguments, @code{echo} toggles the current echo +state. +@end deffn + +@defvr {Built-in Variable} echo_executing_commands +This variable may also be used to control the echo state. It may be +the sum of the following values: + +@table @asis +@item 1 +Echo commands read from script files. + +@item 2 +Echo commands from functions. + +@item 4 +Echo commands read from command line. +@end table + +More than one state can be active at once. For example, a value of 3 is +equivalent to the command @kbd{echo on all}. + +The value of @code{echo_executing_commands} is set by the @kbd{echo} +command and the command line option @code{--echo-input}. +@end defvr + +@node Errors, Executable Octave Programs, Command Line Editing, Getting Started +@section How Octave Reports Errors +@cindex error messages +@cindex messages, error + +Octave reports two kinds of errors for invalid programs. + +A @dfn{parse error} occurs if Octave cannot understand something you +have typed. For example, if you misspell a keyword, + +@example +octave:13> functon y = f (x) y = x^2; endfunction +@end example + +@noindent +Octave will respond immediately with a message like this: + +@example +parse error: + + functon y = f (x) y = x^2; endfunction + ^ +@end example + +@noindent +For most parse errors, Octave uses a caret (@samp{^}) to mark the point +on the line where it was unable to make sense of your input. In this +case, Octave generated an error message because the keyword +@code{function} was misspelled. Instead of seeing @samp{function f}, +Octave saw two consecutive variable names, which is invalid in this +context. It marked the error at @code{y} because the first name by +itself was accepted as valid input. + +Another class of error message occurs at evaluation time. These +errors are called @dfn{run-time errors}, or sometimes +@dfn{evaluation errors} because they occur when your program is being +@dfn{run}, or @dfn{evaluated}. For example, if after correcting the +mistake in the previous function definition, you type + +@example +octave:13> f () +@end example + +@noindent +Octave will respond with + +@example +@group +error: `x' undefined near line 1 column 24 +error: evaluating expression near line 1, column 24 +error: evaluating assignment expression near line 1, column 22 +error: called from `f' +@end group +@end example + +This error message has several parts, and gives you quite a bit of +information to help you locate the source of the error. The messages +are generated from the point of the innermost error, and provide a +traceback of enclosing expressions and function calls. + +In the example above, the first line indicates that a variable named +@samp{x} was found to be undefined near line 1 and column 24 of some +function or expression. For errors occurring within functions, lines +are counted from the beginning of the file containing the function +definition. For errors occurring at the top level, the line number +indicates the input line number, which is usually displayed in the +prompt string. + +The second and third lines in the example indicate that the error +occurred within an assignment expression, and the last line of the error +message indicates that the error occurred within the function @code{f}. +If the function @code{f} had been called from another function, for +example, @code{g}, the list of errors would have ended with one more +line: + +@example +error: called from `g' +@end example + +These lists of function calls usually make it fairly easy to trace the +path your program took before the error occurred, and to correct the +error before trying again. + +@node Executable Octave Programs, Comments, Errors, Getting Started +@section Executable Octave Programs +@cindex executable scripts +@cindex scripts +@cindex self contained programs +@cindex program, self contained +@cindex @samp{#!} + +Once you have learned Octave, you may want to write self-contained +Octave scripts, using the @samp{#!} script mechanism. You can do this +on GNU systems and on many Unix systems @footnote{The @samp{#!} +mechanism works on Unix systems derived from Berkeley Unix, System V +Release 4, and some System V Release 3 systems.} + +For example, you could create a text file named @file{hello}, containing +the following lines: + +@example +@group +#! @var{octave-interpreter-name} -qf +# a sample Octave program +printf ("Hello, world!\n"); +@end group +@end example + +@noindent +(where @var{octave-interpreter-name} should be replaced with the full +file name for your Octave binary). After making this file executable +(with the @code{chmod} command), you can simply type: + +@example +hello +@end example + +@noindent +at the shell, and the system will arrange to run Octave as if you had +typed: + +@example +octave hello +@end example + +The line beginning with @samp{#!} lists the full file name of an +interpreter to be run, and an optional initial command line argument to +pass to that interpreter. The operating system then runs the +interpreter with the given argument and the full argument list of the +executed program. The first argument in the list is the full file name +of the Octave program. The rest of the argument list will either be +options to Octave, or data files, or both. The @samp{-qf} option is +usually specified in stand-alone Octave programs to prevent them from +printing the normal startup message, and to keep them from behaving +differently depending on the contents of a particular user's +@file{~/.octaverc} file. @xref{Invoking Octave}. Note that some +operating systems may place a limit on the number of characters that are +recognized after @samp{#!}. + +Self-contained Octave scripts are useful when you want to write a +program which users can invoke without knowing that the program is +written in the Octave language. + +If you invoke an executable Octave script with command line arguments, +the arguments are available in the built-in variable @code{argv}. +@xref{Command Line Options}. For example, the following program will +reproduce the command line that is used to execute it. + +@example +@group +#! /bin/octave -qf +printf ("%s", program_name); +for i = 1:nargin + printf (" %s", argv(i,:)); +endfor +printf ("\n"); +@end group +@end example + +@node Comments, , Executable Octave Programs, Getting Started +@section Comments in Octave Programs +@cindex @samp{#} +@cindex @samp{%} +@cindex comments +@cindex use of comments +@cindex documenting Octave programs +@cindex programs + +A @dfn{comment} is some text that is included in a program for the sake +of human readers, and that is not really part of the program. Comments +can explain what the program does, and how it works. Nearly all +programming languages have provisions for comments, because programs are +typically hard to understand without them. + +In the Octave language, a comment starts with either the sharp sign +character, @samp{#}, or the percent symbol @samp{%} and continues to the +end of the line. The Octave interpreter ignores the rest of a +line following a sharp sign or percent symbol. For example, we could +have put the following into the function @code{f}: + +@example +@group +function xdot = f (x, t) + +# usage: f (x, t) +# +# This function defines the right hand +# side functions for a set of nonlinear +# differential equations. + + r = 0.25; + @dots{} +endfunction +@end group +@end example + +The @code{help} command (@pxref{Getting Help}) is able to find the first +block of comments in a function (even those that are composed directly +on the command line). This means that users of Octave can use the same +commands to get help for built-in functions, and for functions that you +have defined. For example, after defining the function @code{f} above, +the command @kbd{help f} produces the output + +@example +@group + usage: f (x, t) + + This function defines the right hand + side functions for a set of nonlinear + differential equations. +@end group +@end example + +Although it is possible to put comment lines into keyboard-composed +throw-away Octave programs, it usually isn't very useful, because the +purpose of a comment is to help you or another person understand the +program at a later time. + diff --git a/doc/interpreter/bugs.texi b/doc/interpreter/bugs.texi deleted file mode 100644 --- a/doc/interpreter/bugs.texi +++ /dev/null @@ -1,475 +0,0 @@ -@c Copyright (C) 1996, 1997 John W. Eaton -@c This is part of the Octave manual. -@c For copying conditions, see the file gpl.texi. - -@c The text of this file will eventually appear in the file BUGS -@c in the Octave distribution, as well as in the Octave manual. - -@ifclear BUGSONLY -@node Trouble, Installation, Tips, Top -@appendix Known Causes of Trouble -@end ifclear - -@ifset BUGSONLY -@include conf.texi - -This file documents known bugs in Octave and describes where and how to -report any bugs that you may find. - -Copyright (C) 1996, 1997 John W. Eaton. You may copy, distribute, and -modify it freely as long as you preserve this copyright notice and -permission notice. - -@node Trouble, , Trouble -@chapter Known Causes of Trouble with Octave -@end ifset - -@cindex bugs, known -@cindex installation trouble -@cindex known causes of trouble -@cindex troubleshooting - -This section describes known problems that affect users of Octave. Most -of these are not Octave bugs per se---if they were, we would fix them. -But the result for a user may be like the result of a bug. - -Some of these problems are due to bugs in other software, some are -missing features that are too much work to add, and some are places -where people's opinions differ as to what is best. - -@menu -* Actual Bugs:: Bugs we will fix later. -* Reporting Bugs:: -* Bug Criteria:: -* Bug Lists:: -* Bug Reporting:: -* Sending Patches:: -* Service:: -@end menu - -@node Actual Bugs, Reporting Bugs, Trouble, Trouble -@appendixsec Actual Bugs We Haven't Fixed Yet - -@itemize @bullet -@item -Output that comes directly from Fortran functions is not sent through -the pager and may appear out of sequence with other output that is sent -through the pager. One way to avoid this is to force pending output to -be flushed before calling a function that will produce output from -within Fortran functions. To do this, use the command - -@example -fflush (stdout) -@end example - -Another possible workaround is to use the command - -@example -page_screen_output = "false" -@end example - -@noindent -to turn the pager off. - -@item -If you get messages like - -@example -Input line too long -@end example - -when trying to plot many lines on one graph, you have probably generated -a plot command that is too larger for @code{gnuplot}'s fixed-length -buffer for commands. Splitting up the plot command doesn't help because -replot is implemented in gnuplot by simply appending the new plotting -commands to the old command line and then evaluating it again. - -You can demonstrate this `feature' by running gnuplot and doing -something like - -@example - plot sin (x), sin (x), sin (x), ... lots more ..., sin (x) -@end example - -@noindent -and then - -@example - replot sin (x), sin (x), sin (x), ... lots more ..., sin (x) -@end example - -@noindent -after repeating the replot command a few times, gnuplot will give you -an error. - -Also, it doesn't help to use backslashes to enter a plot command over -several lines, because the limit is on the overall command line -length, once the backslashed lines are all pasted together. - -Because of this, Octave tries to use as little of the command-line -length as possible by using the shortest possible abbreviations for -all the plot commands and options. Unfortunately, the length of the -temporary file names is probably what is taking up the most space on -the command line. - -You can buy a little bit of command line space by setting the -environment variable @code{TMPDIR} to be "." before starting Octave, or -you can increase the maximum command line length in gnuplot by changing -the following limits in the file plot.h in the gnuplot distribution and -recompiling gnuplot. - -@example -#define MAX_LINE_LEN 32768 /* originally 1024 */ -#define MAX_TOKENS 8192 /* originally 400 */ -@end example - -Of course, this doesn't really fix the problem, but it does make it -much less likely that you will run into trouble unless you are putting -a very large number of lines on a given plot. -@end itemize - -A list of ideas for future enhancements is distributed with Octave. See -the file @file{PROJECTS} in the top level directory in the source -distribution. - -@node Reporting Bugs, Bug Criteria, Actual Bugs, Trouble -@appendixsec Reporting Bugs -@cindex bugs -@cindex reporting bugs - -Your bug reports play an essential role in making Octave reliable. - -When you encounter a problem, the first thing to do is to see if it is -already known. @xref{Trouble}. If it isn't known, then you should -report the problem. - -Reporting a bug may help you by bringing a solution to your problem, or -it may not. In any case, the principal function of a bug report is -to help the entire community by making the next version of Octave work -better. Bug reports are your contribution to the maintenance of Octave. - -In order for a bug report to serve its purpose, you must include the -information that makes it possible to fix the bug. - -@findex bug_report - -If you have Octave working at all, the easiest way to prepare a complete -bug report is to use the Octave function @code{bug_report}. When you -execute this function, Octave will prompt you for a subject and then -invoke the editor on a file that already contains all the configuration -information. When you exit the editor, Octave will mail the bug report -for you. - -@menu -* Bug Criteria:: -* Where: Bug Lists. Where to send your bug report. -* Reporting: Bug Reporting. How to report a bug effectively. -* Patches: Sending Patches. How to send a patch for Octave. -@end menu - -@node Bug Criteria, Bug Lists, Reporting Bugs, Trouble -@appendixsec Have You Found a Bug? -@cindex bug criteria - -If you are not sure whether you have found a bug, here are some guidelines: - -@itemize @bullet -@cindex fatal signal -@cindex core dump -@item -If Octave gets a fatal signal, for any input whatever, that is -a bug. Reliable interpreters never crash. - -@cindex incorrect output -@cindex incorrect results -@cindex results, incorrect -@cindex answers, incorrect -@cindex erroneous results -@cindex wrong answers -@item -If Octave produces incorrect results, for any input whatever, -that is a bug. - -@cindex undefined behavior -@cindex undefined function value -@item -Some output may appear to be incorrect when it is in fact due to a -program whose behavior is undefined, which happened by chance to give -the desired results on another system. For example, the range operator -may produce different results because of differences in the way floating -point arithmetic is handled on various systems. - -@cindex erroneous messages -@cindex incorrect error messages -@cindex error messages, incorrect -@item -If Octave produces an error message for valid input, that is a bug. - -@cindex invalid input -@item -If Octave does not produce an error message for invalid input, that is -a bug. However, you should note that your idea of ``invalid input'' -might be my idea of ``an extension'' or ``support for traditional -practice''. - -@cindex improving Octave -@cindex suggestions -@item -If you are an experienced user of programs like Octave, your suggestions -for improvement are welcome in any case. -@end itemize - -@node Bug Lists, Bug Reporting, Bug Criteria, Trouble -@appendixsec Where to Report Bugs -@cindex bug report mailing lists -@cindex reporting bugs -@cindex bugs, reporting - -@findex bug_report - -If you have Octave working at all, the easiest way to prepare a complete -bug report is to use the Octave function @code{bug_report}. When you -execute this function, Octave will prompt you for a subject and then -invoke the editor on a file that already contains all the configuration -information. When you exit the editor, Octave will mail the bug report -for you. - -If for some reason you cannot use Octave's @code{bug_report} function, -send bug reports for Octave to @email{bug-octave@@bevo.che.wisc.edu}. - -@strong{Do not send bug reports to @samp{help-octave}}. Most users of -Octave do not want to receive bug reports. Those that do have asked to -be on the mailing list. - -As a last resort, send bug reports on paper to: - -@example -Octave Bugs c/o John W. Eaton -University of Wisconsin-Madison -Department of Chemical Engineering -1415 Engineering Drive -Madison, Wisconsin 53706 USA -@end example - -@node Bug Reporting, Sending Patches, Bug Lists, Trouble -@appendixsec How to Report Bugs -@cindex bugs, reporting - -Send bug reports for Octave to one of the addresses listed in -@ref{Bug Lists}. - -The fundamental principle of reporting bugs usefully is this: -@strong{report all the facts}. If you are not sure whether to state a -fact or leave it out, state it! - -Often people omit facts because they think they know what causes the -problem and they conclude that some details don't matter. Thus, you might -assume that the name of the variable you use in an example does not matter. -Well, probably it doesn't, but one cannot be sure. Perhaps the bug is a -stray memory reference which happens to fetch from the location where that -name is stored in memory; perhaps, if the name were different, the contents -of that location would fool the interpreter into doing the right thing -despite the bug. Play it safe and give a specific, complete example. - -Keep in mind that the purpose of a bug report is to enable someone to -fix the bug if it is not known. Always write your bug reports on -the assumption that the bug is not known. - -Sometimes people give a few sketchy facts and ask, ``Does this ring a -bell?'' This cannot help us fix a bug. It is better to send a complete -bug report to begin with. - -Try to make your bug report self-contained. If we have to ask you for -more information, it is best if you include all the previous information -in your response, as well as the information that was missing. - -To enable someone to investigate the bug, you should include all these -things: - -@itemize @bullet -@item -The version of Octave. You can get this by noting the version number -that is printed when Octave starts, or running it with the @samp{-v} -option. - -@item -A complete input file that will reproduce the bug. - -A single statement may not be enough of an example---the bug might -depend on other details that are missing from the single statement where -the error finally occurs. - -@item -The command arguments you gave Octave to execute that example -and observe the bug. To guarantee you won't omit something important, -list all the options. - -If we were to try to guess the arguments, we would probably guess wrong -and then we would not encounter the bug. - -@item -The type of machine you are using, and the operating system name and -version number. - -@item -The command-line arguments you gave to the @code{configure} command when -you installed the interpreter. - -@item -A complete list of any modifications you have made to the interpreter -source. - -Be precise about these changes---show a context diff for them. - -@item -Details of any other deviations from the standard procedure for installing -Octave. - -@cindex incorrect output -@cindex incorrect results -@cindex results, incorrect -@cindex answers, incorrect -@cindex erroneous results -@cindex wrong answers -@item -A description of what behavior you observe that you believe is -incorrect. For example, "The interpreter gets a fatal signal," or, "The -output produced at line 208 is incorrect." - -Of course, if the bug is that the interpreter gets a fatal signal, then -one can't miss it. But if the bug is incorrect output, we might not -notice unless it is glaringly wrong. - -Even if the problem you experience is a fatal signal, you should still -say so explicitly. Suppose something strange is going on, such as, your -copy of the interpreter is out of synch, or you have encountered a bug -in the C library on your system. Your copy might crash and the copy -here would not. If you said to expect a crash, then when the -interpreter here fails to crash, we would know that the bug was not -happening. If you don't say to expect a crash, then we would not know -whether the bug was happening. We would not be able to draw any -conclusion from our observations. - -Often the observed symptom is incorrect output when your program is run. -Unfortunately, this is not enough information unless the program is -short and simple. It is very helpful if you can include an explanation -of the expected output, and why the actual output is incorrect. - -@item -If you wish to suggest changes to the Octave source, send them as -context diffs. If you even discuss something in the Octave source, -refer to it by context, not by line number, because the line numbers in -the development sources probably won't match those in your sources. -@end itemize - -Here are some things that are not necessary: - -@itemize @bullet -@cindex bugs, investigating -@item -A description of the envelope of the bug. - -Often people who encounter a bug spend a lot of time investigating which -changes to the input file will make the bug go away and which changes -will not affect it. Such information is usually not necessary to enable -us to fix bugs in Octave, but if you can find a simpler example to -report @emph{instead} of the original one, that is a convenience. -Errors in the output will be easier to spot, running under the debugger -will take less time, etc. Most Octave bugs involve just one function, so -the most straightforward way to simplify an example is to delete all the -function definitions except the one in which the bug occurs. - -However, simplification is not vital; if you don't want to do -this, report the bug anyway and send the entire test case you -used. - -@item -A patch for the bug. Patches can be helpful, but if you find a bug, you -should report it, even if you cannot send a fix for the problem. -@end itemize - -@node Sending Patches, Service, Bug Reporting, Trouble -@appendixsec Sending Patches for Octave -@cindex improving Octave -@cindex diffs, submitting -@cindex patches, submitting -@cindex submitting diffs -@cindex submitting patches - -If you would like to write bug fixes or improvements for Octave, that is -very helpful. When you send your changes, please follow these -guidelines to avoid causing extra work for us in studying the patches. - -If you don't follow these guidelines, your information might still be -useful, but using it will take extra work. Maintaining Octave is a lot -of work in the best of circumstances, and we can't keep up unless you do -your best to help. - -@itemize @bullet -@item -Send an explanation with your changes of what problem they fix or what -improvement they bring about. For a bug fix, just include a copy of the -bug report, and explain why the change fixes the bug. - -@item -Always include a proper bug report for the problem you think you have -fixed. We need to convince ourselves that the change is right before -installing it. Even if it is right, we might have trouble judging it if -we don't have a way to reproduce the problem. - -@item -Include all the comments that are appropriate to help people reading the -source in the future understand why this change was needed. - -@item -Don't mix together changes made for different reasons. -Send them @emph{individually}. - -If you make two changes for separate reasons, then we might not want to -install them both. We might want to install just one. - -@item -Use @samp{diff -c} to make your diffs. Diffs without context are hard -for us to install reliably. More than that, they make it hard for us to -study the diffs to decide whether we want to install them. Unidiff -format is better than contextless diffs, but not as easy to read as -@samp{-c} format. - -If you have GNU diff, use @samp{diff -cp}, which shows the name of the -function that each change occurs in. - -@item -Write the change log entries for your changes. - -Read the @file{ChangeLog} file to see what sorts of information to put -in, and to learn the style that we use. The purpose of the change log -is to show people where to find what was changed. So you need to be -specific about what functions you changed; in large functions, it's -often helpful to indicate where within the function the change was made. - -On the other hand, once you have shown people where to find the change, -you need not explain its purpose. Thus, if you add a new function, all -you need to say about it is that it is new. If you feel that the -purpose needs explaining, it probably does---but the explanation will be -much more useful if you put it in comments in the code. - -If you would like your name to appear in the header line for who made -the change, send us the header line. -@end itemize - -@node Service, , Sending Patches, Trouble -@appendixsec How To Get Help with Octave -@cindex help, where to find - -The mailing list @email{help-octave@@bevo.che.wisc.edu} exists for the -discussion of matters related to using and installing Octave. If would -like to join the discussion, please send a short note to -@email{help-octave@strong{-request}@@bevo.che.wisc.edu}. - -@strong{Please do not} send requests to be added or removed from the -mailing list, or other administrative trivia to the list itself. - -If you think you have found a bug in the installation procedure, -however, you should send a complete bug report for the problem to -@email{bug-octave@@bevo.che.wisc.edu}. @xref{Bug Reporting} for -information that will help you to submit a useful report. diff --git a/doc/interpreter/bugs.txi b/doc/interpreter/bugs.txi new file mode 100644 --- /dev/null +++ b/doc/interpreter/bugs.txi @@ -0,0 +1,475 @@ +@c Copyright (C) 1996, 1997 John W. Eaton +@c This is part of the Octave manual. +@c For copying conditions, see the file gpl.texi. + +@c The text of this file will eventually appear in the file BUGS +@c in the Octave distribution, as well as in the Octave manual. + +@ifclear BUGSONLY +@node Trouble, Installation, Tips, Top +@appendix Known Causes of Trouble +@end ifclear + +@ifset BUGSONLY +@include conf.texi + +This file documents known bugs in Octave and describes where and how to +report any bugs that you may find. + +Copyright (C) 1996, 1997 John W. Eaton. You may copy, distribute, and +modify it freely as long as you preserve this copyright notice and +permission notice. + +@node Trouble, , Trouble +@chapter Known Causes of Trouble with Octave +@end ifset + +@cindex bugs, known +@cindex installation trouble +@cindex known causes of trouble +@cindex troubleshooting + +This section describes known problems that affect users of Octave. Most +of these are not Octave bugs per se---if they were, we would fix them. +But the result for a user may be like the result of a bug. + +Some of these problems are due to bugs in other software, some are +missing features that are too much work to add, and some are places +where people's opinions differ as to what is best. + +@menu +* Actual Bugs:: Bugs we will fix later. +* Reporting Bugs:: +* Bug Criteria:: +* Bug Lists:: +* Bug Reporting:: +* Sending Patches:: +* Service:: +@end menu + +@node Actual Bugs, Reporting Bugs, Trouble, Trouble +@appendixsec Actual Bugs We Haven't Fixed Yet + +@itemize @bullet +@item +Output that comes directly from Fortran functions is not sent through +the pager and may appear out of sequence with other output that is sent +through the pager. One way to avoid this is to force pending output to +be flushed before calling a function that will produce output from +within Fortran functions. To do this, use the command + +@example +fflush (stdout) +@end example + +Another possible workaround is to use the command + +@example +page_screen_output = "false" +@end example + +@noindent +to turn the pager off. + +@item +If you get messages like + +@example +Input line too long +@end example + +when trying to plot many lines on one graph, you have probably generated +a plot command that is too larger for @code{gnuplot}'s fixed-length +buffer for commands. Splitting up the plot command doesn't help because +replot is implemented in gnuplot by simply appending the new plotting +commands to the old command line and then evaluating it again. + +You can demonstrate this `feature' by running gnuplot and doing +something like + +@example + plot sin (x), sin (x), sin (x), ... lots more ..., sin (x) +@end example + +@noindent +and then + +@example + replot sin (x), sin (x), sin (x), ... lots more ..., sin (x) +@end example + +@noindent +after repeating the replot command a few times, gnuplot will give you +an error. + +Also, it doesn't help to use backslashes to enter a plot command over +several lines, because the limit is on the overall command line +length, once the backslashed lines are all pasted together. + +Because of this, Octave tries to use as little of the command-line +length as possible by using the shortest possible abbreviations for +all the plot commands and options. Unfortunately, the length of the +temporary file names is probably what is taking up the most space on +the command line. + +You can buy a little bit of command line space by setting the +environment variable @code{TMPDIR} to be "." before starting Octave, or +you can increase the maximum command line length in gnuplot by changing +the following limits in the file plot.h in the gnuplot distribution and +recompiling gnuplot. + +@example +#define MAX_LINE_LEN 32768 /* originally 1024 */ +#define MAX_TOKENS 8192 /* originally 400 */ +@end example + +Of course, this doesn't really fix the problem, but it does make it +much less likely that you will run into trouble unless you are putting +a very large number of lines on a given plot. +@end itemize + +A list of ideas for future enhancements is distributed with Octave. See +the file @file{PROJECTS} in the top level directory in the source +distribution. + +@node Reporting Bugs, Bug Criteria, Actual Bugs, Trouble +@appendixsec Reporting Bugs +@cindex bugs +@cindex reporting bugs + +Your bug reports play an essential role in making Octave reliable. + +When you encounter a problem, the first thing to do is to see if it is +already known. @xref{Trouble}. If it isn't known, then you should +report the problem. + +Reporting a bug may help you by bringing a solution to your problem, or +it may not. In any case, the principal function of a bug report is +to help the entire community by making the next version of Octave work +better. Bug reports are your contribution to the maintenance of Octave. + +In order for a bug report to serve its purpose, you must include the +information that makes it possible to fix the bug. + +@findex bug_report + +If you have Octave working at all, the easiest way to prepare a complete +bug report is to use the Octave function @code{bug_report}. When you +execute this function, Octave will prompt you for a subject and then +invoke the editor on a file that already contains all the configuration +information. When you exit the editor, Octave will mail the bug report +for you. + +@menu +* Bug Criteria:: +* Where: Bug Lists. Where to send your bug report. +* Reporting: Bug Reporting. How to report a bug effectively. +* Patches: Sending Patches. How to send a patch for Octave. +@end menu + +@node Bug Criteria, Bug Lists, Reporting Bugs, Trouble +@appendixsec Have You Found a Bug? +@cindex bug criteria + +If you are not sure whether you have found a bug, here are some guidelines: + +@itemize @bullet +@cindex fatal signal +@cindex core dump +@item +If Octave gets a fatal signal, for any input whatever, that is +a bug. Reliable interpreters never crash. + +@cindex incorrect output +@cindex incorrect results +@cindex results, incorrect +@cindex answers, incorrect +@cindex erroneous results +@cindex wrong answers +@item +If Octave produces incorrect results, for any input whatever, +that is a bug. + +@cindex undefined behavior +@cindex undefined function value +@item +Some output may appear to be incorrect when it is in fact due to a +program whose behavior is undefined, which happened by chance to give +the desired results on another system. For example, the range operator +may produce different results because of differences in the way floating +point arithmetic is handled on various systems. + +@cindex erroneous messages +@cindex incorrect error messages +@cindex error messages, incorrect +@item +If Octave produces an error message for valid input, that is a bug. + +@cindex invalid input +@item +If Octave does not produce an error message for invalid input, that is +a bug. However, you should note that your idea of ``invalid input'' +might be my idea of ``an extension'' or ``support for traditional +practice''. + +@cindex improving Octave +@cindex suggestions +@item +If you are an experienced user of programs like Octave, your suggestions +for improvement are welcome in any case. +@end itemize + +@node Bug Lists, Bug Reporting, Bug Criteria, Trouble +@appendixsec Where to Report Bugs +@cindex bug report mailing lists +@cindex reporting bugs +@cindex bugs, reporting + +@findex bug_report + +If you have Octave working at all, the easiest way to prepare a complete +bug report is to use the Octave function @code{bug_report}. When you +execute this function, Octave will prompt you for a subject and then +invoke the editor on a file that already contains all the configuration +information. When you exit the editor, Octave will mail the bug report +for you. + +If for some reason you cannot use Octave's @code{bug_report} function, +send bug reports for Octave to @email{bug-octave@@bevo.che.wisc.edu}. + +@strong{Do not send bug reports to @samp{help-octave}}. Most users of +Octave do not want to receive bug reports. Those that do have asked to +be on the mailing list. + +As a last resort, send bug reports on paper to: + +@example +Octave Bugs c/o John W. Eaton +University of Wisconsin-Madison +Department of Chemical Engineering +1415 Engineering Drive +Madison, Wisconsin 53706 USA +@end example + +@node Bug Reporting, Sending Patches, Bug Lists, Trouble +@appendixsec How to Report Bugs +@cindex bugs, reporting + +Send bug reports for Octave to one of the addresses listed in +@ref{Bug Lists}. + +The fundamental principle of reporting bugs usefully is this: +@strong{report all the facts}. If you are not sure whether to state a +fact or leave it out, state it! + +Often people omit facts because they think they know what causes the +problem and they conclude that some details don't matter. Thus, you might +assume that the name of the variable you use in an example does not matter. +Well, probably it doesn't, but one cannot be sure. Perhaps the bug is a +stray memory reference which happens to fetch from the location where that +name is stored in memory; perhaps, if the name were different, the contents +of that location would fool the interpreter into doing the right thing +despite the bug. Play it safe and give a specific, complete example. + +Keep in mind that the purpose of a bug report is to enable someone to +fix the bug if it is not known. Always write your bug reports on +the assumption that the bug is not known. + +Sometimes people give a few sketchy facts and ask, ``Does this ring a +bell?'' This cannot help us fix a bug. It is better to send a complete +bug report to begin with. + +Try to make your bug report self-contained. If we have to ask you for +more information, it is best if you include all the previous information +in your response, as well as the information that was missing. + +To enable someone to investigate the bug, you should include all these +things: + +@itemize @bullet +@item +The version of Octave. You can get this by noting the version number +that is printed when Octave starts, or running it with the @samp{-v} +option. + +@item +A complete input file that will reproduce the bug. + +A single statement may not be enough of an example---the bug might +depend on other details that are missing from the single statement where +the error finally occurs. + +@item +The command arguments you gave Octave to execute that example +and observe the bug. To guarantee you won't omit something important, +list all the options. + +If we were to try to guess the arguments, we would probably guess wrong +and then we would not encounter the bug. + +@item +The type of machine you are using, and the operating system name and +version number. + +@item +The command-line arguments you gave to the @code{configure} command when +you installed the interpreter. + +@item +A complete list of any modifications you have made to the interpreter +source. + +Be precise about these changes---show a context diff for them. + +@item +Details of any other deviations from the standard procedure for installing +Octave. + +@cindex incorrect output +@cindex incorrect results +@cindex results, incorrect +@cindex answers, incorrect +@cindex erroneous results +@cindex wrong answers +@item +A description of what behavior you observe that you believe is +incorrect. For example, "The interpreter gets a fatal signal," or, "The +output produced at line 208 is incorrect." + +Of course, if the bug is that the interpreter gets a fatal signal, then +one can't miss it. But if the bug is incorrect output, we might not +notice unless it is glaringly wrong. + +Even if the problem you experience is a fatal signal, you should still +say so explicitly. Suppose something strange is going on, such as, your +copy of the interpreter is out of synch, or you have encountered a bug +in the C library on your system. Your copy might crash and the copy +here would not. If you said to expect a crash, then when the +interpreter here fails to crash, we would know that the bug was not +happening. If you don't say to expect a crash, then we would not know +whether the bug was happening. We would not be able to draw any +conclusion from our observations. + +Often the observed symptom is incorrect output when your program is run. +Unfortunately, this is not enough information unless the program is +short and simple. It is very helpful if you can include an explanation +of the expected output, and why the actual output is incorrect. + +@item +If you wish to suggest changes to the Octave source, send them as +context diffs. If you even discuss something in the Octave source, +refer to it by context, not by line number, because the line numbers in +the development sources probably won't match those in your sources. +@end itemize + +Here are some things that are not necessary: + +@itemize @bullet +@cindex bugs, investigating +@item +A description of the envelope of the bug. + +Often people who encounter a bug spend a lot of time investigating which +changes to the input file will make the bug go away and which changes +will not affect it. Such information is usually not necessary to enable +us to fix bugs in Octave, but if you can find a simpler example to +report @emph{instead} of the original one, that is a convenience. +Errors in the output will be easier to spot, running under the debugger +will take less time, etc. Most Octave bugs involve just one function, so +the most straightforward way to simplify an example is to delete all the +function definitions except the one in which the bug occurs. + +However, simplification is not vital; if you don't want to do +this, report the bug anyway and send the entire test case you +used. + +@item +A patch for the bug. Patches can be helpful, but if you find a bug, you +should report it, even if you cannot send a fix for the problem. +@end itemize + +@node Sending Patches, Service, Bug Reporting, Trouble +@appendixsec Sending Patches for Octave +@cindex improving Octave +@cindex diffs, submitting +@cindex patches, submitting +@cindex submitting diffs +@cindex submitting patches + +If you would like to write bug fixes or improvements for Octave, that is +very helpful. When you send your changes, please follow these +guidelines to avoid causing extra work for us in studying the patches. + +If you don't follow these guidelines, your information might still be +useful, but using it will take extra work. Maintaining Octave is a lot +of work in the best of circumstances, and we can't keep up unless you do +your best to help. + +@itemize @bullet +@item +Send an explanation with your changes of what problem they fix or what +improvement they bring about. For a bug fix, just include a copy of the +bug report, and explain why the change fixes the bug. + +@item +Always include a proper bug report for the problem you think you have +fixed. We need to convince ourselves that the change is right before +installing it. Even if it is right, we might have trouble judging it if +we don't have a way to reproduce the problem. + +@item +Include all the comments that are appropriate to help people reading the +source in the future understand why this change was needed. + +@item +Don't mix together changes made for different reasons. +Send them @emph{individually}. + +If you make two changes for separate reasons, then we might not want to +install them both. We might want to install just one. + +@item +Use @samp{diff -c} to make your diffs. Diffs without context are hard +for us to install reliably. More than that, they make it hard for us to +study the diffs to decide whether we want to install them. Unidiff +format is better than contextless diffs, but not as easy to read as +@samp{-c} format. + +If you have GNU diff, use @samp{diff -cp}, which shows the name of the +function that each change occurs in. + +@item +Write the change log entries for your changes. + +Read the @file{ChangeLog} file to see what sorts of information to put +in, and to learn the style that we use. The purpose of the change log +is to show people where to find what was changed. So you need to be +specific about what functions you changed; in large functions, it's +often helpful to indicate where within the function the change was made. + +On the other hand, once you have shown people where to find the change, +you need not explain its purpose. Thus, if you add a new function, all +you need to say about it is that it is new. If you feel that the +purpose needs explaining, it probably does---but the explanation will be +much more useful if you put it in comments in the code. + +If you would like your name to appear in the header line for who made +the change, send us the header line. +@end itemize + +@node Service, , Sending Patches, Trouble +@appendixsec How To Get Help with Octave +@cindex help, where to find + +The mailing list @email{help-octave@@bevo.che.wisc.edu} exists for the +discussion of matters related to using and installing Octave. If would +like to join the discussion, please send a short note to +@email{help-octave@strong{-request}@@bevo.che.wisc.edu}. + +@strong{Please do not} send requests to be added or removed from the +mailing list, or other administrative trivia to the list itself. + +If you think you have found a bug in the installation procedure, +however, you should send a complete bug report for the problem to +@email{bug-octave@@bevo.che.wisc.edu}. @xref{Bug Reporting} for +information that will help you to submit a useful report. diff --git a/doc/interpreter/control.texi b/doc/interpreter/control.texi deleted file mode 100644 --- a/doc/interpreter/control.texi +++ /dev/null @@ -1,3571 +0,0 @@ -@c Copyright (C) 1996, 1997 John W. Eaton -@c This is part of the Octave manual. -@c For copying conditions, see the file gpl.texi. - -@node Control Theory, Signal Processing, Polynomial Manipulations, Top -@chapter Control Theory - -The Octave Control Systems Toolbox (OCST) was initially developed -by Dr.@: A. Scottedward Hodel -@email{a.s.hodel@@eng.auburn.edu} with the assistance -of his students -@itemize @bullet -@item R. Bruce Tenison @email{btenison@@dibbs.net}, -@item David C. Clem, -@item John E. Ingram @email{John.Ingram@@sea.siemans.com}, and -@item Kristi McGowan. -@end itemize -This development was supported in part by NASA's Marshall Space Flight -Center as part of an in-house CACSD environment. Additional important -contributions were made by Dr. Kai Mueller @email{mueller@@ifr.ing.tu-bs.de} -and Jose Daniel Munoz Frias (@code{place.m}). - -An on-line menu-driven tutorial is available via @ref{DEMOcontrol}; -beginning OCST users should start with this program. - -@menu -* OCST demonstration/tutorial:DEMOcontrol. -* System Data Structure:sysstruct. -* System Construction and Interface Functions:sysinterface. -* System display functions:sysdisp. -* Block Diagram Manipulations:blockdiag. -* Numerical Functions:numerical. -* System Analysis-Properties:sysprop. -* System Analysis-Time Domain:systime. -* System Analysis-Frequency Domain:sysfreq. -* Controller Design:cacsd. -* Miscellaneous Functions:misc. -@end menu - -@node DEMOcontrol, sysstruct, Control Theory, Control Theory -@unnumberedsec OCST demo program -@deftypefn {Function File } { } DEMOcontrol -Octave Control Systems Toolbox demo/tutorial program. The demo -allows the user to select among several categories of OCST function: -@example -@group -octave:1> DEMOcontrol - O C T A V E C O N T R O L S Y S T E M S T O O L B O X -Octave Controls System Toolbox Demo - - [ 1] System representation - [ 2] Block diagram manipulations - [ 3] Frequency response functions - [ 4] State space analysis functions - [ 5] Root locus functions - [ 6] LQG/H2/Hinfinity functions - [ 7] End -@end group -@end example -Command examples are interactively run for users to observe the use -of OCST functions. -@end deftypefn - -@node sysstruct, sysinterface, DEMOcontrol, Control Theory -@section System Data Structure -@menu -* Demo program:sysrepdemo. -* Variables common to all OCST system formats:sysstructvars. -* tf format variables:sysstructtf. -* zp format variables:sysstructzp. -* ss format variables:sysstructss. -@end menu -The OCST stores all dynamic systems in -a single data structure format that can represent continuous systems, -discrete-systems, and mixed (hybrid) systems in state-space form, and -can also represent purely continuous/discrete systems in either -transfer function or pole-zero form. In order to -provide more flexibility in treatment of discrete/hybrid systems, the -OCST also keeps a record of which system outputs are sampled. - -Octave structures are accessed with a syntax much like that used -by the C programming language. For consistency in -use of the data structure used in the OCST, it is recommended that -the system structure access m-files be used (@xref{sysinterface}). -Some elements of the data structure are absent depending on the internal -system representation(s) used. More than one system representation -can be used for SISO systems; the OCST m-files ensure that all representations -used are consistent with one another. - -@node sysrepdemo, sysstructvars, sysstruct, sysstruct -@unnumberedsec System representation demo program -@deftypefn {Function File } {} sysrepdemo -Tutorial for the use of the system data structure functions. -@end deftypefn - -@node sysstructvars, sysstructtf, sysrepdemo, sysstruct -@subsection Variables common to all OCST system formats - -The data structure elements (and variable types) common to all system -representations are listed below; examples of the initialization -and use of the system data structures are given in subsequent sections and -in the online demo @code{DEMOcontrol}. -@table @var -@item n,nz -The respective number of continuous and discrete states -in the system (scalar) - -@item inname, outname -list of name(s) of the system input, output signal(s). (list of strings) - -@item sys - System status vector. (vector) - -This vector indicates both what - representation was used to initialize the system data structure - (called the primary system type) and which other representations - are currently up-to-date with the primary system type (@xref{sysupdate}). - -@table @var - -@item sys(0) -primary system type - - =0 for tf form (initialized with @code{tf2sys} or @code{fir2sys}) - - =1 for zp form (initialized with @code{zp2sys}) - - =2 for ss form (initialized with @code{ss2sys}) - -@item sys(1:3) - boolean flags to indicate whether tf, zp, or ss, respectively, - are ``up to date" (whether it is safe to use the variables - associated with these representations). -These flags are changed when calls are made to the @code{sysupdate} command. -@end table - -@item tsam - Discrete time sampling period (nonnegative scalar). - @var{tsam} is set to 0 for continuous time systems. - -@item yd - Discrete-time output list (vector) - - indicates which outputs are discrete time (i.e., - produced by D/A converters) and which are continuous time. - yd(ii) = 0 if output ii is continuous, = 1 if discrete. -@end table - -The remaining variables of the system data structure are only present -if the corresponding entry of the @code{sys} vector is true (=1). - -@node sysstructtf, sysstructzp, sysstructvars, sysstruct -@subsection @code{tf} format variables - -@table @var - -@item num - numerator coefficients (vector) - -@item den - denominator coefficients (vector) - -@end table - -@node sysstructzp, sysstructss, sysstructtf, sysstruct -@subsection @code{zp} format variables -@table @var -@item zer - system zeros (vector) - -@item pol - system poles (vector) - -@item k - leading coefficient (scalar) - -@end table - -@node sysstructss, , sysstructzp, sysstruct -@subsection @code{ss} format variables -@table @var -@item a,b,c,d -The usual state-space matrices. If a system has both - continuous and discrete states, they are sorted so that - continuous states come first, then discrete states - -@strong{Note} some functions (e.g., @code{bode}, @code{hinfsyn}) -will not accept systems with both discrete and continuous states/outputs - -@item stname -names of system states (list of strings) - -@end table - -@node sysinterface, sysdisp, sysstruct, Control Theory -@section System Construction and Interface Functions - -Construction and manipulations of the OCST system data structure -(@xref{sysstruct}) requires attention to many details in order -to ensure that data structure contents remain consistent. Users -are strongly encouraged to use the system interface functions -in this section. Functions for the formatted display in of system -data structures are given in @ref{sysdisp}. - -@menu -* Finite impulse response system interface functions:fir2sys. -* sys2fir:: -* State space system interface functions:ss2sys. -* sys2ss:: -* Transfer function system interface functions:tf2sys. -* sys2tf:: -* Zero-pole system interface functions:zp2sys. -* sys2zp:: -* Data structure access functions:structaccess. -* Data structure internal functions:structintern -@end menu - -@node fir2sys,sys2fir,sysinterface,sysinterface -@subsection Finite impulse response system interface functions - -@deftypefn {Function File } { @var{sys} =} fir2sys ( @var{num}@{, @var{tsam}, @var{inname}, @var{outname} @} ) - construct a system data structure from FIR description - -@strong{Inputs:} -@table @var -@item num - vector of coefficients @math{[c_0 c_1 ... c_n]} -of the SISO FIR transfer function -@ifinfo - -C(z) = c0 + c1*z^@{-1@} + c2*z^@{-2@} + ... + znz^@{-n@} - -@end ifinfo -@iftex -@tex -$$C(z) = c0 + c1*z^{-1} + c2*z^{-2} + ... + znz^{-n}$$ -@end tex -@end iftex - -@item tsam - sampling time (default: 1) - -@item inname -name of input signal; may be a string or a list with a single entry. - -@item outname - name of output signal; may be a string or a list with a single entry. -@end table - -@strong{Outputs} - @var{sys} (system data structure) - -@strong{Example} -@example -octave:1> sys = fir2sys([1 -1 2 4],0.342,"A/D input","filter output"); -octave:2> sysout(sys) -Input(s) - 1: A/D input - -Output(s): - 1: filter output (discrete) - -Sampling interval: 0.342 -transfer function form: -1*z^3 - 1*z^2 + 2*z^1 + 4 -------------------------- -1*z^3 + 0*z^2 + 0*z^1 + 0 -@end example -@end deftypefn - -@node sys2fir,ss2sys,fir2sys, sysinterface -@deftypefn {Function File } {[@var{c}, @var{tsam}, @var{input}, @var{output}] =} sys2fir (@var{sys}) - -Extract FIR data from system data structure; see @ref{fir2sys} for -parameter descriptions. - -@end deftypefn - - -@node ss2sys, sys2ss, sys2fir, sysinterface -@subsection State space system interface functions -@deftypefn {Function File } { @var{sys} =} ss2sys (@var{a},@var{b},@var{c}@{,@var{d}, @var{tsam}, @var{n}, @var{nz}, @var{stname}, @var{inname}, @var{outname}, @var{outlist}@}) - Create system structure from state-space data. May be continous, - discrete, or mixed (sampeld-data) - -@strong{Inputs} -@table @var -@item a, b, c, d - usual state space matrices. - - default: @var{d} = zero matrix - -@item tsam - sampling rate. Default: @math{tsam = 0} (continuous system) - -@item n, nz - number of continuous, discrete states in the system - - default: -@table @var -@item tsam = 0 -@math{n = @code{rows}(@var{a})}, @math{nz = 0} - -@item tsam > 0 -@math{ n = 0}, @math{nz = @code{rows}(@var{a})} - - see below for system partitioning - -@end table - -@item stname - list of strings of state signal names - - default (@var{stname}=[] on input): @code{x_n} for continuous states, - @code{xd_n} for discrete states - -@item inname - list of strings of input signal names - - default (@var{inname} = [] on input): @code{u_n} - -@item outname - list of strings of input signal names - - default (@var{outname} = [] on input): @code{y_n} - -@item outlist - - list of indices of outputs y that are sampled - - default: -@table @var -@item tsam = 0 -@math{outlist = []} -@item tsam > 0 -@math{outlist = 1:@code{rows}(@var{c})} -@end table - -Unlike states, discrete/continous outputs may appear in any order. - -@strong{Note} @code{sys2ss} returns a vector @var{yd} where -@var{yd}(@var{outlist}) = 1; all other entries of @var{yd} are 0. - -@end table - -@strong{Outputs} -@var{outsys} = system data structure - -@strong{System partitioning} - - Suppose for simplicity that outlist specified - that the first several outputs were continuous and the remaining outputs - were discrete. Then the system is partitioned as -@example -@group -x = [ xc ] (n x 1) - [ xd ] (nz x 1 discrete states) -a = [ acc acd ] b = [ bc ] - [ adc add ] [ bd ] -c = [ ccc ccd ] d = [ dc ] - [ cdc cdd ] [ dd ] - - (cdc = c(outlist,1:n), etc.) -@end group -@end example -with dynamic equations: -@ifinfo -@math{ d/dt xc(t) = acc*xc(t) + acd*xd(k*tsam) + bc*u(t)} - -@math{ xd((k+1)*tsam) = adc*xc(k*tsam) + add*xd(k*tsam) + bd*u(k*tsam)} - -@math{ yc(t) = ccc*xc(t) + ccd*xd(k*tsam) + dc*u(t)} - -@math{ yd(k*tsam) = cdc*xc(k*tsam) + cdd*xd(k*tsam) + dd*u(k*tsam)} -@end ifinfo -@iftex -@tex -$$\eqalign{ -{d \over dt} x_c(t) - & = a_{cc} x_c(t) + a_{cd} x_d(k*t_{sam}) + bc*u(t) \cr -x_d((k+1)*t_{sam}) - & = a_{dc} x_c(k t_{sam}) + a_{dd} x_d(k t_{sam}) + b_d u(k t_{sam}) \cr -y_c(t) - & = c_{cc} x_c(t) + c_{cd} x_d(k t_{sam}) + d_c u(t) \cr -y_d(k t_{sam}) - & = c_{dc} x_c(k t_{sam}) + c_{dd} x_d(k t_{sam}) + d_d u(k t_{sam}) -}$$ -@end tex -@end iftex - -@strong{Signal partitions} -@example -@group - | continuous | discrete | ----------------------------------------------------- -states | stname(1:n,:) | stname((n+1):(n+nz),:) | ----------------------------------------------------- -outputs | outname(cout,:) | outname(outlist,:) | ----------------------------------------------------- -@end group -@end example -where @math{cout} is the list of in 1:@code{rows}(@var{p}) -that are not contained in outlist. (Discrete/continuous outputs -may be entered in any order desired by the user.) - -@strong{Example} -@example -octave:1> a = [1 2 3; 4 5 6; 7 8 10]; -octave:2> b = [0 0 ; 0 1 ; 1 0]; -octave:3> c = eye(3); -octave:4> sys = ss2sys(a,b,c,[],0,3,0,list("volts","amps","joules")); -octave:5> sysout(sys); -Input(s) - 1: u_1 - 2: u_2 - -Output(s): - 1: y_1 - 2: y_2 - 3: y_3 - -state-space form: -3 continuous states, 0 discrete states -State(s): - 1: volts - 2: amps - 3: joules - -A matrix: 3 x 3 - 1 2 3 - 4 5 6 - 7 8 10 -B matrix: 3 x 2 - 0 0 - 0 1 - 1 0 -C matrix: 3 x 3 - 1 0 0 - 0 1 0 - 0 0 1 -D matrix: 3 x 3 - 0 0 - 0 0 - 0 0 -@end example -Notice that the @var{D} matrix is constructed by default to the -correct dimensions. Default input and output signals names were assigned -since none were given. - -@end deftypefn - -@node sys2ss,tf2sys,ss2sys,sysinterface -@deftypefn {Function File } {[@var{a},@var{b},@var{c},@var{d},@var{tsam},@var{n},@var{nz},@var{stname},@var{inname},@var{outname},@var{yd}] =} sys2ss (@var{sys}) -Extract state space representation from system data structure. - -@strong{Inputs} -@var{sys} system data structure (@xref{sysstruct}) - -@strong{Outputs} -@table @var -@item a,b,c,d - state space matrices for sys - -@item tsam - sampling time of sys (0 if continuous) - -@item n, nz - number of continuous, discrete states (discrete states come - last in state vector @var{x}) - -@item stname, inname, outname - signal names (lists of strings); names of states, - inputs, and outputs, respectively - -@item yd - binary vector; @var{yd}(@var{ii}) is 1 if output @var{y}(@var{ii})$ - is discrete (sampled); otherwise @var{yd}(@var{ii}) 0. - -@end table - -@strong{Example} -@example -octave:1> sys=tf2sys([1 2],[3 4 5]); -octave:2> [a,b,c,d] = sys2ss(sys) -a = - 0.00000 1.00000 - -1.66667 -1.33333 -b = - 0 - 1 -c = 0.66667 0.33333 -d = 0 -@end example -@end deftypefn - -@node tf2sys,sys2tf,sys2ss,sysinterface -@subsection Transfer function system interface functions -@deftypefn {Function File } { @var{sys} = } tf2sys( @var{num}, @var{den} @{, @var{tsam}, @var{inname}, @var{outname} @}) - build system data structure from transfer function format data - -@strong{Inputs} -@table @var -@item num, den - coefficients of numerator/denominator polynomials -@item tsam - sampling interval. default: 0 (continuous time) -@item inname, outname - input/output signal names; may be a string or list with a single string -entry. -@end table - -@strong{Outputs} - @var{sys} = system data structure - -@strong{Example} -@example -octave:1> sys=tf2sys([2 1],[1 2 1],0.1); -octave:2> sysout(sys) -Input(s) - 1: u_1 -Output(s): - 1: y_1 (discrete) -Sampling interval: 0.1 -transfer function form: -2*z^1 + 1 ------------------ -1*z^2 + 2*z^1 + 1 -@end example -@end deftypefn - -@node sys2tf,zp2sys,tf2sys,sysinterface -@deftypefn {Function File } {[@var{num},@var{den},@var{tsam},@var{inname},@var{outname}] =} sys2tf (@var{sys}) -Extract transfer function data from a system data structure - -See @ref{tf2sys} for parameter descriptions. - -@strong{Example} -@example -octave:1> sys=ss2sys([1 -2; -1.1,-2.1],[0;1],[1 1]); -octave:2> [num,den] = sys2tf(sys) -num = 1.0000 -3.0000 -den = 1.0000 1.1000 -4.3000 -@end example -@end deftypefn - -@node zp2sys,sys2zp,sys2tf,sysinterface -@subsection Zero-pole system interface functions - -@deftypefn {Function File } { @var{sys} =} zp2sys (@var{zer},@var{pol},@var{k}@{,@var{tsam},@var{inname},@var{outname}@}) - Create system data structure from zero-pole data - -@strong{Inputs} -@table @var -@item zer - vector of system zeros -@item pol - vector of system poles -@item k - scalar leading coefficient -@item tsam - sampling period. default: 0 (continuous system) -@item inname, outname - input/output signal names (lists of strings) -@end table - -@strong{Outputs} - sys: system data structure - -@strong{Example} -@example -octave:1> sys=zp2sys([1 -1],[-2 -2 0],1); -octave:2> sysout(sys) -Input(s) - 1: u_1 -Output(s): - 1: y_1 -zero-pole form: -1 (s - 1) (s + 1) ------------------ -s (s + 2) (s + 2) -@end example -@end deftypefn - -@node sys2zp, structaccess, zp2sys, sysinterface -@deftypefn {Function File } {[@var{zer}, @var{pol}, @var{k}, @var{tsam}, @var{inname}, @var{outname}] =} sys2zp (@var{sys}) -Extract zero/pole/leading coefficient information from a system data -structure - -See @ref{zp2sys} for parameter descriptions. - -@strong{Example} -@example -octave:1> sys=ss2sys([1 -2; -1.1,-2.1],[0;1],[1 1]); -octave:2> [zer,pol,k] = sys2zp(sys) -zer = 3.0000 -pol = - -2.6953 - 1.5953 -k = 1 -@end example -@end deftypefn - -@node structaccess, structintern, sys2zp, sysinterface -@subsection Data structure access functions - -@menu -* syschnames:: -* syschtsam:: -* sysdimensions:: -* sysgetsignals:: -* sysgettsam:: -* sysgettype:: -* syssetsignals:: -* sysupdate:: -@end menu - -@node syschnames, syschtsam, structaccess, structaccess -@deftypefn {Function File } {@var{retsys} =} syschnames (@var{sys}, @var{opt}, @var{list}, @var{names}) -Superseded by @code{syssetsignals} - -@end deftypefn - -@node syschtsam, sysdimensions, syschnames, structaccess -@deftypefn {Function File } { retsys =} syschtsam ( sys,tsam ) -This function changes the sampling time (tsam) of the system. Exits with -an error if sys is purely continuous time. -@end deftypefn - -@node sysdimensions, sysgetsignals, syschtsam, structaccess -@deftypefn {Function File } { [@var{n}, @var{nz}, @var{m}, @var{p},@var{yd}] =} sysdimensions (@var{sys}@{, @var{opt}@}) - return the number of states, inputs, and/or outputs in the system @var{sys}. - -@strong{Inputs} -@table @var -@item sys - system data structure - -@item opt -String indicating which dimensions are desired. Values: -@table @code -@item "all" -(default) return all parameters as specified under Outputs below. - -@item "cst" -return @var{n}= number of continuous states - -@item "dst" -return @var{n}= number of discrete states - -@item "in" -return @var{n}= number of inputs - -@item "out" -return @var{n}= number of outputs -@end table -@end table - -@strong{Outputs} -@table @var -@item n - number of continuous states (or individual requested dimension as specified -by @var{opt}). -@item nz - number of discrete states -@item m - number of system inputs -@item p - number of system outputs -@item yd - binary vector; @var{yd}(@var{ii}) is nonzero if output @var{ii} is -discrete. -@math{yd(ii) = 0} if output @var{ii} is continous -@end table - -@end deftypefn - -@node sysgetsignals, sysgettsam, sysdimensions, structaccess -@deftypefn {Function File } {[@var{stname}, @var{inname}, @var{outname}, @var{yd}] =} sysgetsignals (@var{sys}) -@deftypefnx{Function File } { @var{siglist} =} sysgetsignals (@var{sys},@var{sigid}) -@deftypefnx{Function File } { @var{signame} =} sysgetsignals (@var{sys},@var{sigid},@var{signum}@{, @var{strflg}@}) - Get signal names from a system - -@strong{Inputs} -@table @var -@item sys - system data structure for the state space system - -@item sigid -signal id. String. Must be one of -@table @code -@item "in" -input signals -@item "out" -output signals -@item "st" -stage signals -@item "yd" -value of logical vector @var{yd} -@end table - -@item signum -Index of signal (or indices of signals if signum is a vector) - -@item strflg -flag to return a string instead of a list; Values: -@table @code -@item 0 -(default) return a list (even if signum is a scalar) - -@item 1 -return a string. Exits with an error if signum is not a scalar. -@end table - -@end table - -@strong{Outputs} -@table @bullet -@item If @var{sigid} is not specified -@table @var -@item stname, inname, outname - signal names (lists of strings); names of states, - inputs, and outputs, respectively -@item yd - binary vector; @var{yd}(@var{ii}) is nonzero if output @var{ii} is -discrete. -@end table - -@item If @var{sigid} is specified but @var{signum} is not specified, then -@table @code -@item sigid="in" -@var{siglist} is set to the list of input names - -@item sigid="out" -@var{siglist} is set to the list of output names - -@item sigid="st" -@var{siglist} is set to the list of state names - -stage signals -@item sigid="yd" -@var{siglist} is set to logical vector indicating discrete outputs; -@var{siglist(ii) = 0} indicates that output @var{ii} is continuous -(unsampled), otherwise it is discrete. - -@end table - -@item if the first three input arguments are specified, then @var{signame} is -a list of the specified signal names (@var{sigid} is @code{"in"}, -@code{"out"}, or @code{"st"}), or else the logical flag -indicating whether output(s) @var{signum} is(are) discrete (@var{sigval}=1) -or continuous (@var{sigval}=0). -@end table - -@strong{Examples} (From @code{sysrepdemo}) -@example -octave> sys=ss2sys(rand(4),rand(4,2),rand(3,4)); -octave> [Ast,Ain,Aout,Ayd] = sysgetsignals(sys) i # get all signal names -Ast = -( - [1] = x_1 - [2] = x_2 - [3] = x_3 - [4] = x_4 -) -Ain = -( - [1] = u_1 - [2] = u_2 -) -Aout = -( - [1] = y_1 - [2] = y_2 - [3] = y_3 -) -Ayd = - - 0 0 0 -octave> Ain = sysgetsignals(sys,"in") # get only input signal names -Ain = -( - [1] = u_1 - [2] = u_2 -) -octave> Aout = sysgetsignals(sys,"out",2) # get name of output 2 (in list) -Aout = -( - [1] = y_2 -) -octave> Aout = sysgetsignals(sys,"out",2,1) # get name of output 2 (as string) -Aout = y_2 -@end example - -@end deftypefn - -@node sysgettsam, sysgettype, sysgetsignals, structaccess -@deftypefn {Function File } { Tsam =} sysgettsam ( sys ) - return the sampling time of the system -@end deftypefn - -@node sysgettype, syssetsignals, sysgettsam, structaccess -@deftypefn {Function File } { @var{systype} =} sysgettype ( @var{sys} ) - return the initial system type of the system - -@strong{Inputs} - @var{sys}: system data structure - -@strong{Outputs} - @var{systype}: string indicating how the structure was initially - constructed: - values: @code{"ss"}, @code{"zp"}, or @code{"tf"} - -@strong{Note} FIR initialized systems return @code{systype="tf"}. - - -@end deftypefn - -@node syssetsignals, sysupdate, sysgettype, structaccess -@deftypefn {Function File } {@var{retsys} =} syssetsignals (@var{sys}, @var{opt}, @var{names}@{, @var{sig_idx}@}) - change the names of selected inputs, outputs and states. -@strong{Inputs} -@table @var -@item sys - system data structure - -@item opt -change default name (output) - -@table @code -@item "out" - change selected output names -@item "in" - change selected input names -@item "st" - change selected state names -@item "yd" - change selected outputs from discrete to continuous or - from continuous to discrete. -@end table - -@item names -@table @code -@item opt = "out", "in", or "st" - string or string array containing desired signal names or values. -@item opt = "yd" -To desired output continuous/discrete flag. -Set name to 0 for continuous, or 1 for discrete. -@end table -@item list - vector of indices of outputs, yd, inputs, or - states whose respective names should be changed. - - Default: replace entire list of names/entire yd vector. -@end table -@strong{Outputs} - @var{retsys=sys} with appropriate signal names changed - (or yd values, where appropriate) - - -@strong{Example} -@example -octave:1> sys=ss2sys([1 2; 3 4],[5;6],[7 8]); -octave:2> sys = syssetsignals(sys,"st",str2mat("Posx","Velx")); -octave:3> sysout(sys) -Input(s) - 1: u_1 -Output(s): - 1: y_1 -state-space form: -2 continuous states, 0 discrete states -State(s): - 1: Posx - 2: Velx -A matrix: 2 x 2 - 1 2 - 3 4 -B matrix: 2 x 1 - 5 - 6 -C matrix: 1 x 2 - 7 8 -D matrix: 1 x 1 -0 -@end example - -@end deftypefn - -@node sysupdate, , syssetsignals, structaccess -@deftypefn {Function File } { @var{sys} =} sysupdate ( @var{sys}, @var{opt} ) - Update the internal representation of a system. - -@strong{Inputs} -@table @var -@item sys: -system data structure -@item opt - string: -@table @code -@item "tf" -update transfer function form -@item "zp" -update zero-pole form -@item "ss" -update state space form -@item "all" -all of the above -@end table -@end table - -@strong{Outputs} -@var{retsys}: contains union of data in sys and requested data. -If requested data in sys is already up to date then retsys=sys. - -Conversion to @code{tf} or @code{zp} exits with an error if the system is - mixed continuous/digital. -@end deftypefn - -@node structintern, , structaccess, sysinterface -@subsection Data structure internal functions -@deftypefn {Function File } { } syschnamesl - used internally in syschnames -@end deftypefn - -@deftypefn {Function File } { @var{ioname} =} sysdefioname (@var{n},@var{str} @{,@var{m}@}) -return default input or output names given @var{n}, @var{str}, @var{m}. - @var{n} is the final value, @var{str} is the string prefix, and @var{m} -is start value - - used internally, minimal argument checking - -@strong{Example} @code{ioname = sysdefioname(5,"u",3)} -returns the list: -@example -ioname = -( - [1] = u_3 - [2] = u_4 - [3] = u_5 -) -@end example -@end deftypefn - -@deftypefn {Function File } { @var{stname} =} sysdefstname (@var{n}, @var{nz}) - return default state names given @var{n}, @var{nz} - - used internally, minimal argument checking -@end deftypefn - -@deftypefn {Function File } { @var{vec} = } tf2sysl (@var{vec}) - used internally in @ref{tf2sys}. - strip leading zero coefficients to get the true polynomial length -@end deftypefn - -@node sysdisp, blockdiag, sysinterface, Control Theory -@section System display functions - -@deftypefn {Function File } { } sysout ( @var{sys}@{, @var{opt}@}) - print out a system data structure in desired format -@table @var -@item sys - system data structure -@item opt -Display option -@table @code -@item [] - primary system form (default); see @ref{sysgettype}. -@item "ss" - state space form -@item "tf" - transfer function form -@item "zp" - zero-pole form -@item "all" - all of the above -@end table -@end table -@end deftypefn - -@deftypefn {Function File } { @var{y} =} polyout ( @var{c}@{, @var{x}@}) -write formatted polynomial -@example - c(x) = c(1) * x^n + ... + c(n) x + c(n+1) -@end example - to string @var{y} or to the screen (if @var{y} is omitted) - @var{x} defaults to the string @code{"s"} -@end deftypefn - -@deftypefn {Function File } { } tfout (@var{num}, @var{denom}@{, @var{x}@}) - print formatted transfer function @math{n(s)/d(s) } to the screen - @var{x} defaults to the string @code{"s"} -@end deftypefn - -@deftypefn {Function File } { } zpout (@var{zer}, @var{pol}, @var{k}@{, @var{x}@}) - print formatted zero-pole form to the screen. -@var{x} defaults to the string @code{"s"} -@end deftypefn - -@deftypefn {Function File } { } outlist (@var{lmat}@{, @var{tabchar}, @var{yd}, @var{ilist} @}) - Prints an enumerated list of strings. - internal use only; minimal argument checking performed - -@strong{Inputs} -@table @var -@item lmat - list of strings -@item tabchar - tab character (default: none) -@item yd - indices of strings to append with the string "(discrete)" - (used by @var{sysout}; minimal checking of this argument) - @math{yd = [] } indicates all outputs are continuous -@item ilist -index numbers to print with names. - -default: @code{1:rows(lmat)} -@end table - -@strong{Outputs} - prints the list to the screen, numbering each string in order. - -@end deftypefn - -@node blockdiag, numerical, sysdisp, Control Theory -@section Block Diagram Manipulations - -@xref{systime} - -Unless otherwise noted, all parameters (input,output) are -system data structures. -@menu -* buildssic:: -* jet707:: -* ord2:: -* parallel:: -* sysadd:: -* sysappend:: -* sysconnect:: -* syscont:: -* syscont_disc:: -* sysdisc:: -* sysdup:: -* sysgroup:: -* sysgroupn:: -* sysmult:: -* sysprune:: -* sysreorder:: -* sysscale:: -* syssub:: -@end menu - -@deftypefn {Function File } { outputs =} bddemo ( inputs ) - Octave Controls toolbox demo: Block Diagram Manipulations demo -@end deftypefn - -@node buildssic, jet707, blockdiag, blockdiag -@deftypefn {Function File } {[@var{sys}] =} buildssic(@var{Clst}, @var{Ulst}, @var{Olst}, @var{Ilst}, @var{s1}, @var{s2}, @var{s3}, @var{s4}, @var{s5}, @var{s6}, @var{s7}, @var{s8}) - -Contributed by Kai Mueller. - - Form an arbitrary complex (open or closed loop) system in - state-space form from several systems. "@code{buildssic}" can - easily (despite it's cryptic syntax) integrate transfer functions - from a complex block diagram into a single system with one call. - This function is especially useful for building open loop - interconnections for H_infinity and H2 designs or for closing - loops with these controllers. - - Although this function is general purpose, the use of "@code{sysgroup}" - "@code{sysmult}", "@code{sysconnect}" and the like is recommended for standard - operations since they can handle mixed discrete and continuous - systems and also the names of inputs, outputs, and states. - - The parameters consist of 4 lists that describe the connections - outputs and inputs and up to 8 systems s1-s8. - Format of the lists: -@table @var -@item Clst -connection list, describes the input signal of -each system. The maximum number of rows of Clst is -equal to the sum of all inputs of s1-s8. - -Example: -@code{[1 2 -1; 2 1 0]} ==> new input 1 is old inpout 1 -+ output 2 - output 1, new input 2 is old input 2 -+ output 1. The order of rows is arbitrary. - -@item Ulst - if not empty the old inputs in vector Ulst will - be appended to the outputs. You need this if you - want to "pull out" the input of a system. Elements - are input numbers of s1-s8. - -@item Olst - output list, specifiy the outputs of the resulting - systems. Elements are output numbers of s1-s8. - The numbers are alowed to be negative and may - appear in any order. An empty matrix means - all outputs. - -@item Ilst - input list, specifiy the inputs of the resulting - systems. Elements are input numbers of s1-s8. - The numbers are alowed to be negative and may - appear in any order. An empty matrix means - all inputs. -@end table - - Example: Very simple closed loop system. -@example -@group -w e +-----+ u +-----+ - --->o--*-->| K |--*-->| G |--*---> y - ^ | +-----+ | +-----+ | - - | | | | - | | +----------------> u - | | | - | +-------------------------|---> e - | | - +----------------------------+ -@end group -@end example - -The closed loop system GW can be optained by -@example -GW = buildssic([1 2; 2 -1], [2], [1 2 3], [2], G, K); -@end example -@table @var -@item Clst -(1. row) connect input 1 (G) with output 2 (K). -(2. row) connect input 2 (K) with neg. output 1 (G). -@item Ulst -append input of (2) K to the number of outputs. -@item Olst -Outputs are output of 1 (G), 2 (K) and appended output 3 (from Ulst). -@item Ilst -the only input is 2 (K). -@end table - -Here is a real example: -@example -@group - +----+ - -------------------->| W1 |---> v1 -z | +----+ -----|-------------+ || GW || => min. - | | vz infty - | +---+ v +----+ - *--->| G |--->O--*-->| W2 |---> v2 - | +---+ | +----+ - | | - | v - u y -@end group -@end example - -The closed loop system GW from [z; u]' to [v1; v2; y]' can be -obtained by (all SISO systems): -@example -GW = buildssic([1 4;2 4;3 1],[3],[2 3 5],[3 4],G,W1,W2,One); -@end example -where "One" is a unity gain (auxillary) function with order 0. -(e.g. @code{One = ugain(1);}) -@end deftypefn - -@node jet707, ord2, buildssic, blockdiag -@deftypefn {Function File } { @var{outsys} =} jet707 ( ) - Creates linearized state space model of a Boeing 707-321 aircraft - at v=80m/s. (M = 0.26, Ga0 = -3 deg, alpha0 = 4 deg, kappa = 50 deg) - System inputs: (1) thrust and (2) elevator angle - System outputs: (1) airspeed and (2) pitch angle - Ref: R. Brockhaus: Flugregelung (Flight Control), Springer, 1994 - - see also: ord2 - -Contributed by Kai Mueller -@end deftypefn - -@node ord2, parallel, jet707, blockdiag -@deftypefn {Function File } { @var{outsys} =} ord2 (@var{nfreq}, @var{damp}@{[, @var{gain}@}) - Creates a continuous 2nd order system with parameters: -@strong{Inputs} -@table @var -@item nfreq: natural frequency [Hz]. (not in rad/s) -@item damp: damping coefficient -@item gain: dc-gain - This is steady state value only for damp > 0. - gain is assumed to be 1.0 if ommitted. -@end table -@strong{Outputs} -@var{outsys} - system data structure has representation with @math{w = 2 * pi * nfreq}: -@example - / \ - | / -2w*damp -w \ / w \ | -G = | | |, | |, [ 0 gain ], 0 | - | \ w 0 / \ 0 / | - \ / -@end example -@strong{See also} @code{jet707} (MIMO example, Boeing 707-321 aircraft model) -@end deftypefn - -@node parallel, sysadd, ord2, blockdiag -@deftypefn {Function File } { @var{sysp} =} parallel(@var{Asys}, @var{Bsys}) -Forms the parallel connection of two systems. -@example - ____________________ - | ________ | -u ----->|----> | Asys |--->|----> y1 - | | -------- | - | | ________ | - |--->|----> | Bsys |--->|----> y2 - | -------- | - -------------------- - Ksys -@end example -@end deftypefn - -@node sysadd, sysappend, parallel, blockdiag -@deftypefn {Function File } { @var{sys} =} sysadd ( @var{Gsys},@var{Hsys}) -returns @var{sys} = @var{Gsys} + @var{Hsys}. -@itemize @bullet -@item Exits with -an error if @var{Gsys} and @var{Hsys} are not compatibly dimensioned. -@item Prints a warning message is system states have identical names; - duplicate names are given a suffix to make them unique. -@item @var{sys} input/output names are taken from @var{Gsys}. -@end itemize -@example -@group - ________ - ----| Gsys |--- -u | ---------- +| ------ (_)----> y - | ________ +| - ----| Hsys |--- - -------- -@end group -@end example -@end deftypefn - -@node sysappend, sysconnect, sysadd, blockdiag -@deftypefn {Function File } {@var{retsys} =} sysappend (@var{sys},@var{b}@{, @var{c}, @var{d}, @var{outname}, @var{inname}, @var{yd}@}) -appends new inputs and/or outputs to a system - -@strong{Inputs} -@table @var -@item sys -system data structure - -@item b -matrix to be appended to sys "B" matrix (empty if none) - -@item c -matrix to be appended to sys "C" matrix (empty if none) - -@item d -revised sys d matrix (can be passed as [] if the revised d is all zeros) - -@item outname -list of names for new outputs - -@item inname -list of names for new inputs - -@item yd -binary vector; @math{yd(ii)=0} indicates a continuous output; -@math{yd(ii)=1} indicates a discrete output. -@end table - -@strong{Outputs} @var{sys} -@example -@group - sys.b := [sys.b , b] - sys.c := [sys.c ] - [ c ] - sys.d := [sys.d | D12 ] - [D21 | D22 ] -@end group -@end example -where @var{D12}, @var{D21}, and @var{D22} are the appropriate dimensioned -blocks of the input parameter @var{d}. -@itemize @bullet -@item The leading block @var{D11} of @var{d} is ignored. -@item If @var{inname} and @var{outname} are not given as arguments, - the new inputs and outputs are be assigned default names. -@item @var{yd} is a binary vector of length rows(c) that indicates - continuous/sampled outputs. Default value for @var{yd} is: - -@item @var{sys} = continuous or mixed -@var{yd} = @code{zeros(1,rows(c))} - -@item @var{sys} = discrete -@var{yd} = @code{ones(1,rows(c))} - -@end itemize - -@end deftypefn - -@node sysconnect, syscont, sysappend, blockdiag -@deftypefn {Function File } {@var{retsys} =} sysconnect (@var{sys}, @var{out_idx},@var{in_idx}@{,@var{order}, @var{tol}@}) -Close the loop from specified outputs to respective specified inputs - -@strong{Inputs} -@table @var -@item sys -system data structure -@item out_idx, in_idx -list of connections indices; @math{y(out_idx(ii))} -is connected to @math{u(in_idx(ii))}. -@item order -logical flag (default = 0) -@table @code -@item 0 -leave inputs and outputs in their original order -@item 1 -permute inputs and outputs to the order shown in the diagram below -@end table -@item tol -tolerance for singularities in algebraic loops default: 200@var{eps} -@end table - -@strong{Outputs} - @var{sys}: resulting closed loop system. - -@strong{Method} -@code{sysconnect} internally permutes selected inputs, outputs as shown - below, closes the loop, and then permutes inputs and outputs back to their - original order -@example -@group - ____________________ - u_1 ----->| |----> y_1 - | sys | - old u_2 | | -u_2* ---->(+)--->| |----->y_2 -(in_idx) ^ -------------------| | (out_idx) - | | - ------------------------------- -@end group -@end example -The input that has the summing junction added to it has an * added to the end -of the input name. - -@end deftypefn - -@node syscont, syscont_disc, sysconnect, blockdiag - -@deftypefn {Function File} { [@var{csys}, @var{Acd}, @var{Ccd}] = } syscont (@var{sys}) -Extract the purely continuous subsystem of an input system. - -@strong{Inputs} -@var{sys} is a system data structure - -@strong{Outputs} -@table @var -@item csys - is the purely continuous input/output connections of @var{sys} -@item Acd, Ccd: - connections from discrete states to continuous states, - discrete states to continuous outputs, respectively. - - returns @var{csys} empty if no continuous/continous path exists -@end table - -@end deftypefn - -@node syscont_disc, sysdisc, syscont, blockdiag -@deftypefn {Function File } { [@var{n_tot}, @var{st_c}, @var{st_d}, @var{y_c}, @var{y_d}] =} syscont_disc(@var{sys}) -Used internally in syscont and sysdisc. - -@strong{Inputs} -@var{ sys} is a system data structure. - -@strong{Outputs} -@table @var -@item n_tot -total number of states -@item st_c -vector of continuous state indices (empty if none) -@item st_d -vector of discrete state indices (empty if none) -@item y_c -vector of continuous output indices -@item y_d -vector of discrete output indices -@end table - -@end deftypefn - -@node sysdisc, sysdup, syscont_disc, blockdiag -@deftypefn {Function File } { [@var{dsys}, @var{Adc}, @var{Cdc}] =} sysdisc (@var{sys}) - -@strong{Inputs} -@var{sys} = system data structure - -@strong{Outputs} -@table @var -@item dsys - purely discrete portion of sys (returned empty if there is - no purely discrete path from inputs to outputs) -@item Adc, Cdc - connections from continuous states to discrete states and discrete - outputs, respectively. -@end table - -@end deftypefn - -@node sysdup, sysgroup, sysdisc, blockdiag -@deftypefn {Function File } { @var{retsys} =} sysdup (@var{Asys}, @var{out_idx}, @var{in_idx}) - Duplicate specified input/output connections of a system - -@strong{Inputs} -@table @var -@item Asys - system data structure (@xref{ss2sys}) -@item out_idx,in_idx - list of connections indices; - duplicates are made of @var{y(out_idx(ii))} and @var{u(in_idx(ii))}. -@end table - -@strong{Outputs} -@var{retsys}: resulting closed loop system: - duplicated i/o names are appended with a @code{"+"} suffix. - - -@strong{Method} -@code{sysdup} creates copies of selected inputs and outputs as - shown below. u1/y1 is the set of original inputs/outputs, and - u2,y2 is the set of duplicated inputs/outputs in the order specified - in @var{in_idx}, @var{out_idx}, respectively -@example -@group - ____________________ -u1 ----->| |----> y1 - | Asys | -u2 ------>| |----->y2 -(in_idx) -------------------| (out_idx) -@end group -@end example - -@end deftypefn - -@node sysgroup, sysgroupn, sysdup, blockdiag -@deftypefn {Function File } { @var{sys} =} sysgroup ( @var{Asys}, @var{Bsys}) -Combines two systems into a single system - -@strong{Inputs} -@var{Asys}, @var{Bsys}: system data structures - -@strong{Outputs} - @math{sys = @r{block diag}(Asys,Bsys)} -@example -@group - __________________ - | ________ | -u1 ----->|--> | Asys |--->|----> y1 - | -------- | - | ________ | -u2 ----->|--> | Bsys |--->|----> y2 - | -------- | - ------------------ - Ksys -@end group -@end example -The function also rearranges the internal state-space realization of @var{sys} -so that the - continuous states come first and the discrete states come last. - If there are duplicate names, the second name has a unique suffix appended - on to the end of the name. - -@end deftypefn - -@node sysgroupn, sysmult, sysgroup, blockdiag -@deftypefn {Function File } { @var{names} =} sysgroupn (@var{names}) -Locate and mark duplicate names. Used internally in sysgroup (and elsewhere). -@end deftypefn - -@node sysmult, sysprune, sysgroupn, blockdiag -@deftypefn {Function File } { @var{sys} =} sysmult( @var{Asys}, @var{Bsys}) -Compute @math{sys = Asys*Bsys} (series connection): -@example -@group -u ---------- ---------- ---->| Bsys |---->| Asys |---> - ---------- ---------- -@end group -@end example -A warning occurs if there is direct feed-through -from an input of Bsys or a continuous state of Bsys through a discrete -output of Bsys to a continuous state or output in Asys (system data structure -does not recognize discrete inputs). -@end deftypefn - -@node sysprune, sysreorder, sysmult, blockdiag -@deftypefn {Function File } { @var{retsys} =} sysprune ( @var{Asys}, @var{out_idx}, @var{in_idx}) -Extract specified inputs/outputs from a system - -@strong{Inputs} -@table @var -@item Asys -system data structure -@item out_idx,in_idx - list of connections indices; the new - system has outputs y(out_idx(ii)) and inputs u(in_idx(ii)). - May select as [] (empty matrix) to specify all outputs/inputs. -@end table - -@strong{Outputs} -@var{retsys}: resulting system -@example -@group - ____________________ -u1 ------->| |----> y1 - (in_idx) | Asys | (out_idx) -u2 ------->| |----| y2 - (deleted)-------------------- (deleted) -@end group -@end example - -@end deftypefn - -@node sysreorder, sysscale, sysprune, blockdiag -@deftypefn {Function File } { @var{pv} =} sysreorder( @var{vlen}, @{var{list}) - -@strong{Inputs} -@var{vlen}=vector length, @var{list}= a subset of @code{[1:vlen]}, - -@strong{Outputs} - @var{pv}: a permutation vector to order elements of @code{[1:vlen]} in -@code{list} to the end of a vector. - - Used internally by @code{sysconnect} to permute vector elements to their - desired locations. -@end deftypefn - -@node sysscale, syssub, sysreorder, blockdiag -@deftypefn {Function File } {@var{sys} =} sysscale (@var{sys}, @var{outscale}, @var{inscale}@{, @var{outname}, @var{inname}@}) -scale inputs/outputs of a system. - -@strong{Inputs} - sys: structured system - outscale, inscale: constant matrices of appropriate dimension - -@strong{Outputs} -@var{sys}: resulting open loop system: -@example - ----------- ------- ----------- -u --->| inscale |--->| sys |--->| outscale |---> y - ----------- ------- ----------- -@end example - If the input names and output names (each a list of strings) -are not given and the scaling matrices - are not square, then default names will be given to the inputs and/or - outputs. - -A warning message is printed if outscale attempts to add continuous -system outputs to discrete system outputs; otherwise @var{yd} is -set appropriately in the returned value of @var{sys}. -@end deftypefn - -@node syssub, , sysscale, blockdiag -@deftypefn {Function File } { @var{sys} =} syssub (@var{Gsys}, @var{Hsys}) - returns @math{sys = Gsys - Hsys} - - Method: @var{Gsys} and @var{Hsys} are connected in parallel - The input vector is connected to both systems; the outputs are - subtracted. Returned system names are those of @var{Gsys}. -@example -@group - ________ - ----| Gsys |--- -u | ---------- +| ------ (_)----> y - | ________ -| - ----| Hsys |--- - -------- -@end group -@end example -@end deftypefn - -@deftypefn {Function File } { @var{outsys} =} ugain(n) - Creates a system with unity gain, no states. - This trivial system is sometimes needed to create arbitrary - complex systems from simple systems with buildssic. - Watch out if you are forming sampled systems since "ugain" - does not contain a sampling period. - -See also: hinfdemo (MIMO H_infinty example, Boeing 707-321 aircraft model) - -@end deftypefn - -@deftypefn {Function File } { @var{wsys} =} wgt1o (@var{vl}, @var{vh}, @var{fc}) -State space description of a first order weighting function. - - Weighting function are needed by the H2/H_infinity design procedure. - These function are part of thye augmented plant P (see hinfdemo - for an applicattion example). - - vl = Gain @@ low frequencies - - vh = Gain @@ high frequencies - - fc = Corner frequency (in Hz, *not* in rad/sec) -@end deftypefn - -@node numerical, sysprop, blockdiag, Control Theory -@section Numerical Functions -@deftypefn {Function File} {} are (@var{a}, @var{b}, @var{c}, @var{opt}) -Solve the algebraic Riccati equation -@iftex -@tex -$$ -A^TX + XA - XBX + C = 0 -$$ -@end tex -@end iftex -@ifinfo -@example -a' * x + x * a - x * b * x + c = 0 -@end example -@end ifinfo - -@strong{Inputs} -@noindent -for identically dimensioned square matrices -@table @var -@item a -@var{n}x@var{n} matrix. -@item b - @var{n}x@var{n} matrix or @var{n}x@var{m} matrix; in the latter case - @var{b} is replaced by @math{b:=b*b'}. -@item c - @var{n}x@var{n} matrix or @var{p}x@var{m} matrix; in the latter case - @var{c} is replaced by @math{c:=c'*c}. -@item opt -(optional argument; default = @code{"B"}): -String option passed to @code{balance} prior to ordered Schur decomposition. -@end table - -@strong{Outputs} -@var{x}: solution of the ARE. - -@strong{Method} -Laub's Schur method (IEEE Transactions on -Automatic Control, 1979) is applied to the appropriate Hamiltonian -matrix. - -@end deftypefn - -@deftypefn {Function File} {} dare (@var{a}, @var{b}, @var{c}, @var{r}, @var{opt}) - -Return the solution, @var{x} of the discrete-time algebraic Riccati -equation -@iftex -@tex -$$ -A^TXA - X + A^TXB (R + B^TXB)^{-1} B^TXA + C = 0 -$$ -@end tex -@end iftex -@ifinfo -@example -a' x a - x + a' x b (r + b' x b)^(-1) b' x a + c = 0 -@end example -@end ifinfo -@noindent - -@strong{Inputs} -@table @var -@item a -@var{n} by @var{n}. - -@item b -@var{n} by @var{m}. - -@item c -@var{n} by @var{n}, symmetric positive semidefinite, or @var{p} by @var{n}. -In the latter case @math{c:=c'*c} is used. - -@item r -@var{m} by @var{m}, symmetric positive definite (invertible). - -@item opt -(optional argument; default = @code{"B"}): -String option passed to @code{balance} prior to ordered @var{QZ} decomposition. -@end table - -@strong{Outputs} -@var{x} solution of DARE. - -@strong{Method} -Generalized eigenvalue approach (Van Dooren; SIAM J. - Sci. Stat. Comput., Vol 2) applied to the appropriate symplectic pencil. - - See also: Ran and Rodman, "Stable Hermitian Solutions of Discrete - Algebraic Riccati Equations," Mathematics of Control, Signals and - Systems, Vol 5, no 2 (1992) pp 165-194. - -@end deftypefn - -@deftypefn {Function File } { @var{m} =} dgram ( @var{a}, @var{b}) - Return controllability grammian of discrete time system -@example - x(k+1) = a x(k) + b u(k) -@end example - -@strong{Inputs} -@table @var -@item a -@var{n} by @var{n} matrix -@item b -@var{n} by @var{m} matrix -@end table - -@strong{Outputs} -@var{m} (@var{n} by @var{n}) satisfies -@example - a m a' - m + b*b' = 0 -@end example - -@end deftypefn - -@deftypefn {Function File} {@var{x} = } dlyap (@var{a}, @var{b}) -Solve the discrete-time Lyapunov equation - - @strong{Inputs} - @table @var - @item a - @var{n} by @var{n} matrix - @item b - Matrix: @var{n} by @var{n}, @var{n} by @var{m}, or @var{p} by @var{n}. - @end table - - @strong{Outputs} - @var{x}: matrix satisfying appropriate discrete time Lyapunov equation. - Options: - @itemize @bullet - @item @var{b} is square: solve @code{a x a' - x + b = 0} - @item @var{b} is not square: @var{x} satisfies either - @example - a x a' - x + b b' = 0 - @end example - @noindent - or - @example - a' x a - x + b' b = 0, - @end example - @noindent - whichever is appropriate. - @end itemize - -@strong{Method} - Uses Schur decomposition method as in Kitagawa, - @cite{An Algorithm for Solving the Matrix Equation @var{X} = - @var{F}@var{X}@var{F}' + @var{S}}, - International Journal of Control, Volume 25, Number 5, pages 745--753 - (1977). - -Column-by-column solution method as suggested in - Hammarling, @cite{Numerical Solution of the Stable, Non-Negative - Definite Lyapunov Equation}, IMA Journal of Numerical Analysis, Volume - 2, pages 303--323 (1982). - -@end deftypefn - -@deftypefn {Function File } { @var{m} =} gram (@var{a}, @var{b}) - Return controllability grammian @var{m} of the continuous time system -@math{ dx/dt = a x + b u}. - -@var{m} satisfies @math{ a m + m a' + b b' = 0 }. -@end deftypefn - - -@deftypefn {Function File} {} lyap (@var{a}, @var{b}, @var{c}) -@deftypefnx {Function File} {} lyap (@var{a}, @var{b}) - Solve the Lyapunov (or Sylvester) equation via the Bartels-Stewart - algorithm (Communications of the ACM, 1972). - - If @var{a}, @var{b}, and @var{c} are specified, then @code{lyap} returns - the solution of the Sylvester equation - @iftex - @tex - $$ A X + X B + C = 0 $$ - @end tex - @end iftex - @ifinfo - @example - a x + x b + c = 0 - @end example - @end ifinfo - If only @code{(a, b)} are specified, then @code{lyap} returns the - solution of the Lyapunov equation - @iftex - @tex - $$ A^T X + X A + B = 0 $$ - @end tex - @end iftex - @ifinfo - @example - a' x + x a + b = 0 - @end example - @end ifinfo - If @var{b} is not square, then @code{lyap} returns the solution of either - @iftex - @tex - $$ A^T X + X A + B^T B = 0 $$ - @end tex - @end iftex - @ifinfo - @example - a' x + x a + b' b = 0 - @end example - @end ifinfo - @noindent - or - @iftex - @tex - $$ A X + X A^T + B B^T = 0 $$ - @end tex - @end iftex - @ifinfo - @example - a x + x a' + b b' = 0 - @end example - @end ifinfo - @noindent - whichever is appropriate. -@end deftypefn - -@deftypefn {Function File } { } pinv ( @var{X}@{,@var{tol}@} ) -Returns the pseudoinverse of X; singular values less than tol are ignored. -@end deftypefn - -@deftypefn {Function File } { @var{x} =} qzval (@var{A}, @var{B}) -Compute generalized eigenvalues of the matrix pencil -@ifinfo -@example -(A - lambda B). -@end example -@end ifinfo -@iftex -@tex -$(A - \lambda B)$. -@end tex -@end iftex - -@var{A} and @var{B} must be real matrices. - -@strong{Note} @code{qzval} is obsolete; use @code{qz} instead. -@end deftypefn - -@deftypefn {Function File } { } zgfmul -@deftypefnx {Function File } { } zgfslv -@deftypefnx {Function File } { } zginit -@deftypefnx {Function File } {@var{retsys} =} zgpbal (@var{Asys}) -@deftypefnx {Function File } {} zgreduce -@deftypefnx {Function File } { [@var{nonz}, @var{zer}] =} zgrownorm (@var{mat}, @var{meps}) -@deftypefnx {Function File } { x =} zgscal (@var{f}, @var{z}, @var{n}, @var{m}, @var{p}) -@deftypefnx {Function File } { } zgsgiv ( ) -@deftypefnx {Function File } { @var{x} =} zgshsr( @var{y}) -Used internally by @code{tzero}. -Minimal argument checking performed. - -Details involving major subroutines: -@table @code -@item zgpbal -Implementation of zero computation generalized eigenvalue problem - balancing method. @code{zgpbal} computes a state/input/output -weighting that attempts to - reduced the range of the magnitudes of the nonzero elements of [a,b,c,d] - The weighting uses scalar multiplication by powers of 2, so no roundoff - will occur. - - @code{zgpbal} should be followed by @code{zgpred} - -@item zgreduce -Implementation of procedure REDUCE in (Emami-Naeini and Van Dooren, -Automatica, 1982). - -@item zgrownorm - Returns @var{nonz} = number of rows of @var{mat} whose two norm exceeds - @var{meps}, @var{zer} = number of rows of mat whose two norm - is less than meps - -@item zgscal -Generalized conjugate gradient iteration to - solve zero-computation generalized eigenvalue problem balancing equation - @math{fx=z}; - called by @code{zgepbal} - -@item zgsgiv -apply givens rotation c,s to column vector a,b -@item zgshsr -Apply Householder vector based on @code{e^(m)} (all ones) to -(column vector) @var{y}. Called by @code{zgfslv}. - -@end table -References: -@table @strong -@item ZGEP - Hodel, "Computation of Zeros with Balancing," 1992, Linear Algebra - and its Applications -@item @strong{Generalized CG} - Golub and Van Loan, "Matrix Computations, 2nd ed" 1989 -@end table - -@end deftypefn - -@node sysprop, systime, numerical, Control Theory -@section System Analysis-Properties - -@deftypefn {Function File } { } analdemo ( ) - Octave Controls toolbox demo: State Space analysis demo -@end deftypefn - - -@deftypefn {Function File} {[@var{n}, @var{m}, @var{p}] =} abcddim (@var{a}, @var{b}, @var{c}, @var{d}) -Check for compatibility of the dimensions of the matrices defining -the linear system -@iftex -@tex -$[A, B, C, D]$ corresponding to -$$ -\eqalign{ - {dx\over dt} &= A x + B u\cr - y &= C x + D u} -$$ -@end tex -@end iftex -@ifinfo -[A, B, C, D] corresponding to - -@example -dx/dt = a x + b u -y = c x + d u -@end example - -@end ifinfo -or a similar discrete-time system. - -If the matrices are compatibly dimensioned, then @code{abcddim} returns - -@table @var -@item n -The number of system states. - -@item m -The number of system inputs. - -@item p -The number of system outputs. -@end table - -Otherwise @code{abcddim} returns @var{n} = @var{m} = @var{p} = @minus{}1. - -Note: n = 0 (pure gain block) is returned without warning. - -See also: is_abcd -@end deftypefn - -@deftypefn {Function File } {[@var{y}, @var{my}, @var{ny}] =} abcddims (@var{x}) - -Used internally in @code{abcddim}. If @var{x} is a zero-size matrix, -both dimensions are set to 0 in @var{y}. -@var{my} and @var{ny} are the row and column dimensions of the result. -@end deftypefn - -@deftypefn {Function File } {@var{Qs} =} ctrb(@var{sys} @{, @var{b}@}) -@deftypefnx {Function File } {@var{Qs} =} ctrb(@var{A}, @var{B}) -Build controllability matrix -@example - 2 n-1 -Qs = [ B AB A B ... A B ] -@end example - - of a system data structure or the pair (@var{A}, @var{B}). - -@strong{Note} @code{ctrb} forms the controllability matrix. - The numerical properties of @code{is_controllable} - are much better for controllability tests. -@end deftypefn - -@deftypefn {Function File } {@var{retval} =} h2norm(@var{sys}) -Computes the H2 norm of a system data structure (continuous time only) - -Reference: - Doyle, Glover, Khargonekar, Francis, ``State Space Solutions to Standard - H2 and Hinf Control Problems", IEEE TAC August 1989 -@end deftypefn - -@deftypefn {Function File } {[@var{g}, @var{gmin}, @var{gmax}] =} hinfnorm(@var{sys}@{, @var{tol}, @var{gmin}, @var{gmax}, @var{ptol}@}) - Computes the H infinity norm of a system data structure. - -@strong{Inputs} -@table @var -@item sys -system data structure -@item tol -H infinity norm search tolerance (default: 0.001) -@item gmin -minimum value for norm search (default: 1e-9) -@item gmax -maximum value for norm search (default: 1e+9) -@item ptol - pole tolerance: -@itemize @bullet -@item if sys is continuous, poles with -|real(pole)| < ptol*||H|| (H is appropriate Hamiltonian) -are considered to be on the imaginary axis. - -@item if sys is discrete, poles with -|abs(pole)-1| < ptol*||[s1,s2]|| (appropriate symplectic pencil) -are considered to be on the unit circle - -@item Default: 1e-9 -@end itemize -@end table - -@strong{Outputs} -@table @var -@item g -Computed gain, within @var{tol} of actual gain. @var{g} is returned as Inf -if the system is unstable. -@item gmin, gmax -Actual system gain lies in the interval [@var{gmin}, @var{gmax}] -@end table - - References: - Doyle, Glover, Khargonekar, Francis, "State space solutions to standard - H2 and Hinf control problems", IEEE TAC August 1989 - Iglesias and Glover, "State-Space approach to discrete-time Hinf control," - Int. J. Control, vol 54, #5, 1991 - Zhou, Doyle, Glover, "Robust and Optimal Control," Prentice-Hall, 1996 - $Revision: 1.9 $ -@end deftypefn - -@deftypefn {Function File } { @var{Qb} =} obsv (@var{sys}@{, @var{c}@}) -Build observability matrix -@example -@group - | C | - | CA | -Qb = | CA^2 | - | ... | - | CA^(n-1) | -@end group -@end example -of a system data structure or the pair (A, C). - -Note: @code{obsv()} forms the observability matrix. - - The numerical properties of is_observable() - are much better for observability tests. -@end deftypefn - -@deftypefn {Function File } {[@var{zer}, @var{pol}]=} pzmap (@var{sys}) - Plots the zeros and poles of a system in the complex plane. -@strong{Inputs} - @var{sys} system data structure - -@strong{Outputs} -if omitted, the poles and zeros are plotted on the screen. - otherwise, pol, zer are returned as the system poles and zeros. - (see sys2zp for a preferable function call) -@end deftypefn - -@deftypefn{Function File} {outputs = } synKnames (inputs) -Return controller signal names based in plant signal names and dimensions -@end deftypefn - -@deftypefn {Function File } { @var{retval} =} is_abcd( @var{a}@{, @var{b}, @var{c}, @var{d}@}) - Returns @var{retval} = 1 if the dimensions of @var{a}, @var{b}, @var{c}, @var{d} - are compatible, otherwise @var{retval} = 0 with an appropriate diagnostic -message printed to the screen. -@end deftypefn - -@deftypefn {Function File } {[@var{retval}, @var{U}] =} is_controllable (@var{sys}@{, @var{tol}@}) -@deftypefnx {Function File } {[@var{retval}, @var{U}] =} is_controllable (@var{a}@{, @var{b} ,@var{tol}@}) -Logical check for system controllability. - -@strong{Inputs} -@table @var -@item sys -system data structure -@item a, b -@var{n} by @var{n}, @var{n} by @var{m} matrices, respectively -@item tol -optional roundoff paramter. default value: @code{10*eps} -@end table - -@strong{Outputs} -@table @var -@item retval -Logical flag; returns true (1) if the system @var{sys} or the -pair (@var{a},@var{b}) is controllable, whichever was passed as input arguments. -@item U - U is an orthogonal basis of the controllable subspace. -@end table - -@strong{Method} -Controllability is determined by applying Arnoldi iteration with -complete re-orthogonalization to obtain an orthogonal basis of the -Krylov subspace -@example -span ([b,a*b,...,a^@{n-1@}*b]). -@end example -The Arnoldi iteration is executed with @code{krylov} if the system has a single input; otherwise a block Arnoldi iteration is performed with @code{krylovb}. - -@strong{See also} -@code{is_observable}, @code{is_stabilizable}, @code{is_detectable}, - @code{krylov}, @code{krylovb} - -@end deftypefn - -@deftypefn {Function File } { [@var{retval}, @var{U}] =} is_detectable (@var{a}, @var{c}@{, @var{tol}@}) -@deftypefnx {Function File } { [@var{retval}, @var{U}] =} is_detectable (@var{sys}@{, @var{tol}@}) -Test for detactability (observability of unstable modes) of (@var{a},@var{c}). - - Returns 1 if the system @var{a} or the pair (@var{a},@var{c})is - detectable, 0 if not. - -@strong{See} @code{is_stabilizable} for detailed description of arguments and -computational method. - -@end deftypefn - -@deftypefn {Function File } { [@var{retval}, @var{dgkf_struct} ] =} is_dgkf (@var{Asys}, @var{nu}, @var{ny}, @var{tol} ) - Determine whether a continuous time state space system meets - assumptions of DGKF algorithm. - Partitions system into: -@example -[dx/dt] = [A | Bw Bu ][w] -[ z ] [Cz | Dzw Dzu ][u] -[ y ] [Cy | Dyw Dyu ] -@end example -or similar discrete-time system. -If necessary, orthogonal transformations @var{Qw}, @var{Qz} and nonsingular - transformations @var{Ru}, @var{Ry} are applied to respective vectors -@var{w}, @var{z}, @var{u}, @var{y} in order to satisfy DGKF assumptions. -Loop shifting is used if @var{Dyu} block is nonzero. - -@strong{Inputs} -@table @var -@item Asys -system data structure -@item nu -number of controlled inputs -@item ny - number of measured outputs -@item tol - threshhold for 0. Default: 200@var{eps} -@end table -@strong{Outputs} -@table @var -@item retval - true(1) if system passes check, false(0) otherwise -@item dgkf_struct - data structure of @code{is_dgkf} results. Entries: -@table @var -@item nw, nz - dimensions of @var{w}, @var{z} -@item A - system @var{A} matrix -@item Bw - (@var{n} x @var{nw}) @var{Qw}-transformed disturbance input matrix -@item Bu - (@var{n} x @var{nu}) @var{Ru}-transformed controlled input matrix; - - @strong{Note} @math{B = [Bw Bu] } -@item Cz - (@var{nz} x @var{n}) Qz-transformed error output matrix -@item Cy - (@var{ny} x @var{n}) @var{Ry}-transformed measured output matrix - - @strong{Note} @math{C = [Cz; Cy] } -@item Dzu, Dyw - off-diagonal blocks of transformed @var{D} matrix that enter -@var{z}, @var{y} from @var{u}, @var{w} respectively -@item Ru - controlled input transformation matrix -@item Ry - observed output transformation matrix -@item Dyu_nz - nonzero if the @var{Dyu} block is nonzero. -@item Dyu - untransformed @var{Dyu} block -@item dflg - nonzero if the system is discrete-time - @end table -@end table -@code{is_dgkf} exits with an error if the system is mixed discrete/continuous - -@strong{References} -@table @strong -@item [1] - Doyle, Glover, Khargonekar, Francis, "State Space Solutions - to Standard H2 and Hinf Control Problems," IEEE TAC August 1989 -@item [2] - Maciejowksi, J.M.: "Multivariable feedback design," -@end table - -@end deftypefn - -@deftypefn {Function File } { @var{retval} =} is_digital ( @var{sys}) -Return nonzero if system is digital; -Exits with an error of sys is a mixed (continuous and discrete) system -@end deftypefn - -@deftypefn {Function File } { [@var{retval},@var{U}] =} is_observable (@var{a}, @var{c}@{,@var{tol}@}) -@deftypefnx {Function File } { [@var{retval},@var{U}] =} is_observable (@var{sys}@{, @var{tol}@}) -Logical check for system observability. - Returns 1 if the system @var{sys} or the pair (@var{a},@var{c}) is - observable, 0 if not. - -@strong{See} @code{is_controllable} for detailed description of arguments -and default values. -@end deftypefn - -@deftypefn {Function File } { @var{retval} =} is_sample (@var{Ts}) - return true if @var{Ts} is a legal sampling time - (real,scalar, > 0) -@end deftypefn - -@deftypefn {Function File } { @var{retval} =} is_siso (@var{sys}) -return nonzero if the system data structure -@var{sys} is single-input, single-output. -@end deftypefn - -@deftypefn {Function File } {[@var{retval}, @var{U}] =} is_stabilizable (@var{sys}@{, @var{tol}@}) -@deftypefnx {Function File } {[@var{retval}, @var{U}] =} is_stabilizable (@var{a}@{, @var{b} ,@var{tol}@}) -Logical check for system stabilizability (i.e., all unstable modes are controllable). - -@strong{See} @code{is_controllable} for description of inputs, outputs. -Test for stabilizability is performed via an ordered Schur decomposition -that reveals the unstable subspace of the system @var{A} matrix. - -@end deftypefn - -@deftypefn {Function File } {@var{flg} =} is_signal_list (@var{mylist}) -returns true if mylist is a list of individual strings (legal for input -to @var{syssetsignals}). -@end deftypefn - -@deftypefn {Function File } { @var{retval} =} is_stable (@var{a}@{,@var{tol},@var{dflg}@}) -@deftypefnx {Function File } { @var{retval} =} is_stable (@var{sys}@{,@var{tol}@}) - Returns retval = 1 if the matrix @var{a} or the system @var{sys} -is stable, or 0 if not. - -@strong{Inputs} -@table @var -@item tol -is a roundoff paramter, set to 200*@var{eps} if omitted. -@item dflg -Digital system flag (not required for system data structure): -@table @code -@item @var{dflg} != 0 -stable if eig(a) in unit circle - -@item @var{dflg} == 0 -stable if eig(a) in open LHP (default) -@end table -@end table -@end deftypefn - -@node systime, sysfreq, sysprop, Control Theory -@section System Analysis-Time Domain - -@deftypefn {Function File } { @var{dsys} =} c2d (@var{sys}@{, @var{opt}, @var{T}@}) -@deftypefnx {Function File } { @var{dsys} =} c2d (@var{sys}@{, @var{T}@}) - -@strong{Inputs} -@table @var -@item sys - system data structure (may have both continuous time and discrete time subsystems) -@item opt -string argument; conversion option (optional argument; -may be omitted as shown above) -@table @code -@item "ex" -use the matrix exponential (default) -@item "bi" -use the bilinear transformation -@end table -@example - 2(z-1) -s = ----- - T(z+1) -@end example -FIXME: This option exits with an error if @var{sys} is not purely -continuous. (The @code{ex} option can handle mixed systems.) -@item @var{T} -sampling time; required if sys is purely continuous. - -@strong{Note} If the 2nd argument is not a string, @code{c2d} assumes that -the 2nd argument is @var{T} and performs appropriate argument checks. -@end table - -@strong{Outputs} -@var{dsys} discrete time equivalent via zero-order hold, -sample each @var{T} sec. - -converts the system data structure describing -@example -. -x = Ac x + Bc u -@end example -into a discrete time equivalent model -@example -x[n+1] = Ad x[n] + Bd u[n] -@end example -via the matrix exponential or bilinear transform - -@strong{Note} This function adds the suffix @code{_d} -to the names of the new discrete states. -@end deftypefn - -@deftypefn {Function File } {@var{csys} =} d2c (@var{sys}@{,@var{tol}@}) -@deftypefnx {Function File } {@var{csys} =} d2c (@var{sys}, @var{opt}) -Convert discrete (sub)system to a purely continuous system. Sampling -time used is @code{sysgettsam(@var{sys})} - -@strong{Inputs} -@table @var -@item sys - system data structure with discrete components -@item tol -Scalar value. - tolerance for convergence of default @code{"log"} option (see below) -@item opt - conversion option. Choose from: -@table @code -@item "log" - (default) Conversion is performed via a matrix logarithm. -Due to some problems with this computation, it is -followed by a steepest descent algorithm to identify continuous time -@var{A}, @var{B}, to get a better fit to the original data. - -If called as @code{d2c}(@var{sys},@var{tol}), @var{tol=}positive scalar, - the @code{"log"} option is used. The default value for @var{tol} is - @code{1e-8}. -@item "bi" - Conversion is performed via bilinear transform -@math{z = (1 + s T / 2)/(1 - s T / 2)} where @var{T} is the -system sampling time (see @code{sysgettsam}). - -FIXME: bilinear option exits with an error if @var{sys} is not purely discrete - -@end table -@end table -@strong{Outputs} @var{csys} continuous time system (same dimensions and -signal names as in @var{sys}). -@end deftypefn - -@deftypefn {Function File } {[@var{dsys}, @var{fidx}] =} dmr2d (@var{sys}, @var{idx}, @var{sprefix}, @var{Ts2} @{,@var{cuflg}@}) - convert a multirate digital system to a single rate digital system - states specified by @var{idx}, @var{sprefix} are sampled at @var{Ts2}, all - others are assumed sampled at @var{Ts1} = @code{sysgettsam(@var{sys})}. - -@strong{Inputs} -@table @var -@item sys -discrete time system; -@code{dmr2d} exits with an error if @var{sys} is not discrete -@item idx -list of states with sampling time @code{sysgettsam(@var{sys})} (may be empty) -@item sprefix -list of string prefixes of states with sampling time @code{sysgettsam(@var{sys})} -(may be empty) -@item Ts2 -sampling time of states not specified by @var{idx}, @var{sprefix} -must be an integer multiple of @code{sysgettsam(@var{sys})} -@item cuflg -"constant u flag" if @var{cuflg} is nonzero then the system inputs are - assumed to be constant over the revised sampling interval @var{Ts2}. - Otherwise, since the inputs can change during the interval - @var{t} in @math{[k Ts2, (k+1) Ts2]}, an additional set of inputs is - included in the revised B matrix so that these intersample inputs - may be included in the single-rate system. - default - @var{cuflg} = 1. -@end table - -@strong{Outputs} -@table @var -@item dsys - equivalent discrete time system with sampling time @var{Ts2}. - - The sampling time of sys is updated to @var{Ts2}. - - if @var{cuflg}=0 then a set of additional inputs is added to - the system with suffixes _d1, ..., _dn to indicate their - delay from the starting time k @var{Ts2}, i.e. - u = [u_1; u_1_d1; ..., u_1_dn] where u_1_dk is the input - k*Ts1 units of time after u_1 is sampled. (Ts1 is - the original sampling time of discrete time sys and - @var{Ts2} = (n+1)*Ts1) - -@item fidx -indices of "formerly fast" states specified by @var{idx} and @var{sprefix}; -these states are updated to the new (slower) sampling interval @var{Ts2}. -@end table - -@strong{WARNING} Not thoroughly tested yet; especially when @var{cuflg} == 0. - -@end deftypefn - -@deftypefn {Function File } {} damp(@var{p}@{, @var{tsam}@}) - Displays eigenvalues, natural frequencies and damping ratios - of the eigenvalues of a matrix @var{p} or the @var{A}-matrix of a - system @var{p}, respectively. - If @var{p} is a system, @var{tsam} must not be specified. - If @var{p} is a matrix and @var{tsam} is specified, eigenvalues - of @var{p} are assumed to be in @var{z}-domain. - -See also: @code{eig} -@end deftypefn - -@deftypefn {Function File } {@var{gm} =} dcgain(@var{sys}@{, tol@}) - Returns dc-gain matrix. If dc-gain is infinite - an empty matrix is returned. - The argument @var{tol} is an optional tolerance for the condition - number of @var{A}-Matrix in @var{sys} (default @var{tol} = 1.0e-10) -@end deftypefn - -@deftypefn {Function File } {[@var{y}, @var{t}] =} impulse (@var{sys}@{, @var{inp},@var{tstop}, @var{n}@}) -Impulse response for a linear system. - The system can be discrete or multivariable (or both). -If no output arguments are specified, @code{impulse} - produces a plot or the step response data for system @var{sys}. - -@strong{Inputs} -@table @var -@item sys -System data structure. -@item inp -Index of input being excited -@item tstop - The argument @var{tstop} (scalar value) denotes the time when the - simulation should end. -@item n -the number of data values. - - Both parameters @var{tstop} and @var{n} can be omitted and will be - computed from the eigenvalues of the A-Matrix. -@end table -@strong{Outputs} -@var{y}, @var{t}: impulse response -@end deftypefn - -@deftypefn {Function File } {[@var{y}, @var{t}] =} step (@var{sys}@{, @var{inp},@var{tstop}, @var{n}@}) -Step response of a linear system; calling protocol is identical to -@code{impulse}. -@end deftypefn - -@deftypefn {Function File } { } stepimp ( ) -Used internally in @code{impulse}, @code{step}. -@end deftypefn - -@node sysfreq, cacsd, systime, Control Theory -@section System Analysis-Frequency Domain - -@strong{Demonstration/tutorial script} -@deftypefn {Function File } { } frdemo ( ) -@end deftypefn - - -@deftypefn {Function File } {[@var{mag}, @var{phase}, @var{w}] =} bode(@var{sys}@{,@var{w}, @var{out_idx}, @var{in_idx}@}) -If no output arguments are given: produce Bode plots of a system; otherwise, -compute the frequency response of a system data structure - -@strong{Inputs} -@table @var -@item sys - a system data structure (must be either purely continuous or discrete; - see is_digital) -@item w - frequency values for evaluation. - -if @var{sys} is continuous, then bode evaluates @math{G(jw)} where -@math{G(s)} is the system transfer function. - -if @var{sys} is discrete, then bode evaluates G(@code{exp}(jwT)), where -@itemize @bullet -@item @var{T}=@code{sysgettsam(@var{sys})} (the system sampling time) and -@item @math{G(z)} is the system transfer function. -@end itemize - -@strong{ Default} the default frequency range is selected as follows: (These - steps are NOT performed if @var{w} is specified) -@enumerate -@item via routine bodquist, isolate all poles and zeros away from -@var{w}=0 (@var{jw}=0 or @math{@code{exp}(jwT)}=1) and select the frequency -range based on the breakpoint locations of the frequencies. -@item if @var{sys} is discrete time, the frequency range is limited - to @math{jwT} in -@ifinfo -[0,2 pi /T] -@end ifinfo -@iftex -@tex -$[0,2\pi/T]$ -@end tex -@end iftex -@item A "smoothing" routine is used to ensure that the plot phase does - not change excessively from point to point and that singular - points (e.g., crossovers from +/- 180) are accurately shown. - -@end enumerate -@item out_idx, in_idx - the indices of the output(s) and input(s) to be used in - the frequency response; see @code{sysprune}. -@end table -@strong{Outputs} -@table @var -@item mag, phase - the magnitude and phase of the frequency response - @math{G(jw)} or @math{G(@code{exp}(jwT))} at the selected frequency values. -@item w -the vector of frequency values used -@end table - -@strong{Notes} -@enumerate -@item If no output arguments are given, e.g., -@example -bode(sys); -@end example -bode plots the results to the -screen. Descriptive labels are automatically placed. - -Failure to include a concluding semicolon will yield some garbage -being printed to the screen (@code{ans = []}). - -@item If the requested plot is for an MIMO system, mag is set to - @math{||G(jw)||} or @math{||G(@code{exp}(jwT))||} -and phase information is not computed. -@end enumerate -@end deftypefn - -@deftypefn {Function File } {[@var{wmin}, @var{wmax}] =} bode_bounds (@var{zer}, @var{pol}, @var{dflg}@{, @var{tsam} @}) -Get default range of frequencies based on cutoff frequencies of system -poles and zeros. -Frequency range is the interval [10^wmin,10^wmax] - -Used internally in freqresp (@code{bode}, @code{nyquist}) -@end deftypefn - -@deftypefn {Function File } { [@var{f}, @var{w}] =} bodquist (@var{sys}, @var{w}, @var{out_idx}, @var{in_idx}) - used internally by bode, nyquist; compute system frequency response. - -@strong{Inputs} -@table @var -@item sys -input system structure -@item w -range of frequencies; empty if user wants default -@item out_idx -list of outputs; empty if user wants all -@item in_idx -list of inputs; empty if user wants all -@item rname -name of routine that called bodquist ("bode" or "nyquist") -@end table -@strong{Outputs} -@table @var -@item w - list of frequencies -@item f - frequency response of sys; @math{f(ii) = f(omega(ii))} -@end table -@strong{Note} bodquist could easily be incorporated into a Nichols -plot function; this is in a "to do" list. -@end deftypefn - -@deftypefn {Function File } { @var{retval} =} freqchkw ( @var{w} ) -Used by @code{freqresp} to check that input frequency vector @var{w} is legal. -Returns boolean value. -@end deftypefn - -@deftypefn {Function File } { @var{out} =} freqresp (@var{sys},@var{USEW}@{,@var{w}@}); - Frequency response function - used internally by @code{bode}, @code{nyquist}. - minimal argument checking; "do not attempt to do this at home" - -@strong{Inputs} -@table @var -@item sys -system data structure -@item USEW -returned by @code{freqchkw} -@item optional - must be present if @var{USEW} is true (nonzero) -@end table -@strong{Outputs} -@table @var -@item @var{out} -vector of finite @math{G(j*w)} entries (or @math{||G(j*w)||} for MIMO) -@item w -vector of corresponding frequencies -@end table -@end deftypefn - -@deftypefn {Function File } {@var{out} =} ltifr (@var{A}, @var{B}, @var{w}) -@deftypefnx {Function File } {@var{out} =} ltifr (@var{sys}, @var{w}) -Linear time invariant frequency response of single input systems -@strong{Inputs} -@table @var -@item A, B -coefficient matrices of @math{dx/dt = A x + B u} -@item sys - system data structure -@item w - vector of frequencies -@end table -@strong{Outputs} -@var{out} -@example - -1 - G(s) = (jw I-A) B -@end example -for complex frequencies @math{s = jw}. -@end deftypefn - -@deftypefn {Function File } {[@var{realp}, @var{imagp}, @var{w}] =} nyquist (@var{sys}@{, @var{w}, @var{out_idx}, @var{in_idx}, @var{atol}@}) -@deftypefnx {Function File } {} nyquist (@var{sys}@{, @var{w}, @var{out_idx}, @var{in_idx}, @var{atol}@}) -Produce Nyquist plots of a system; if no output arguments are given, Nyquist -plot is printed to the screen. - -Arguments are identical to @code{bode} with exceptions as noted below: - -@strong{Inputs} (pass as empty to get default values) -@table @var -@item atol -for interactive nyquist plots: atol is a change-in-slope tolerance -for the of asymptotes (default = 0; 1e-2 is a good choice). This allows -the user to ``zoom in'' on portions of the Nyquist plot too small to be -seen with large asymptotes. -@end table -@strong{Outputs} -@table @var -@item realp, imagp -the real and imaginary parts of the frequency response - @math{G(jw)} or @math{G(exp(jwT))} at the selected frequency values. -@item w - the vector of frequency values used -@end table - - If no output arguments are given, nyquist plots the results to the screen. - If @var{atol} != 0 and asymptotes are detected then the user is asked - interactively if they wish to zoom in (remove asymptotes) - Descriptive labels are automatically placed. - - Note: if the requested plot is for an MIMO system, a warning message is - presented; the returned information is of the magnitude - ||G(jw)|| or ||G(exp(jwT))|| only; phase information is not computed. - -@end deftypefn - -@deftypefn {Function File} {} tzero (@var{a}, @var{b}, @var{c}, @var{d}@{, @var{opt}@}) -@deftypefnx {Function File} {} tzero (@var{sys}@{,@var{opt}@}) - Compute transmission zeros of a continuous -@example -. -x = Ax + Bu -y = Cx + Du -@end example -or discrete -@example -x(k+1) = A x(k) + B u(k) -y(k) = C x(k) + D u(k) -@end example -system. -@strong{Outputs} -@table @var -@item zer - transmission zeros of the system -@item gain -leading coefficient (pole-zero form) of SISO transfer function -returns gain=0 if system is multivariable -@end table -@strong{References} -@enumerate -@item Emami-Naeini and Van Dooren, Automatica, 1982. -@item Hodel, "Computation of Zeros with Balancing," 1992 Lin. Alg. Appl. -@end enumerate -@end deftypefn - -@deftypefn {Function File } { @var{zr} =} tzero2 (@var{a}, @var{b}, @var{c}, @var{d}, @var{bal}) -Compute the transmission zeros of a, b, c, d. - -bal = balancing option (see balance); default is "B". - -Needs to incorporate @code{mvzero} algorithm to isolate finite zeros; use -@code{tzero} instead. -@end deftypefn - -@node cacsd, misc, sysfreq, Control Theory -@section Controller Design - -@deftypefn {Function File } { } dgkfdemo ( ) - Octave Controls toolbox demo: H2/Hinfinity options demos -@end deftypefn -@deftypefn {Function File } { } hinfdemo ( ) -Non-trivial H_infinity design demo. - -H_infinity optimal controller for the jet707 plant; -Linearized state space model of a Boeing 707-321 aircraft -at v=80m/s. (M = 0.26, Ga0 = -3 deg, -alpha0 = 4 deg, kappa = 50 deg) -inputs: (1) thrust and (2) elevator angle -outputs: (1) airspeed and (2) pitch angle - -The optimal controller minimizes the H_infinity norm of the -augmented plant P (mixed-sensitivity problem): -@example -@group - w - 1 -----------+ - | +----+ - +---------------------->| W1 |----> z1 - w | | +----+ - 2 ------------------------+ - | | | - | v +----+ v +----+ - +--*-->o-->| G |-->o--*-->| W2 |---> z2 - | +----+ | +----+ - | | - ^ v - u (from y (to K) - controller - K) - -+ + + + -| z | | w | -| 1 | | 1 | -| z | = [ P ] * | w | -| 2 | | 2 | -| y | | u | -+ + + + -@end group -@end example -@end deftypefn - -@deftypefn {Function File} {[@var{l}, @var{m}, @var{p}, @var{e}] =} dlqe (@var{a}, @var{g}, @var{c}, @var{sigw}, @var{sigv}, @var{z}) -Construct the linear quadratic estimator (Kalman filter) for the -discrete time system -@iftex -@tex -$$ - x_{k+1} = A x_k + B u_k + G w_k -$$ -$$ - y_k = C x_k + D u_k + w_k -$$ -@end tex -@end iftex -@ifinfo - -@example -x[k+1] = A x[k] + B u[k] + G w[k] - y[k] = C x[k] + D u[k] + w[k] -@end example - -@end ifinfo -where @var{w}, @var{v} are zero-mean gaussian noise processes with -respective intensities @code{@var{sigw} = cov (@var{w}, @var{w})} and -@code{@var{sigv} = cov (@var{v}, @var{v})}. - -If specified, @var{z} is @code{cov (@var{w}, @var{v})}. Otherwise -@code{cov (@var{w}, @var{v}) = 0}. - -The observer structure is -@iftex -@tex -$$ - z_{k+1} = A z_k + B u_k + k (y_k - C z_k - D u_k) -$$ -@end tex -@end iftex -@ifinfo - -@example -z[k+1] = A z[k] + B u[k] + k (y[k] - C z[k] - D u[k]) -@end example -@end ifinfo - -@noindent -The following values are returned: - -@table @var -@item l -The observer gain, -@iftex -@tex -$(A - ALC)$. -@end tex -@end iftex -@ifinfo -(@var{a} - @var{a}@var{l}@var{c}). -@end ifinfo -is stable. - -@item m -The Riccati equation solution. - -@item p -The estimate error covariance after the measurement update. - -@item e -The closed loop poles of -@iftex -@tex -$(A - ALC)$. -@end tex -@end iftex -@ifinfo -(@var{a} - @var{a}@var{l}@var{c}). -@end ifinfo -@end table -@end deftypefn - -@deftypefn {Function File} {[@var{k}, @var{p}, @var{e}] =} dlqr (@var{a}, @var{b}, @var{q}, @var{r}, @var{z}) -Construct the linear quadratic regulator for the discrete time system -@iftex -@tex -$$ - x_{k+1} = A x_k + B u_k -$$ -@end tex -@end iftex -@ifinfo - -@example -x[k+1] = A x[k] + B u[k] -@end example - -@end ifinfo -to minimize the cost functional -@iftex -@tex -$$ - J = \sum x^T Q x + u^T R u -$$ -@end tex -@end iftex -@ifinfo - -@example -J = Sum (x' Q x + u' R u) -@end example -@end ifinfo - -@noindent -@var{z} omitted or -@iftex -@tex -$$ - J = \sum x^T Q x + u^T R u + 2 x^T Z u -$$ -@end tex -@end iftex -@ifinfo - -@example -J = Sum (x' Q x + u' R u + 2 x' Z u) -@end example - -@end ifinfo -@var{z} included. - -The following values are returned: - -@table @var -@item k -The state feedback gain, -@iftex -@tex -$(A - B K)$ -@end tex -@end iftex -@ifinfo -(@var{a} - @var{b}@var{k}) -@end ifinfo -is stable. - -@item p -The solution of algebraic Riccati equation. - -@item e -The closed loop poles of -@iftex -@tex -$(A - B K)$. -@end tex -@end iftex -@ifinfo -(@var{a} - @var{b}@var{k}). -@end ifinfo -@end table -@strong{References} -@enumerate -@item Anderson and Moore, Optimal Control: Linear Quadratic Methods, - Prentice-Hall, 1990, pp. 56-58 -@item Kuo, Digital Control Systems, Harcourt Brace Jovanovich, 1992, - section 11-5-2. -@end enumerate -@end deftypefn - -@deftypefn {Function File } {[K}, @var{gain}, @var{Kc}, @var{Kf}, @var{Pc}, @var{Pf}] = h2syn(@var{Asys}, @var{nu}, @var{ny}, @var{tol}) - Design H2 optimal controller per procedure in - Doyle, Glover, Khargonekar, Francis, "State Space Solutions to Standard - H2 and Hinf Control Problems", IEEE TAC August 1989 - -@strong{Inputs} input system is passed as either -@table @var -@item Asys -system data structure (see ss2sys, sys2ss) -@itemize @bullet -@item controller is implemented for continuous time systems -@item controller is NOT implemented for discrete time systems -@end itemize -@item nu -number of controlled inputs -@item ny -number of measured outputs -@item tol -threshhold for 0. Default: 200*eps -@end table - -@strong{Outputs} -@table @var -@item K -system controller -@item gain -optimal closed loop gain -@item Kc -full information control (packed) -@item Kf -state estimator (packed) -@item Pc -ARE solution matrix for regulator subproblem -@item Pf -ARE solution matrix for filter subproblem -@end table -@end deftypefn - -@deftypefn {Function File } {@var{K} =} hinf_ctr(@var{dgs}, @var{F}, @var{H}, @var{Z}, @var{g}) -Called by @code{hinfsyn} to compute the H_inf optimal controller. - -@strong{Inputs} -@table @var -@item dgs -data structure returned by @code{is_dgkf} -@item F, H -feedback and filter gain (not partitioned) -@item g -final gamma value -@end table -@strong{Outputs} -controller K (system data structure) - -Do not attempt to use this at home; no argument checking performed. -@end deftypefn - -@deftypefn {Function File } {[@var{K}, @var{g}, @var{GW}, @var{Xinf}, @var{Yinf}] =} hinfsyn(@var{Asys}, @var{nu}, @var{ny}, @var{gmin}, @var{gmax}, @var{gtol}@{, @var{ptol}, @var{tol}@}) - -@strong{Inputs} input system is passed as either -@table @var -@item Asys -system data structure (see ss2sys, sys2ss) -@itemize @bullet -@item controller is implemented for continuous time systems -@item controller is NOT implemented for discrete time systems (see -bilinear transforms in @code{c2d}, @code{d2c}) -@end itemize -@item nu -number of controlled inputs -@item ny -number of measured outputs -@item gmin -initial lower bound on H-infinity optimal gain -@item gmax -initial upper bound on H-infinity optimal gain -@item gtol -gain threshhold. Routine quits when gmax/gmin < 1+tol -@item ptol -poles with abs(real(pole)) < ptol*||H|| (H is appropriate -Hamiltonian) are considered to be on the imaginary axis. -Default: 1e-9 -@item tol -threshhold for 0. Default: 200*eps - -@var{gmax}, @var{min}, @var{tol}, and @var{tol} must all be postive scalars. -@end table -@strong{Outputs} -@table @var -@item K -system controller -@item g -designed gain value -@item GW -closed loop system -@item Xinf -ARE solution matrix for regulator subproblem -@item Yinf -ARE solution matrix for filter subproblem -@end table - -@enumerate -@item Doyle, Glover, Khargonekar, Francis, "State Space Solutions - to Standard H2 and Hinf Control Problems," IEEE TAC August 1989 - -@item Maciejowksi, J.M., "Multivariable feedback design," - Addison-Wesley, 1989, ISBN 0-201-18243-2 - -@item Keith Glover and John C. Doyle, "State-space formulae for all - stabilizing controllers that satisfy and h-infinity-norm bound - and relations to risk sensitivity," - Systems & Control Letters 11, Oct. 1988, pp 167-172. -@end enumerate -@end deftypefn - -@deftypefn {Function File } {[@var{xx}, @var{err}] =} hinfsyn_c (@var{nn}, @var{ptol}, @var{s1}@{, @var{s2}@}) -used internally in hinfsyn to evaluate hamiltonian/symplectic - eigenvalue problems. - -@strong{WARNING} Argument checking not performed. - -@strong{Inputs} -@table @var -@item s1 @r{(alone)} -hamiltonian matrix -@item (s1,s2) @r{ as a pair} -symplectic matrix pencil -@end table -@strong{Outputs} -@table @var -@item xx: positive (semi-)definite solution of DARE (set to 0 if err <=2) -@item code: error: -@table @strong -@item 0 -no error -@item 1 - (s1): eigenvalues on imaginary axis - - (s1,s2): gen. eigenvalues on unit circle -@item 2 - unequal number of stable/antistable (generalized) eigenvalues -@item 3 -(s1): infinite entries in solution x - -(s1,s2): infinite entires in solution x or (I + R X) singular -@item 4 -x is not symmetric -@item 5 -x has negative eigenvalues -@end table -@end table - -Solution method: Either Laub's schur method or Symplectic GEP approach; -uses Van Dooren's code to re-order qz decompostion -(www.netlib.com - toms/590) - -See also: Ran and Rodman, "Stable Hermitian Solutions of Discrete - Algebraic Riccati Equations," Mathematics of Control, Signals and - Systems, Vol 5, no 2 (1992) pp 165-194. - -@end deftypefn - -@deftypefn {Function File} {[@var{retval}, @var{Pc}, @var{Pf}] =} hinfsyn_chk(@var{A}, @var{B1}, @var{B2}, @var{C1}, @var{C2}, @var{D12}, @var{D21}, @var{g}, @var{ptol}) - Called by @code{hinfsyn} to see if gain @var{g} satisfies conditions in -Theorem 3 of - Doyle, Glover, Khargonekar, Francis, "State Space Solutions to Standard - H2 and Hinf Control Problems", IEEE TAC August 1989 - -@strong{Warning} Do not attempt to use this at home; no argument checking performed. - -@strong{Inputs} as returned by @code{is_dgkf}, except for: -@table @var -@item g -candidate gain level -@item ptol - as in @code{hinfsyn} -@end table - - Outputs: - retval: = 1 if g exceeds optimal Hinf closed loop gain, else 0 - Pc: solution of "regulator" H-inf ARE - Pf: solution of "filter" H-inf ARE - -@end deftypefn - -@deftypefn {Function File} {[@var{k}, @var{p}, @var{e}] =} lqe (@var{a}, @var{g}, @var{c}, @var{sigw}, @var{sigv}, @var{z}) -Construct the linear quadratic estimator (Kalman filter) for the -continuous time system -@iftex -@tex -$$ - {dx\over dt} = A x + B u -$$ -$$ - y = C x + D u -$$ -@end tex -@end iftex -@ifinfo - -@example -dx --- = a x + b u -dt - -y = c x + d u -@end example - -@end ifinfo -where @var{w} and @var{v} are zero-mean gaussian noise processes with -respective intensities - -@example -sigw = cov (w, w) -sigv = cov (v, v) -@end example - -The optional argument @var{z} is the cross-covariance -@code{cov (@var{w}, @var{v})}. If it is omitted, -@code{cov (@var{w}, @var{v}) = 0} is assumed. - -Observer structure is @code{dz/dt = A z + B u + k (y - C z - D u)} - -The following values are returned: - -@table @var -@item k -The observer gain, -@iftex -@tex -$(A - K C)$ -@end tex -@end iftex -@ifinfo -(@var{a} - @var{k}@var{c}) -@end ifinfo -is stable. - -@item p -The solution of algebraic Riccati equation. - -@item e -The vector of closed loop poles of -@iftex -@tex -$(A - K C)$. -@end tex -@end iftex -@ifinfo -(@var{a} - @var{k}@var{c}). -@end ifinfo -@end table -@end deftypefn - -@deftypefn {Function File } {[@var{K}, @var{Q}, @var{P}, @var{Ee}, @var{Er}] =} lqg(@var{sys}, @var{Sigw}, @var{Sigv}, @var{Q}, @var{R}, @var{in_idx}) -Design a linear-quadratic-gaussian optimal controller for the system -@example -dx/dt = A x + B u + G w [w]=N(0,[Sigw 0 ]) - y = C x + v [v] ( 0 Sigv ]) -@end example -or -@example -x(k+1) = A x(k) + B u(k) + G w(k) [w]=N(0,[Sigw 0 ]) - y(k) = C x(k) + v(k) [v] ( 0 Sigv ]) -@end example - -@strong{Inputs} -@table @var -@item sys -system data structure -@item Sigw, Sigv -intensities of independent Gaussian noise processes (as above) -@item Q, R -state, control weighting respectively. Control ARE is -@item in_idx -indices of controlled inputs - - default: last dim(R) inputs are assumed to be controlled inputs, all - others are assumed to be noise inputs. -@end table -@strong{Outputs} -@table @var -@item K -system data structure format LQG optimal controller -(Obtain A,B,C matrices with @code{sys2ss}, @code{sys2tf}, or @code{sys2zp} as appropriate) -@item P -Solution of control (state feedback) algebraic Riccati equation -@item Q -Solution of estimation algebraic Riccati equation -@item Ee -estimator poles -@item Es -controller poles -@end table -@end deftypefn - -@deftypefn {Function File} {[@var{k}, @var{p}, @var{e}] =} lqr (@var{a}, @var{b}, @var{q}, @var{r}, @var{z}) -construct the linear quadratic regulator for the continuous time system -@iftex -@tex -$$ - {dx\over dt} = A x + B u -$$ -@end tex -@end iftex -@ifinfo - -@example -dx --- = A x + B u -dt -@end example - -@end ifinfo -to minimize the cost functional -@iftex -@tex -$$ - J = \int_0^\infty x^T Q x + u^T R u -$$ -@end tex -@end iftex -@ifinfo - -@example - infinity - / - J = | x' Q x + u' R u - / - t=0 -@end example -@end ifinfo - -@noindent -@var{z} omitted or -@iftex -@tex -$$ - J = \int_0^\infty x^T Q x + u^T R u + 2 x^T Z u -$$ -@end tex -@end iftex -@ifinfo - -@example - infinity - / - J = | x' Q x + u' R u + 2 x' Z u - / - t=0 -@end example - -@end ifinfo -@var{z} included. - -The following values are returned: - -@table @var -@item k -The state feedback gain, -@iftex -@tex -$(A - B K)$ -@end tex -@end iftex -@ifinfo -(@var{a} - @var{b}@var{k}) -@end ifinfo -is stable. - -@item p -The stabilizing solution of appropriate algebraic Riccati equation. - -@item e -The vector of the closed loop poles of -@iftex -@tex -$(A - B K)$. -@end tex -@end iftex -@ifinfo -(@var{a} - @var{b}@var{k}). -@end ifinfo -@end table -@end deftypefn - -@deftypefn {Function File } { } lsim (@var{sys}, @var{u}, @var{t}@{,@var{x0}@}) -Produce output for a linear simulation of a system - -Produces a plot for the output of the system, sys. - -U is an array that contains the system's inputs. Each column in u -corresponds to a different time step. Each row in u corresponds to a -different input. T is an array that contains the time index of the -system. T should be regularly spaced. If initial conditions are required -on the system, the x0 vector should be added to the argument list. - -When the lsim function is invoked with output parameters: -[y,x] = lsim(sys,u,t,[x0]) -a plot is not displayed, however, the data is returned in y = system output -and x = system states. -@end deftypefn - -@deftypefn {Function File } { @var{K} =} place (@var{sys}, @var{P}) -Computes the matrix K such that if the state -is feedback with gain K, then the eigenvalues of the closed loop -system (i.e. A-BK) are those specified in the vector P. - -Version: Beta (May-1997): If you have any comments, please let me know. - (see the file place.m for my address) - -Written by: Jose Daniel Munoz Frias. -@end deftypefn - -@node misc, , cacsd, Control Theory -@section Miscellaneous Functions (Not yet properly filed/documented) - - -@deftypefn{Function File } { @var{axvec} =} axis2dlim (@var{axdata}) - determine axis limits for 2-d data(column vectors); leaves a 10% margin - around the plots. - puts in margins of +/- 0.1 if data is one dimensional (or a single point) - -@strong{Inputs} - @var{axdata} nx2 matrix of data [x,y] - -@strong{Outputs} - @var{axvec} vector of axis limits appropriate for call to axis() function -@end deftypefn - -@deftypefn {Function File } { outputs =} mb ( inputs ) -@format - $Revision: 1.9 $ - - -@end format -@end deftypefn - -@deftypefn {Function File } { outputs =} moddemo ( inputs ) -@format - Octave Controls toolbox demo: Model Manipulations demo - Written by David Clem August 15, 1994 - - -@end format -@end deftypefn - -@deftypefn {Function File } { outputs =} prompt ( inputs ) -@format - function prompt([str]) - Prompt user to continue - str: input string. Default value: "\n ---- Press a key to continue ---" - Written by David Clem August 15, 1994 - Modified A. S. Hodel June 1995 - - -@end format -@end deftypefn - -@deftypefn {Function File } { outputs =} rldemo ( inputs ) -@end deftypefn - -@deftypefn {Function File } { outputs =} rlocus ( inputs ) -@format - [rldata, k] = rlocus(sys[,increment,min_k,max_k]) - Displays root locus plot of the specified SISO system. - - ----- --- -------- - --->| + |---|k|---->| SISO |-----------> - ----- --- -------- | - - ^ | - |_____________________________| - -inputs: sys = system data structure - min_k, max_k,increment: minimum, maximum values of k and - the increment used in computing gain values - Outputs: plots the root locus to the screen. - rldata: Data points plotted column 1: real values, column 2: imaginary - values) - k: gains for real axis break points. - - -@end format -@end deftypefn - -@deftypefn {Function File } { outputs =} sortcom ( inputs ) -@format - [yy,idx] = sortcom(xx[,opt]): sort a complex vector - xx: complex vector - opt: sorting option: - "re": real part (default) - "mag": by magnitude - "im": by imaginary part - - if opt != "im" then complex conjugate pairs are grouped together, - a - jb followed by a + jb. - yy: sorted values - idx: permutation vector: yy = xx(idx) - - -@end format -@end deftypefn - -@deftypefn {Function File } { outputs =} ss2tf ( inputs ) -@format - [num,den] = ss2tf(a,b,c,d) - Conversion from tranfer function to state-space. - The state space system - . - x = Ax + Bu - y = Cx + Du - - is converted to a transfer function - - num(s) - G(s)=------- - den(s) - - used internally in system data structure format manipulations - - -@end format -@end deftypefn - -@deftypefn {Function File } { outputs =} ss2zp ( inputs ) -@format - Converts a state space representation to a set of poles and zeros. - - [pol,zer,k] = ss2zp(a,b,c,d) returns the poles and zeros of the state space - system (a,b,c,d). K is a gain associated with the zeros. - - used internally in system data structure format manipulations - - -@end format -@end deftypefn - -@deftypefn {Function File } { outputs =} starp ( inputs ) -@format - - [sys] = starp(P, K, ny, nu) - - Redheffer star product or upper/lower LFT, respectively. - - - +-------+ - --------->| |---------> - | P | - +--->| |---+ ny - | +-------+ | - +-------------------+ - | | - +----------------+ | - | | - | +-------+ | - +--->| |------+ nu - | K | - --------->| |---------> - +-------+ - - If ny and nu "consume" all inputs and outputs of K then the result - is a lower fractional transformation. If ny and nu "consume" all - inputs and outputs of P then the result is an upper fractional - transformation. - - ny and/or nu may be negative (= negative feedback) -@end format -@end deftypefn -@deftypefn {Function File } { outputs =} susball ( inputs ) -@format - -@end format -@end deftypefn -@deftypefn {Function File } { outputs =} swap ( inputs ) -@format - [a1,b1] = swap(a,b) - interchange a and b - - -@end format -@end deftypefn -@deftypefn {Function File } { outputs =} swapcols ( inputs ) -@format - function B = swapcols(A) - permute columns of A into reverse order - - -@end format -@end deftypefn -@deftypefn {Function File } { outputs =} swaprows ( inputs ) -@format - function B = swaprows(A) - permute rows of A into reverse order - - -@end format -@end deftypefn - -@deftypefn {Function File } { outputs =} tf2ss ( inputs ) -@format - Conversion from tranfer function to state-space. - The state space system - . - x = Ax + Bu - y = Cx + Du - - is obtained from a transfer function - - num(s) - G(s)=------- - den(s) - - via the function call [a,b,c,d] = tf2ss(num,den). - The vector 'den' must contain only one row, whereas the vector 'num' - may contain as many rows as there are outputs of the system 'y'. - The state space system matrices obtained from this function will be - in controllable canonical form as described in "Modern Control Theory", - [Brogan, 1991]. - - -@end format -@end deftypefn - - -@deftypefn {Function File } { outputs =} tf2zp ( inputs ) -@format - Converts transfer functions to poles / zeros. - - [zer,pol,k] = tf2zp(num,den) returns the zeros and poles of the SISO system - defined by num/den. K is a gain associated with the system zeros. - - -@end format -@end deftypefn - -@deftypefn {Function File } { } zp2ss -Conversion from zero / pole to state space. -The state space system -@example -. -x = Ax + Bu -y = Cx + Du -@end example -is obtained from a vector of zeros and a vector of poles via the -function call @code{[a,b,c,d] = zp2ss(zer,pol,k)}. -The vectors @samp{zer} and -@samp{pol} may either be row or column vectors. Each zero and pole that -has an imaginary part must have a conjugate in the list. -The number of zeros must not exceed the number of poles. -@samp{k} is @code{zp}-form leading coefficient. -@end deftypefn - -@deftypefn {Function File } { [@var{poly}, @var{rvals}] =} zp2ssg2 (@var{rvals}) -Used internally in @code{zp2ss} -Extract 2 values from @var{rvals} (if possible) and construct - a polynomial with those roots. -@end deftypefn - -@deftypefn {Function File } { } zp2tf - Converts zeros / poles to a transfer function. - -@code{[num,den] = zp2tf(zer,pol,k)} forms the transfer function -@code{num/den} from the vectors of poles and zeros. -@end deftypefn - diff --git a/doc/interpreter/control.txi b/doc/interpreter/control.txi new file mode 100644 --- /dev/null +++ b/doc/interpreter/control.txi @@ -0,0 +1,3571 @@ +@c Copyright (C) 1996, 1997 John W. Eaton +@c This is part of the Octave manual. +@c For copying conditions, see the file gpl.texi. + +@node Control Theory, Signal Processing, Polynomial Manipulations, Top +@chapter Control Theory + +The Octave Control Systems Toolbox (OCST) was initially developed +by Dr.@: A. Scottedward Hodel +@email{a.s.hodel@@eng.auburn.edu} with the assistance +of his students +@itemize @bullet +@item R. Bruce Tenison @email{btenison@@dibbs.net}, +@item David C. Clem, +@item John E. Ingram @email{John.Ingram@@sea.siemans.com}, and +@item Kristi McGowan. +@end itemize +This development was supported in part by NASA's Marshall Space Flight +Center as part of an in-house CACSD environment. Additional important +contributions were made by Dr. Kai Mueller @email{mueller@@ifr.ing.tu-bs.de} +and Jose Daniel Munoz Frias (@code{place.m}). + +An on-line menu-driven tutorial is available via @ref{DEMOcontrol}; +beginning OCST users should start with this program. + +@menu +* OCST demonstration/tutorial:DEMOcontrol. +* System Data Structure:sysstruct. +* System Construction and Interface Functions:sysinterface. +* System display functions:sysdisp. +* Block Diagram Manipulations:blockdiag. +* Numerical Functions:numerical. +* System Analysis-Properties:sysprop. +* System Analysis-Time Domain:systime. +* System Analysis-Frequency Domain:sysfreq. +* Controller Design:cacsd. +* Miscellaneous Functions:misc. +@end menu + +@node DEMOcontrol, sysstruct, Control Theory, Control Theory +@unnumberedsec OCST demo program +@deftypefn {Function File } { } DEMOcontrol +Octave Control Systems Toolbox demo/tutorial program. The demo +allows the user to select among several categories of OCST function: +@example +@group +octave:1> DEMOcontrol + O C T A V E C O N T R O L S Y S T E M S T O O L B O X +Octave Controls System Toolbox Demo + + [ 1] System representation + [ 2] Block diagram manipulations + [ 3] Frequency response functions + [ 4] State space analysis functions + [ 5] Root locus functions + [ 6] LQG/H2/Hinfinity functions + [ 7] End +@end group +@end example +Command examples are interactively run for users to observe the use +of OCST functions. +@end deftypefn + +@node sysstruct, sysinterface, DEMOcontrol, Control Theory +@section System Data Structure +@menu +* Demo program:sysrepdemo. +* Variables common to all OCST system formats:sysstructvars. +* tf format variables:sysstructtf. +* zp format variables:sysstructzp. +* ss format variables:sysstructss. +@end menu +The OCST stores all dynamic systems in +a single data structure format that can represent continuous systems, +discrete-systems, and mixed (hybrid) systems in state-space form, and +can also represent purely continuous/discrete systems in either +transfer function or pole-zero form. In order to +provide more flexibility in treatment of discrete/hybrid systems, the +OCST also keeps a record of which system outputs are sampled. + +Octave structures are accessed with a syntax much like that used +by the C programming language. For consistency in +use of the data structure used in the OCST, it is recommended that +the system structure access m-files be used (@xref{sysinterface}). +Some elements of the data structure are absent depending on the internal +system representation(s) used. More than one system representation +can be used for SISO systems; the OCST m-files ensure that all representations +used are consistent with one another. + +@node sysrepdemo, sysstructvars, sysstruct, sysstruct +@unnumberedsec System representation demo program +@deftypefn {Function File } {} sysrepdemo +Tutorial for the use of the system data structure functions. +@end deftypefn + +@node sysstructvars, sysstructtf, sysrepdemo, sysstruct +@subsection Variables common to all OCST system formats + +The data structure elements (and variable types) common to all system +representations are listed below; examples of the initialization +and use of the system data structures are given in subsequent sections and +in the online demo @code{DEMOcontrol}. +@table @var +@item n,nz +The respective number of continuous and discrete states +in the system (scalar) + +@item inname, outname +list of name(s) of the system input, output signal(s). (list of strings) + +@item sys + System status vector. (vector) + +This vector indicates both what + representation was used to initialize the system data structure + (called the primary system type) and which other representations + are currently up-to-date with the primary system type (@xref{sysupdate}). + +@table @var + +@item sys(0) +primary system type + + =0 for tf form (initialized with @code{tf2sys} or @code{fir2sys}) + + =1 for zp form (initialized with @code{zp2sys}) + + =2 for ss form (initialized with @code{ss2sys}) + +@item sys(1:3) + boolean flags to indicate whether tf, zp, or ss, respectively, + are ``up to date" (whether it is safe to use the variables + associated with these representations). +These flags are changed when calls are made to the @code{sysupdate} command. +@end table + +@item tsam + Discrete time sampling period (nonnegative scalar). + @var{tsam} is set to 0 for continuous time systems. + +@item yd + Discrete-time output list (vector) + + indicates which outputs are discrete time (i.e., + produced by D/A converters) and which are continuous time. + yd(ii) = 0 if output ii is continuous, = 1 if discrete. +@end table + +The remaining variables of the system data structure are only present +if the corresponding entry of the @code{sys} vector is true (=1). + +@node sysstructtf, sysstructzp, sysstructvars, sysstruct +@subsection @code{tf} format variables + +@table @var + +@item num + numerator coefficients (vector) + +@item den + denominator coefficients (vector) + +@end table + +@node sysstructzp, sysstructss, sysstructtf, sysstruct +@subsection @code{zp} format variables +@table @var +@item zer + system zeros (vector) + +@item pol + system poles (vector) + +@item k + leading coefficient (scalar) + +@end table + +@node sysstructss, , sysstructzp, sysstruct +@subsection @code{ss} format variables +@table @var +@item a,b,c,d +The usual state-space matrices. If a system has both + continuous and discrete states, they are sorted so that + continuous states come first, then discrete states + +@strong{Note} some functions (e.g., @code{bode}, @code{hinfsyn}) +will not accept systems with both discrete and continuous states/outputs + +@item stname +names of system states (list of strings) + +@end table + +@node sysinterface, sysdisp, sysstruct, Control Theory +@section System Construction and Interface Functions + +Construction and manipulations of the OCST system data structure +(@xref{sysstruct}) requires attention to many details in order +to ensure that data structure contents remain consistent. Users +are strongly encouraged to use the system interface functions +in this section. Functions for the formatted display in of system +data structures are given in @ref{sysdisp}. + +@menu +* Finite impulse response system interface functions:fir2sys. +* sys2fir:: +* State space system interface functions:ss2sys. +* sys2ss:: +* Transfer function system interface functions:tf2sys. +* sys2tf:: +* Zero-pole system interface functions:zp2sys. +* sys2zp:: +* Data structure access functions:structaccess. +* Data structure internal functions:structintern +@end menu + +@node fir2sys,sys2fir,sysinterface,sysinterface +@subsection Finite impulse response system interface functions + +@deftypefn {Function File } { @var{sys} =} fir2sys ( @var{num}@{, @var{tsam}, @var{inname}, @var{outname} @} ) + construct a system data structure from FIR description + +@strong{Inputs:} +@table @var +@item num + vector of coefficients @math{[c_0 c_1 ... c_n]} +of the SISO FIR transfer function +@ifinfo + +C(z) = c0 + c1*z^@{-1@} + c2*z^@{-2@} + ... + znz^@{-n@} + +@end ifinfo +@iftex +@tex +$$C(z) = c0 + c1*z^{-1} + c2*z^{-2} + ... + znz^{-n}$$ +@end tex +@end iftex + +@item tsam + sampling time (default: 1) + +@item inname +name of input signal; may be a string or a list with a single entry. + +@item outname + name of output signal; may be a string or a list with a single entry. +@end table + +@strong{Outputs} + @var{sys} (system data structure) + +@strong{Example} +@example +octave:1> sys = fir2sys([1 -1 2 4],0.342,"A/D input","filter output"); +octave:2> sysout(sys) +Input(s) + 1: A/D input + +Output(s): + 1: filter output (discrete) + +Sampling interval: 0.342 +transfer function form: +1*z^3 - 1*z^2 + 2*z^1 + 4 +------------------------- +1*z^3 + 0*z^2 + 0*z^1 + 0 +@end example +@end deftypefn + +@node sys2fir,ss2sys,fir2sys, sysinterface +@deftypefn {Function File } {[@var{c}, @var{tsam}, @var{input}, @var{output}] =} sys2fir (@var{sys}) + +Extract FIR data from system data structure; see @ref{fir2sys} for +parameter descriptions. + +@end deftypefn + + +@node ss2sys, sys2ss, sys2fir, sysinterface +@subsection State space system interface functions +@deftypefn {Function File } { @var{sys} =} ss2sys (@var{a},@var{b},@var{c}@{,@var{d}, @var{tsam}, @var{n}, @var{nz}, @var{stname}, @var{inname}, @var{outname}, @var{outlist}@}) + Create system structure from state-space data. May be continous, + discrete, or mixed (sampeld-data) + +@strong{Inputs} +@table @var +@item a, b, c, d + usual state space matrices. + + default: @var{d} = zero matrix + +@item tsam + sampling rate. Default: @math{tsam = 0} (continuous system) + +@item n, nz + number of continuous, discrete states in the system + + default: +@table @var +@item tsam = 0 +@math{n = @code{rows}(@var{a})}, @math{nz = 0} + +@item tsam > 0 +@math{ n = 0}, @math{nz = @code{rows}(@var{a})} + + see below for system partitioning + +@end table + +@item stname + list of strings of state signal names + + default (@var{stname}=[] on input): @code{x_n} for continuous states, + @code{xd_n} for discrete states + +@item inname + list of strings of input signal names + + default (@var{inname} = [] on input): @code{u_n} + +@item outname + list of strings of input signal names + + default (@var{outname} = [] on input): @code{y_n} + +@item outlist + + list of indices of outputs y that are sampled + + default: +@table @var +@item tsam = 0 +@math{outlist = []} +@item tsam > 0 +@math{outlist = 1:@code{rows}(@var{c})} +@end table + +Unlike states, discrete/continous outputs may appear in any order. + +@strong{Note} @code{sys2ss} returns a vector @var{yd} where +@var{yd}(@var{outlist}) = 1; all other entries of @var{yd} are 0. + +@end table + +@strong{Outputs} +@var{outsys} = system data structure + +@strong{System partitioning} + + Suppose for simplicity that outlist specified + that the first several outputs were continuous and the remaining outputs + were discrete. Then the system is partitioned as +@example +@group +x = [ xc ] (n x 1) + [ xd ] (nz x 1 discrete states) +a = [ acc acd ] b = [ bc ] + [ adc add ] [ bd ] +c = [ ccc ccd ] d = [ dc ] + [ cdc cdd ] [ dd ] + + (cdc = c(outlist,1:n), etc.) +@end group +@end example +with dynamic equations: +@ifinfo +@math{ d/dt xc(t) = acc*xc(t) + acd*xd(k*tsam) + bc*u(t)} + +@math{ xd((k+1)*tsam) = adc*xc(k*tsam) + add*xd(k*tsam) + bd*u(k*tsam)} + +@math{ yc(t) = ccc*xc(t) + ccd*xd(k*tsam) + dc*u(t)} + +@math{ yd(k*tsam) = cdc*xc(k*tsam) + cdd*xd(k*tsam) + dd*u(k*tsam)} +@end ifinfo +@iftex +@tex +$$\eqalign{ +{d \over dt} x_c(t) + & = a_{cc} x_c(t) + a_{cd} x_d(k*t_{sam}) + bc*u(t) \cr +x_d((k+1)*t_{sam}) + & = a_{dc} x_c(k t_{sam}) + a_{dd} x_d(k t_{sam}) + b_d u(k t_{sam}) \cr +y_c(t) + & = c_{cc} x_c(t) + c_{cd} x_d(k t_{sam}) + d_c u(t) \cr +y_d(k t_{sam}) + & = c_{dc} x_c(k t_{sam}) + c_{dd} x_d(k t_{sam}) + d_d u(k t_{sam}) +}$$ +@end tex +@end iftex + +@strong{Signal partitions} +@example +@group + | continuous | discrete | +---------------------------------------------------- +states | stname(1:n,:) | stname((n+1):(n+nz),:) | +---------------------------------------------------- +outputs | outname(cout,:) | outname(outlist,:) | +---------------------------------------------------- +@end group +@end example +where @math{cout} is the list of in 1:@code{rows}(@var{p}) +that are not contained in outlist. (Discrete/continuous outputs +may be entered in any order desired by the user.) + +@strong{Example} +@example +octave:1> a = [1 2 3; 4 5 6; 7 8 10]; +octave:2> b = [0 0 ; 0 1 ; 1 0]; +octave:3> c = eye(3); +octave:4> sys = ss2sys(a,b,c,[],0,3,0,list("volts","amps","joules")); +octave:5> sysout(sys); +Input(s) + 1: u_1 + 2: u_2 + +Output(s): + 1: y_1 + 2: y_2 + 3: y_3 + +state-space form: +3 continuous states, 0 discrete states +State(s): + 1: volts + 2: amps + 3: joules + +A matrix: 3 x 3 + 1 2 3 + 4 5 6 + 7 8 10 +B matrix: 3 x 2 + 0 0 + 0 1 + 1 0 +C matrix: 3 x 3 + 1 0 0 + 0 1 0 + 0 0 1 +D matrix: 3 x 3 + 0 0 + 0 0 + 0 0 +@end example +Notice that the @var{D} matrix is constructed by default to the +correct dimensions. Default input and output signals names were assigned +since none were given. + +@end deftypefn + +@node sys2ss,tf2sys,ss2sys,sysinterface +@deftypefn {Function File } {[@var{a},@var{b},@var{c},@var{d},@var{tsam},@var{n},@var{nz},@var{stname},@var{inname},@var{outname},@var{yd}] =} sys2ss (@var{sys}) +Extract state space representation from system data structure. + +@strong{Inputs} +@var{sys} system data structure (@xref{sysstruct}) + +@strong{Outputs} +@table @var +@item a,b,c,d + state space matrices for sys + +@item tsam + sampling time of sys (0 if continuous) + +@item n, nz + number of continuous, discrete states (discrete states come + last in state vector @var{x}) + +@item stname, inname, outname + signal names (lists of strings); names of states, + inputs, and outputs, respectively + +@item yd + binary vector; @var{yd}(@var{ii}) is 1 if output @var{y}(@var{ii})$ + is discrete (sampled); otherwise @var{yd}(@var{ii}) 0. + +@end table + +@strong{Example} +@example +octave:1> sys=tf2sys([1 2],[3 4 5]); +octave:2> [a,b,c,d] = sys2ss(sys) +a = + 0.00000 1.00000 + -1.66667 -1.33333 +b = + 0 + 1 +c = 0.66667 0.33333 +d = 0 +@end example +@end deftypefn + +@node tf2sys,sys2tf,sys2ss,sysinterface +@subsection Transfer function system interface functions +@deftypefn {Function File } { @var{sys} = } tf2sys( @var{num}, @var{den} @{, @var{tsam}, @var{inname}, @var{outname} @}) + build system data structure from transfer function format data + +@strong{Inputs} +@table @var +@item num, den + coefficients of numerator/denominator polynomials +@item tsam + sampling interval. default: 0 (continuous time) +@item inname, outname + input/output signal names; may be a string or list with a single string +entry. +@end table + +@strong{Outputs} + @var{sys} = system data structure + +@strong{Example} +@example +octave:1> sys=tf2sys([2 1],[1 2 1],0.1); +octave:2> sysout(sys) +Input(s) + 1: u_1 +Output(s): + 1: y_1 (discrete) +Sampling interval: 0.1 +transfer function form: +2*z^1 + 1 +----------------- +1*z^2 + 2*z^1 + 1 +@end example +@end deftypefn + +@node sys2tf,zp2sys,tf2sys,sysinterface +@deftypefn {Function File } {[@var{num},@var{den},@var{tsam},@var{inname},@var{outname}] =} sys2tf (@var{sys}) +Extract transfer function data from a system data structure + +See @ref{tf2sys} for parameter descriptions. + +@strong{Example} +@example +octave:1> sys=ss2sys([1 -2; -1.1,-2.1],[0;1],[1 1]); +octave:2> [num,den] = sys2tf(sys) +num = 1.0000 -3.0000 +den = 1.0000 1.1000 -4.3000 +@end example +@end deftypefn + +@node zp2sys,sys2zp,sys2tf,sysinterface +@subsection Zero-pole system interface functions + +@deftypefn {Function File } { @var{sys} =} zp2sys (@var{zer},@var{pol},@var{k}@{,@var{tsam},@var{inname},@var{outname}@}) + Create system data structure from zero-pole data + +@strong{Inputs} +@table @var +@item zer + vector of system zeros +@item pol + vector of system poles +@item k + scalar leading coefficient +@item tsam + sampling period. default: 0 (continuous system) +@item inname, outname + input/output signal names (lists of strings) +@end table + +@strong{Outputs} + sys: system data structure + +@strong{Example} +@example +octave:1> sys=zp2sys([1 -1],[-2 -2 0],1); +octave:2> sysout(sys) +Input(s) + 1: u_1 +Output(s): + 1: y_1 +zero-pole form: +1 (s - 1) (s + 1) +----------------- +s (s + 2) (s + 2) +@end example +@end deftypefn + +@node sys2zp, structaccess, zp2sys, sysinterface +@deftypefn {Function File } {[@var{zer}, @var{pol}, @var{k}, @var{tsam}, @var{inname}, @var{outname}] =} sys2zp (@var{sys}) +Extract zero/pole/leading coefficient information from a system data +structure + +See @ref{zp2sys} for parameter descriptions. + +@strong{Example} +@example +octave:1> sys=ss2sys([1 -2; -1.1,-2.1],[0;1],[1 1]); +octave:2> [zer,pol,k] = sys2zp(sys) +zer = 3.0000 +pol = + -2.6953 + 1.5953 +k = 1 +@end example +@end deftypefn + +@node structaccess, structintern, sys2zp, sysinterface +@subsection Data structure access functions + +@menu +* syschnames:: +* syschtsam:: +* sysdimensions:: +* sysgetsignals:: +* sysgettsam:: +* sysgettype:: +* syssetsignals:: +* sysupdate:: +@end menu + +@node syschnames, syschtsam, structaccess, structaccess +@deftypefn {Function File } {@var{retsys} =} syschnames (@var{sys}, @var{opt}, @var{list}, @var{names}) +Superseded by @code{syssetsignals} + +@end deftypefn + +@node syschtsam, sysdimensions, syschnames, structaccess +@deftypefn {Function File } { retsys =} syschtsam ( sys,tsam ) +This function changes the sampling time (tsam) of the system. Exits with +an error if sys is purely continuous time. +@end deftypefn + +@node sysdimensions, sysgetsignals, syschtsam, structaccess +@deftypefn {Function File } { [@var{n}, @var{nz}, @var{m}, @var{p},@var{yd}] =} sysdimensions (@var{sys}@{, @var{opt}@}) + return the number of states, inputs, and/or outputs in the system @var{sys}. + +@strong{Inputs} +@table @var +@item sys + system data structure + +@item opt +String indicating which dimensions are desired. Values: +@table @code +@item "all" +(default) return all parameters as specified under Outputs below. + +@item "cst" +return @var{n}= number of continuous states + +@item "dst" +return @var{n}= number of discrete states + +@item "in" +return @var{n}= number of inputs + +@item "out" +return @var{n}= number of outputs +@end table +@end table + +@strong{Outputs} +@table @var +@item n + number of continuous states (or individual requested dimension as specified +by @var{opt}). +@item nz + number of discrete states +@item m + number of system inputs +@item p + number of system outputs +@item yd + binary vector; @var{yd}(@var{ii}) is nonzero if output @var{ii} is +discrete. +@math{yd(ii) = 0} if output @var{ii} is continous +@end table + +@end deftypefn + +@node sysgetsignals, sysgettsam, sysdimensions, structaccess +@deftypefn {Function File } {[@var{stname}, @var{inname}, @var{outname}, @var{yd}] =} sysgetsignals (@var{sys}) +@deftypefnx{Function File } { @var{siglist} =} sysgetsignals (@var{sys},@var{sigid}) +@deftypefnx{Function File } { @var{signame} =} sysgetsignals (@var{sys},@var{sigid},@var{signum}@{, @var{strflg}@}) + Get signal names from a system + +@strong{Inputs} +@table @var +@item sys + system data structure for the state space system + +@item sigid +signal id. String. Must be one of +@table @code +@item "in" +input signals +@item "out" +output signals +@item "st" +stage signals +@item "yd" +value of logical vector @var{yd} +@end table + +@item signum +Index of signal (or indices of signals if signum is a vector) + +@item strflg +flag to return a string instead of a list; Values: +@table @code +@item 0 +(default) return a list (even if signum is a scalar) + +@item 1 +return a string. Exits with an error if signum is not a scalar. +@end table + +@end table + +@strong{Outputs} +@table @bullet +@item If @var{sigid} is not specified +@table @var +@item stname, inname, outname + signal names (lists of strings); names of states, + inputs, and outputs, respectively +@item yd + binary vector; @var{yd}(@var{ii}) is nonzero if output @var{ii} is +discrete. +@end table + +@item If @var{sigid} is specified but @var{signum} is not specified, then +@table @code +@item sigid="in" +@var{siglist} is set to the list of input names + +@item sigid="out" +@var{siglist} is set to the list of output names + +@item sigid="st" +@var{siglist} is set to the list of state names + +stage signals +@item sigid="yd" +@var{siglist} is set to logical vector indicating discrete outputs; +@var{siglist(ii) = 0} indicates that output @var{ii} is continuous +(unsampled), otherwise it is discrete. + +@end table + +@item if the first three input arguments are specified, then @var{signame} is +a list of the specified signal names (@var{sigid} is @code{"in"}, +@code{"out"}, or @code{"st"}), or else the logical flag +indicating whether output(s) @var{signum} is(are) discrete (@var{sigval}=1) +or continuous (@var{sigval}=0). +@end table + +@strong{Examples} (From @code{sysrepdemo}) +@example +octave> sys=ss2sys(rand(4),rand(4,2),rand(3,4)); +octave> [Ast,Ain,Aout,Ayd] = sysgetsignals(sys) i # get all signal names +Ast = +( + [1] = x_1 + [2] = x_2 + [3] = x_3 + [4] = x_4 +) +Ain = +( + [1] = u_1 + [2] = u_2 +) +Aout = +( + [1] = y_1 + [2] = y_2 + [3] = y_3 +) +Ayd = + + 0 0 0 +octave> Ain = sysgetsignals(sys,"in") # get only input signal names +Ain = +( + [1] = u_1 + [2] = u_2 +) +octave> Aout = sysgetsignals(sys,"out",2) # get name of output 2 (in list) +Aout = +( + [1] = y_2 +) +octave> Aout = sysgetsignals(sys,"out",2,1) # get name of output 2 (as string) +Aout = y_2 +@end example + +@end deftypefn + +@node sysgettsam, sysgettype, sysgetsignals, structaccess +@deftypefn {Function File } { Tsam =} sysgettsam ( sys ) + return the sampling time of the system +@end deftypefn + +@node sysgettype, syssetsignals, sysgettsam, structaccess +@deftypefn {Function File } { @var{systype} =} sysgettype ( @var{sys} ) + return the initial system type of the system + +@strong{Inputs} + @var{sys}: system data structure + +@strong{Outputs} + @var{systype}: string indicating how the structure was initially + constructed: + values: @code{"ss"}, @code{"zp"}, or @code{"tf"} + +@strong{Note} FIR initialized systems return @code{systype="tf"}. + + +@end deftypefn + +@node syssetsignals, sysupdate, sysgettype, structaccess +@deftypefn {Function File } {@var{retsys} =} syssetsignals (@var{sys}, @var{opt}, @var{names}@{, @var{sig_idx}@}) + change the names of selected inputs, outputs and states. +@strong{Inputs} +@table @var +@item sys + system data structure + +@item opt +change default name (output) + +@table @code +@item "out" + change selected output names +@item "in" + change selected input names +@item "st" + change selected state names +@item "yd" + change selected outputs from discrete to continuous or + from continuous to discrete. +@end table + +@item names +@table @code +@item opt = "out", "in", or "st" + string or string array containing desired signal names or values. +@item opt = "yd" +To desired output continuous/discrete flag. +Set name to 0 for continuous, or 1 for discrete. +@end table +@item list + vector of indices of outputs, yd, inputs, or + states whose respective names should be changed. + + Default: replace entire list of names/entire yd vector. +@end table +@strong{Outputs} + @var{retsys=sys} with appropriate signal names changed + (or yd values, where appropriate) + + +@strong{Example} +@example +octave:1> sys=ss2sys([1 2; 3 4],[5;6],[7 8]); +octave:2> sys = syssetsignals(sys,"st",str2mat("Posx","Velx")); +octave:3> sysout(sys) +Input(s) + 1: u_1 +Output(s): + 1: y_1 +state-space form: +2 continuous states, 0 discrete states +State(s): + 1: Posx + 2: Velx +A matrix: 2 x 2 + 1 2 + 3 4 +B matrix: 2 x 1 + 5 + 6 +C matrix: 1 x 2 + 7 8 +D matrix: 1 x 1 +0 +@end example + +@end deftypefn + +@node sysupdate, , syssetsignals, structaccess +@deftypefn {Function File } { @var{sys} =} sysupdate ( @var{sys}, @var{opt} ) + Update the internal representation of a system. + +@strong{Inputs} +@table @var +@item sys: +system data structure +@item opt + string: +@table @code +@item "tf" +update transfer function form +@item "zp" +update zero-pole form +@item "ss" +update state space form +@item "all" +all of the above +@end table +@end table + +@strong{Outputs} +@var{retsys}: contains union of data in sys and requested data. +If requested data in sys is already up to date then retsys=sys. + +Conversion to @code{tf} or @code{zp} exits with an error if the system is + mixed continuous/digital. +@end deftypefn + +@node structintern, , structaccess, sysinterface +@subsection Data structure internal functions +@deftypefn {Function File } { } syschnamesl + used internally in syschnames +@end deftypefn + +@deftypefn {Function File } { @var{ioname} =} sysdefioname (@var{n},@var{str} @{,@var{m}@}) +return default input or output names given @var{n}, @var{str}, @var{m}. + @var{n} is the final value, @var{str} is the string prefix, and @var{m} +is start value + + used internally, minimal argument checking + +@strong{Example} @code{ioname = sysdefioname(5,"u",3)} +returns the list: +@example +ioname = +( + [1] = u_3 + [2] = u_4 + [3] = u_5 +) +@end example +@end deftypefn + +@deftypefn {Function File } { @var{stname} =} sysdefstname (@var{n}, @var{nz}) + return default state names given @var{n}, @var{nz} + + used internally, minimal argument checking +@end deftypefn + +@deftypefn {Function File } { @var{vec} = } tf2sysl (@var{vec}) + used internally in @ref{tf2sys}. + strip leading zero coefficients to get the true polynomial length +@end deftypefn + +@node sysdisp, blockdiag, sysinterface, Control Theory +@section System display functions + +@deftypefn {Function File } { } sysout ( @var{sys}@{, @var{opt}@}) + print out a system data structure in desired format +@table @var +@item sys + system data structure +@item opt +Display option +@table @code +@item [] + primary system form (default); see @ref{sysgettype}. +@item "ss" + state space form +@item "tf" + transfer function form +@item "zp" + zero-pole form +@item "all" + all of the above +@end table +@end table +@end deftypefn + +@deftypefn {Function File } { @var{y} =} polyout ( @var{c}@{, @var{x}@}) +write formatted polynomial +@example + c(x) = c(1) * x^n + ... + c(n) x + c(n+1) +@end example + to string @var{y} or to the screen (if @var{y} is omitted) + @var{x} defaults to the string @code{"s"} +@end deftypefn + +@deftypefn {Function File } { } tfout (@var{num}, @var{denom}@{, @var{x}@}) + print formatted transfer function @math{n(s)/d(s) } to the screen + @var{x} defaults to the string @code{"s"} +@end deftypefn + +@deftypefn {Function File } { } zpout (@var{zer}, @var{pol}, @var{k}@{, @var{x}@}) + print formatted zero-pole form to the screen. +@var{x} defaults to the string @code{"s"} +@end deftypefn + +@deftypefn {Function File } { } outlist (@var{lmat}@{, @var{tabchar}, @var{yd}, @var{ilist} @}) + Prints an enumerated list of strings. + internal use only; minimal argument checking performed + +@strong{Inputs} +@table @var +@item lmat + list of strings +@item tabchar + tab character (default: none) +@item yd + indices of strings to append with the string "(discrete)" + (used by @var{sysout}; minimal checking of this argument) + @math{yd = [] } indicates all outputs are continuous +@item ilist +index numbers to print with names. + +default: @code{1:rows(lmat)} +@end table + +@strong{Outputs} + prints the list to the screen, numbering each string in order. + +@end deftypefn + +@node blockdiag, numerical, sysdisp, Control Theory +@section Block Diagram Manipulations + +@xref{systime} + +Unless otherwise noted, all parameters (input,output) are +system data structures. +@menu +* buildssic:: +* jet707:: +* ord2:: +* parallel:: +* sysadd:: +* sysappend:: +* sysconnect:: +* syscont:: +* syscont_disc:: +* sysdisc:: +* sysdup:: +* sysgroup:: +* sysgroupn:: +* sysmult:: +* sysprune:: +* sysreorder:: +* sysscale:: +* syssub:: +@end menu + +@deftypefn {Function File } { outputs =} bddemo ( inputs ) + Octave Controls toolbox demo: Block Diagram Manipulations demo +@end deftypefn + +@node buildssic, jet707, blockdiag, blockdiag +@deftypefn {Function File } {[@var{sys}] =} buildssic(@var{Clst}, @var{Ulst}, @var{Olst}, @var{Ilst}, @var{s1}, @var{s2}, @var{s3}, @var{s4}, @var{s5}, @var{s6}, @var{s7}, @var{s8}) + +Contributed by Kai Mueller. + + Form an arbitrary complex (open or closed loop) system in + state-space form from several systems. "@code{buildssic}" can + easily (despite it's cryptic syntax) integrate transfer functions + from a complex block diagram into a single system with one call. + This function is especially useful for building open loop + interconnections for H_infinity and H2 designs or for closing + loops with these controllers. + + Although this function is general purpose, the use of "@code{sysgroup}" + "@code{sysmult}", "@code{sysconnect}" and the like is recommended for standard + operations since they can handle mixed discrete and continuous + systems and also the names of inputs, outputs, and states. + + The parameters consist of 4 lists that describe the connections + outputs and inputs and up to 8 systems s1-s8. + Format of the lists: +@table @var +@item Clst +connection list, describes the input signal of +each system. The maximum number of rows of Clst is +equal to the sum of all inputs of s1-s8. + +Example: +@code{[1 2 -1; 2 1 0]} ==> new input 1 is old inpout 1 ++ output 2 - output 1, new input 2 is old input 2 ++ output 1. The order of rows is arbitrary. + +@item Ulst + if not empty the old inputs in vector Ulst will + be appended to the outputs. You need this if you + want to "pull out" the input of a system. Elements + are input numbers of s1-s8. + +@item Olst + output list, specifiy the outputs of the resulting + systems. Elements are output numbers of s1-s8. + The numbers are alowed to be negative and may + appear in any order. An empty matrix means + all outputs. + +@item Ilst + input list, specifiy the inputs of the resulting + systems. Elements are input numbers of s1-s8. + The numbers are alowed to be negative and may + appear in any order. An empty matrix means + all inputs. +@end table + + Example: Very simple closed loop system. +@example +@group +w e +-----+ u +-----+ + --->o--*-->| K |--*-->| G |--*---> y + ^ | +-----+ | +-----+ | + - | | | | + | | +----------------> u + | | | + | +-------------------------|---> e + | | + +----------------------------+ +@end group +@end example + +The closed loop system GW can be optained by +@example +GW = buildssic([1 2; 2 -1], [2], [1 2 3], [2], G, K); +@end example +@table @var +@item Clst +(1. row) connect input 1 (G) with output 2 (K). +(2. row) connect input 2 (K) with neg. output 1 (G). +@item Ulst +append input of (2) K to the number of outputs. +@item Olst +Outputs are output of 1 (G), 2 (K) and appended output 3 (from Ulst). +@item Ilst +the only input is 2 (K). +@end table + +Here is a real example: +@example +@group + +----+ + -------------------->| W1 |---> v1 +z | +----+ +----|-------------+ || GW || => min. + | | vz infty + | +---+ v +----+ + *--->| G |--->O--*-->| W2 |---> v2 + | +---+ | +----+ + | | + | v + u y +@end group +@end example + +The closed loop system GW from [z; u]' to [v1; v2; y]' can be +obtained by (all SISO systems): +@example +GW = buildssic([1 4;2 4;3 1],[3],[2 3 5],[3 4],G,W1,W2,One); +@end example +where "One" is a unity gain (auxillary) function with order 0. +(e.g. @code{One = ugain(1);}) +@end deftypefn + +@node jet707, ord2, buildssic, blockdiag +@deftypefn {Function File } { @var{outsys} =} jet707 ( ) + Creates linearized state space model of a Boeing 707-321 aircraft + at v=80m/s. (M = 0.26, Ga0 = -3 deg, alpha0 = 4 deg, kappa = 50 deg) + System inputs: (1) thrust and (2) elevator angle + System outputs: (1) airspeed and (2) pitch angle + Ref: R. Brockhaus: Flugregelung (Flight Control), Springer, 1994 + + see also: ord2 + +Contributed by Kai Mueller +@end deftypefn + +@node ord2, parallel, jet707, blockdiag +@deftypefn {Function File } { @var{outsys} =} ord2 (@var{nfreq}, @var{damp}@{[, @var{gain}@}) + Creates a continuous 2nd order system with parameters: +@strong{Inputs} +@table @var +@item nfreq: natural frequency [Hz]. (not in rad/s) +@item damp: damping coefficient +@item gain: dc-gain + This is steady state value only for damp > 0. + gain is assumed to be 1.0 if ommitted. +@end table +@strong{Outputs} +@var{outsys} + system data structure has representation with @math{w = 2 * pi * nfreq}: +@example + / \ + | / -2w*damp -w \ / w \ | +G = | | |, | |, [ 0 gain ], 0 | + | \ w 0 / \ 0 / | + \ / +@end example +@strong{See also} @code{jet707} (MIMO example, Boeing 707-321 aircraft model) +@end deftypefn + +@node parallel, sysadd, ord2, blockdiag +@deftypefn {Function File } { @var{sysp} =} parallel(@var{Asys}, @var{Bsys}) +Forms the parallel connection of two systems. +@example + ____________________ + | ________ | +u ----->|----> | Asys |--->|----> y1 + | | -------- | + | | ________ | + |--->|----> | Bsys |--->|----> y2 + | -------- | + -------------------- + Ksys +@end example +@end deftypefn + +@node sysadd, sysappend, parallel, blockdiag +@deftypefn {Function File } { @var{sys} =} sysadd ( @var{Gsys},@var{Hsys}) +returns @var{sys} = @var{Gsys} + @var{Hsys}. +@itemize @bullet +@item Exits with +an error if @var{Gsys} and @var{Hsys} are not compatibly dimensioned. +@item Prints a warning message is system states have identical names; + duplicate names are given a suffix to make them unique. +@item @var{sys} input/output names are taken from @var{Gsys}. +@end itemize +@example +@group + ________ + ----| Gsys |--- +u | ---------- +| +----- (_)----> y + | ________ +| + ----| Hsys |--- + -------- +@end group +@end example +@end deftypefn + +@node sysappend, sysconnect, sysadd, blockdiag +@deftypefn {Function File } {@var{retsys} =} sysappend (@var{sys},@var{b}@{, @var{c}, @var{d}, @var{outname}, @var{inname}, @var{yd}@}) +appends new inputs and/or outputs to a system + +@strong{Inputs} +@table @var +@item sys +system data structure + +@item b +matrix to be appended to sys "B" matrix (empty if none) + +@item c +matrix to be appended to sys "C" matrix (empty if none) + +@item d +revised sys d matrix (can be passed as [] if the revised d is all zeros) + +@item outname +list of names for new outputs + +@item inname +list of names for new inputs + +@item yd +binary vector; @math{yd(ii)=0} indicates a continuous output; +@math{yd(ii)=1} indicates a discrete output. +@end table + +@strong{Outputs} @var{sys} +@example +@group + sys.b := [sys.b , b] + sys.c := [sys.c ] + [ c ] + sys.d := [sys.d | D12 ] + [D21 | D22 ] +@end group +@end example +where @var{D12}, @var{D21}, and @var{D22} are the appropriate dimensioned +blocks of the input parameter @var{d}. +@itemize @bullet +@item The leading block @var{D11} of @var{d} is ignored. +@item If @var{inname} and @var{outname} are not given as arguments, + the new inputs and outputs are be assigned default names. +@item @var{yd} is a binary vector of length rows(c) that indicates + continuous/sampled outputs. Default value for @var{yd} is: + +@item @var{sys} = continuous or mixed +@var{yd} = @code{zeros(1,rows(c))} + +@item @var{sys} = discrete +@var{yd} = @code{ones(1,rows(c))} + +@end itemize + +@end deftypefn + +@node sysconnect, syscont, sysappend, blockdiag +@deftypefn {Function File } {@var{retsys} =} sysconnect (@var{sys}, @var{out_idx},@var{in_idx}@{,@var{order}, @var{tol}@}) +Close the loop from specified outputs to respective specified inputs + +@strong{Inputs} +@table @var +@item sys +system data structure +@item out_idx, in_idx +list of connections indices; @math{y(out_idx(ii))} +is connected to @math{u(in_idx(ii))}. +@item order +logical flag (default = 0) +@table @code +@item 0 +leave inputs and outputs in their original order +@item 1 +permute inputs and outputs to the order shown in the diagram below +@end table +@item tol +tolerance for singularities in algebraic loops default: 200@var{eps} +@end table + +@strong{Outputs} + @var{sys}: resulting closed loop system. + +@strong{Method} +@code{sysconnect} internally permutes selected inputs, outputs as shown + below, closes the loop, and then permutes inputs and outputs back to their + original order +@example +@group + ____________________ + u_1 ----->| |----> y_1 + | sys | + old u_2 | | +u_2* ---->(+)--->| |----->y_2 +(in_idx) ^ -------------------| | (out_idx) + | | + ------------------------------- +@end group +@end example +The input that has the summing junction added to it has an * added to the end +of the input name. + +@end deftypefn + +@node syscont, syscont_disc, sysconnect, blockdiag + +@deftypefn {Function File} { [@var{csys}, @var{Acd}, @var{Ccd}] = } syscont (@var{sys}) +Extract the purely continuous subsystem of an input system. + +@strong{Inputs} +@var{sys} is a system data structure + +@strong{Outputs} +@table @var +@item csys + is the purely continuous input/output connections of @var{sys} +@item Acd, Ccd: + connections from discrete states to continuous states, + discrete states to continuous outputs, respectively. + + returns @var{csys} empty if no continuous/continous path exists +@end table + +@end deftypefn + +@node syscont_disc, sysdisc, syscont, blockdiag +@deftypefn {Function File } { [@var{n_tot}, @var{st_c}, @var{st_d}, @var{y_c}, @var{y_d}] =} syscont_disc(@var{sys}) +Used internally in syscont and sysdisc. + +@strong{Inputs} +@var{ sys} is a system data structure. + +@strong{Outputs} +@table @var +@item n_tot +total number of states +@item st_c +vector of continuous state indices (empty if none) +@item st_d +vector of discrete state indices (empty if none) +@item y_c +vector of continuous output indices +@item y_d +vector of discrete output indices +@end table + +@end deftypefn + +@node sysdisc, sysdup, syscont_disc, blockdiag +@deftypefn {Function File } { [@var{dsys}, @var{Adc}, @var{Cdc}] =} sysdisc (@var{sys}) + +@strong{Inputs} +@var{sys} = system data structure + +@strong{Outputs} +@table @var +@item dsys + purely discrete portion of sys (returned empty if there is + no purely discrete path from inputs to outputs) +@item Adc, Cdc + connections from continuous states to discrete states and discrete + outputs, respectively. +@end table + +@end deftypefn + +@node sysdup, sysgroup, sysdisc, blockdiag +@deftypefn {Function File } { @var{retsys} =} sysdup (@var{Asys}, @var{out_idx}, @var{in_idx}) + Duplicate specified input/output connections of a system + +@strong{Inputs} +@table @var +@item Asys + system data structure (@xref{ss2sys}) +@item out_idx,in_idx + list of connections indices; + duplicates are made of @var{y(out_idx(ii))} and @var{u(in_idx(ii))}. +@end table + +@strong{Outputs} +@var{retsys}: resulting closed loop system: + duplicated i/o names are appended with a @code{"+"} suffix. + + +@strong{Method} +@code{sysdup} creates copies of selected inputs and outputs as + shown below. u1/y1 is the set of original inputs/outputs, and + u2,y2 is the set of duplicated inputs/outputs in the order specified + in @var{in_idx}, @var{out_idx}, respectively +@example +@group + ____________________ +u1 ----->| |----> y1 + | Asys | +u2 ------>| |----->y2 +(in_idx) -------------------| (out_idx) +@end group +@end example + +@end deftypefn + +@node sysgroup, sysgroupn, sysdup, blockdiag +@deftypefn {Function File } { @var{sys} =} sysgroup ( @var{Asys}, @var{Bsys}) +Combines two systems into a single system + +@strong{Inputs} +@var{Asys}, @var{Bsys}: system data structures + +@strong{Outputs} + @math{sys = @r{block diag}(Asys,Bsys)} +@example +@group + __________________ + | ________ | +u1 ----->|--> | Asys |--->|----> y1 + | -------- | + | ________ | +u2 ----->|--> | Bsys |--->|----> y2 + | -------- | + ------------------ + Ksys +@end group +@end example +The function also rearranges the internal state-space realization of @var{sys} +so that the + continuous states come first and the discrete states come last. + If there are duplicate names, the second name has a unique suffix appended + on to the end of the name. + +@end deftypefn + +@node sysgroupn, sysmult, sysgroup, blockdiag +@deftypefn {Function File } { @var{names} =} sysgroupn (@var{names}) +Locate and mark duplicate names. Used internally in sysgroup (and elsewhere). +@end deftypefn + +@node sysmult, sysprune, sysgroupn, blockdiag +@deftypefn {Function File } { @var{sys} =} sysmult( @var{Asys}, @var{Bsys}) +Compute @math{sys = Asys*Bsys} (series connection): +@example +@group +u ---------- ---------- +--->| Bsys |---->| Asys |---> + ---------- ---------- +@end group +@end example +A warning occurs if there is direct feed-through +from an input of Bsys or a continuous state of Bsys through a discrete +output of Bsys to a continuous state or output in Asys (system data structure +does not recognize discrete inputs). +@end deftypefn + +@node sysprune, sysreorder, sysmult, blockdiag +@deftypefn {Function File } { @var{retsys} =} sysprune ( @var{Asys}, @var{out_idx}, @var{in_idx}) +Extract specified inputs/outputs from a system + +@strong{Inputs} +@table @var +@item Asys +system data structure +@item out_idx,in_idx + list of connections indices; the new + system has outputs y(out_idx(ii)) and inputs u(in_idx(ii)). + May select as [] (empty matrix) to specify all outputs/inputs. +@end table + +@strong{Outputs} +@var{retsys}: resulting system +@example +@group + ____________________ +u1 ------->| |----> y1 + (in_idx) | Asys | (out_idx) +u2 ------->| |----| y2 + (deleted)-------------------- (deleted) +@end group +@end example + +@end deftypefn + +@node sysreorder, sysscale, sysprune, blockdiag +@deftypefn {Function File } { @var{pv} =} sysreorder( @var{vlen}, @{var{list}) + +@strong{Inputs} +@var{vlen}=vector length, @var{list}= a subset of @code{[1:vlen]}, + +@strong{Outputs} + @var{pv}: a permutation vector to order elements of @code{[1:vlen]} in +@code{list} to the end of a vector. + + Used internally by @code{sysconnect} to permute vector elements to their + desired locations. +@end deftypefn + +@node sysscale, syssub, sysreorder, blockdiag +@deftypefn {Function File } {@var{sys} =} sysscale (@var{sys}, @var{outscale}, @var{inscale}@{, @var{outname}, @var{inname}@}) +scale inputs/outputs of a system. + +@strong{Inputs} + sys: structured system + outscale, inscale: constant matrices of appropriate dimension + +@strong{Outputs} +@var{sys}: resulting open loop system: +@example + ----------- ------- ----------- +u --->| inscale |--->| sys |--->| outscale |---> y + ----------- ------- ----------- +@end example + If the input names and output names (each a list of strings) +are not given and the scaling matrices + are not square, then default names will be given to the inputs and/or + outputs. + +A warning message is printed if outscale attempts to add continuous +system outputs to discrete system outputs; otherwise @var{yd} is +set appropriately in the returned value of @var{sys}. +@end deftypefn + +@node syssub, , sysscale, blockdiag +@deftypefn {Function File } { @var{sys} =} syssub (@var{Gsys}, @var{Hsys}) + returns @math{sys = Gsys - Hsys} + + Method: @var{Gsys} and @var{Hsys} are connected in parallel + The input vector is connected to both systems; the outputs are + subtracted. Returned system names are those of @var{Gsys}. +@example +@group + ________ + ----| Gsys |--- +u | ---------- +| +----- (_)----> y + | ________ -| + ----| Hsys |--- + -------- +@end group +@end example +@end deftypefn + +@deftypefn {Function File } { @var{outsys} =} ugain(n) + Creates a system with unity gain, no states. + This trivial system is sometimes needed to create arbitrary + complex systems from simple systems with buildssic. + Watch out if you are forming sampled systems since "ugain" + does not contain a sampling period. + +See also: hinfdemo (MIMO H_infinty example, Boeing 707-321 aircraft model) + +@end deftypefn + +@deftypefn {Function File } { @var{wsys} =} wgt1o (@var{vl}, @var{vh}, @var{fc}) +State space description of a first order weighting function. + + Weighting function are needed by the H2/H_infinity design procedure. + These function are part of thye augmented plant P (see hinfdemo + for an applicattion example). + + vl = Gain @@ low frequencies + + vh = Gain @@ high frequencies + + fc = Corner frequency (in Hz, *not* in rad/sec) +@end deftypefn + +@node numerical, sysprop, blockdiag, Control Theory +@section Numerical Functions +@deftypefn {Function File} {} are (@var{a}, @var{b}, @var{c}, @var{opt}) +Solve the algebraic Riccati equation +@iftex +@tex +$$ +A^TX + XA - XBX + C = 0 +$$ +@end tex +@end iftex +@ifinfo +@example +a' * x + x * a - x * b * x + c = 0 +@end example +@end ifinfo + +@strong{Inputs} +@noindent +for identically dimensioned square matrices +@table @var +@item a +@var{n}x@var{n} matrix. +@item b + @var{n}x@var{n} matrix or @var{n}x@var{m} matrix; in the latter case + @var{b} is replaced by @math{b:=b*b'}. +@item c + @var{n}x@var{n} matrix or @var{p}x@var{m} matrix; in the latter case + @var{c} is replaced by @math{c:=c'*c}. +@item opt +(optional argument; default = @code{"B"}): +String option passed to @code{balance} prior to ordered Schur decomposition. +@end table + +@strong{Outputs} +@var{x}: solution of the ARE. + +@strong{Method} +Laub's Schur method (IEEE Transactions on +Automatic Control, 1979) is applied to the appropriate Hamiltonian +matrix. + +@end deftypefn + +@deftypefn {Function File} {} dare (@var{a}, @var{b}, @var{c}, @var{r}, @var{opt}) + +Return the solution, @var{x} of the discrete-time algebraic Riccati +equation +@iftex +@tex +$$ +A^TXA - X + A^TXB (R + B^TXB)^{-1} B^TXA + C = 0 +$$ +@end tex +@end iftex +@ifinfo +@example +a' x a - x + a' x b (r + b' x b)^(-1) b' x a + c = 0 +@end example +@end ifinfo +@noindent + +@strong{Inputs} +@table @var +@item a +@var{n} by @var{n}. + +@item b +@var{n} by @var{m}. + +@item c +@var{n} by @var{n}, symmetric positive semidefinite, or @var{p} by @var{n}. +In the latter case @math{c:=c'*c} is used. + +@item r +@var{m} by @var{m}, symmetric positive definite (invertible). + +@item opt +(optional argument; default = @code{"B"}): +String option passed to @code{balance} prior to ordered @var{QZ} decomposition. +@end table + +@strong{Outputs} +@var{x} solution of DARE. + +@strong{Method} +Generalized eigenvalue approach (Van Dooren; SIAM J. + Sci. Stat. Comput., Vol 2) applied to the appropriate symplectic pencil. + + See also: Ran and Rodman, "Stable Hermitian Solutions of Discrete + Algebraic Riccati Equations," Mathematics of Control, Signals and + Systems, Vol 5, no 2 (1992) pp 165-194. + +@end deftypefn + +@deftypefn {Function File } { @var{m} =} dgram ( @var{a}, @var{b}) + Return controllability grammian of discrete time system +@example + x(k+1) = a x(k) + b u(k) +@end example + +@strong{Inputs} +@table @var +@item a +@var{n} by @var{n} matrix +@item b +@var{n} by @var{m} matrix +@end table + +@strong{Outputs} +@var{m} (@var{n} by @var{n}) satisfies +@example + a m a' - m + b*b' = 0 +@end example + +@end deftypefn + +@deftypefn {Function File} {@var{x} = } dlyap (@var{a}, @var{b}) +Solve the discrete-time Lyapunov equation + + @strong{Inputs} + @table @var + @item a + @var{n} by @var{n} matrix + @item b + Matrix: @var{n} by @var{n}, @var{n} by @var{m}, or @var{p} by @var{n}. + @end table + + @strong{Outputs} + @var{x}: matrix satisfying appropriate discrete time Lyapunov equation. + Options: + @itemize @bullet + @item @var{b} is square: solve @code{a x a' - x + b = 0} + @item @var{b} is not square: @var{x} satisfies either + @example + a x a' - x + b b' = 0 + @end example + @noindent + or + @example + a' x a - x + b' b = 0, + @end example + @noindent + whichever is appropriate. + @end itemize + +@strong{Method} + Uses Schur decomposition method as in Kitagawa, + @cite{An Algorithm for Solving the Matrix Equation @var{X} = + @var{F}@var{X}@var{F}' + @var{S}}, + International Journal of Control, Volume 25, Number 5, pages 745--753 + (1977). + +Column-by-column solution method as suggested in + Hammarling, @cite{Numerical Solution of the Stable, Non-Negative + Definite Lyapunov Equation}, IMA Journal of Numerical Analysis, Volume + 2, pages 303--323 (1982). + +@end deftypefn + +@deftypefn {Function File } { @var{m} =} gram (@var{a}, @var{b}) + Return controllability grammian @var{m} of the continuous time system +@math{ dx/dt = a x + b u}. + +@var{m} satisfies @math{ a m + m a' + b b' = 0 }. +@end deftypefn + + +@deftypefn {Function File} {} lyap (@var{a}, @var{b}, @var{c}) +@deftypefnx {Function File} {} lyap (@var{a}, @var{b}) + Solve the Lyapunov (or Sylvester) equation via the Bartels-Stewart + algorithm (Communications of the ACM, 1972). + + If @var{a}, @var{b}, and @var{c} are specified, then @code{lyap} returns + the solution of the Sylvester equation + @iftex + @tex + $$ A X + X B + C = 0 $$ + @end tex + @end iftex + @ifinfo + @example + a x + x b + c = 0 + @end example + @end ifinfo + If only @code{(a, b)} are specified, then @code{lyap} returns the + solution of the Lyapunov equation + @iftex + @tex + $$ A^T X + X A + B = 0 $$ + @end tex + @end iftex + @ifinfo + @example + a' x + x a + b = 0 + @end example + @end ifinfo + If @var{b} is not square, then @code{lyap} returns the solution of either + @iftex + @tex + $$ A^T X + X A + B^T B = 0 $$ + @end tex + @end iftex + @ifinfo + @example + a' x + x a + b' b = 0 + @end example + @end ifinfo + @noindent + or + @iftex + @tex + $$ A X + X A^T + B B^T = 0 $$ + @end tex + @end iftex + @ifinfo + @example + a x + x a' + b b' = 0 + @end example + @end ifinfo + @noindent + whichever is appropriate. +@end deftypefn + +@deftypefn {Function File } { } pinv ( @var{X}@{,@var{tol}@} ) +Returns the pseudoinverse of X; singular values less than tol are ignored. +@end deftypefn + +@deftypefn {Function File } { @var{x} =} qzval (@var{A}, @var{B}) +Compute generalized eigenvalues of the matrix pencil +@ifinfo +@example +(A - lambda B). +@end example +@end ifinfo +@iftex +@tex +$(A - \lambda B)$. +@end tex +@end iftex + +@var{A} and @var{B} must be real matrices. + +@strong{Note} @code{qzval} is obsolete; use @code{qz} instead. +@end deftypefn + +@deftypefn {Function File } { } zgfmul +@deftypefnx {Function File } { } zgfslv +@deftypefnx {Function File } { } zginit +@deftypefnx {Function File } {@var{retsys} =} zgpbal (@var{Asys}) +@deftypefnx {Function File } {} zgreduce +@deftypefnx {Function File } { [@var{nonz}, @var{zer}] =} zgrownorm (@var{mat}, @var{meps}) +@deftypefnx {Function File } { x =} zgscal (@var{f}, @var{z}, @var{n}, @var{m}, @var{p}) +@deftypefnx {Function File } { } zgsgiv ( ) +@deftypefnx {Function File } { @var{x} =} zgshsr( @var{y}) +Used internally by @code{tzero}. +Minimal argument checking performed. + +Details involving major subroutines: +@table @code +@item zgpbal +Implementation of zero computation generalized eigenvalue problem + balancing method. @code{zgpbal} computes a state/input/output +weighting that attempts to + reduced the range of the magnitudes of the nonzero elements of [a,b,c,d] + The weighting uses scalar multiplication by powers of 2, so no roundoff + will occur. + + @code{zgpbal} should be followed by @code{zgpred} + +@item zgreduce +Implementation of procedure REDUCE in (Emami-Naeini and Van Dooren, +Automatica, 1982). + +@item zgrownorm + Returns @var{nonz} = number of rows of @var{mat} whose two norm exceeds + @var{meps}, @var{zer} = number of rows of mat whose two norm + is less than meps + +@item zgscal +Generalized conjugate gradient iteration to + solve zero-computation generalized eigenvalue problem balancing equation + @math{fx=z}; + called by @code{zgepbal} + +@item zgsgiv +apply givens rotation c,s to column vector a,b +@item zgshsr +Apply Householder vector based on @code{e^(m)} (all ones) to +(column vector) @var{y}. Called by @code{zgfslv}. + +@end table +References: +@table @strong +@item ZGEP + Hodel, "Computation of Zeros with Balancing," 1992, Linear Algebra + and its Applications +@item @strong{Generalized CG} + Golub and Van Loan, "Matrix Computations, 2nd ed" 1989 +@end table + +@end deftypefn + +@node sysprop, systime, numerical, Control Theory +@section System Analysis-Properties + +@deftypefn {Function File } { } analdemo ( ) + Octave Controls toolbox demo: State Space analysis demo +@end deftypefn + + +@deftypefn {Function File} {[@var{n}, @var{m}, @var{p}] =} abcddim (@var{a}, @var{b}, @var{c}, @var{d}) +Check for compatibility of the dimensions of the matrices defining +the linear system +@iftex +@tex +$[A, B, C, D]$ corresponding to +$$ +\eqalign{ + {dx\over dt} &= A x + B u\cr + y &= C x + D u} +$$ +@end tex +@end iftex +@ifinfo +[A, B, C, D] corresponding to + +@example +dx/dt = a x + b u +y = c x + d u +@end example + +@end ifinfo +or a similar discrete-time system. + +If the matrices are compatibly dimensioned, then @code{abcddim} returns + +@table @var +@item n +The number of system states. + +@item m +The number of system inputs. + +@item p +The number of system outputs. +@end table + +Otherwise @code{abcddim} returns @var{n} = @var{m} = @var{p} = @minus{}1. + +Note: n = 0 (pure gain block) is returned without warning. + +See also: is_abcd +@end deftypefn + +@deftypefn {Function File } {[@var{y}, @var{my}, @var{ny}] =} abcddims (@var{x}) + +Used internally in @code{abcddim}. If @var{x} is a zero-size matrix, +both dimensions are set to 0 in @var{y}. +@var{my} and @var{ny} are the row and column dimensions of the result. +@end deftypefn + +@deftypefn {Function File } {@var{Qs} =} ctrb(@var{sys} @{, @var{b}@}) +@deftypefnx {Function File } {@var{Qs} =} ctrb(@var{A}, @var{B}) +Build controllability matrix +@example + 2 n-1 +Qs = [ B AB A B ... A B ] +@end example + + of a system data structure or the pair (@var{A}, @var{B}). + +@strong{Note} @code{ctrb} forms the controllability matrix. + The numerical properties of @code{is_controllable} + are much better for controllability tests. +@end deftypefn + +@deftypefn {Function File } {@var{retval} =} h2norm(@var{sys}) +Computes the H2 norm of a system data structure (continuous time only) + +Reference: + Doyle, Glover, Khargonekar, Francis, ``State Space Solutions to Standard + H2 and Hinf Control Problems", IEEE TAC August 1989 +@end deftypefn + +@deftypefn {Function File } {[@var{g}, @var{gmin}, @var{gmax}] =} hinfnorm(@var{sys}@{, @var{tol}, @var{gmin}, @var{gmax}, @var{ptol}@}) + Computes the H infinity norm of a system data structure. + +@strong{Inputs} +@table @var +@item sys +system data structure +@item tol +H infinity norm search tolerance (default: 0.001) +@item gmin +minimum value for norm search (default: 1e-9) +@item gmax +maximum value for norm search (default: 1e+9) +@item ptol + pole tolerance: +@itemize @bullet +@item if sys is continuous, poles with +|real(pole)| < ptol*||H|| (H is appropriate Hamiltonian) +are considered to be on the imaginary axis. + +@item if sys is discrete, poles with +|abs(pole)-1| < ptol*||[s1,s2]|| (appropriate symplectic pencil) +are considered to be on the unit circle + +@item Default: 1e-9 +@end itemize +@end table + +@strong{Outputs} +@table @var +@item g +Computed gain, within @var{tol} of actual gain. @var{g} is returned as Inf +if the system is unstable. +@item gmin, gmax +Actual system gain lies in the interval [@var{gmin}, @var{gmax}] +@end table + + References: + Doyle, Glover, Khargonekar, Francis, "State space solutions to standard + H2 and Hinf control problems", IEEE TAC August 1989 + Iglesias and Glover, "State-Space approach to discrete-time Hinf control," + Int. J. Control, vol 54, #5, 1991 + Zhou, Doyle, Glover, "Robust and Optimal Control," Prentice-Hall, 1996 + $Revision: 1.9 $ +@end deftypefn + +@deftypefn {Function File } { @var{Qb} =} obsv (@var{sys}@{, @var{c}@}) +Build observability matrix +@example +@group + | C | + | CA | +Qb = | CA^2 | + | ... | + | CA^(n-1) | +@end group +@end example +of a system data structure or the pair (A, C). + +Note: @code{obsv()} forms the observability matrix. + + The numerical properties of is_observable() + are much better for observability tests. +@end deftypefn + +@deftypefn {Function File } {[@var{zer}, @var{pol}]=} pzmap (@var{sys}) + Plots the zeros and poles of a system in the complex plane. +@strong{Inputs} + @var{sys} system data structure + +@strong{Outputs} +if omitted, the poles and zeros are plotted on the screen. + otherwise, pol, zer are returned as the system poles and zeros. + (see sys2zp for a preferable function call) +@end deftypefn + +@deftypefn{Function File} {outputs = } synKnames (inputs) +Return controller signal names based in plant signal names and dimensions +@end deftypefn + +@deftypefn {Function File } { @var{retval} =} is_abcd( @var{a}@{, @var{b}, @var{c}, @var{d}@}) + Returns @var{retval} = 1 if the dimensions of @var{a}, @var{b}, @var{c}, @var{d} + are compatible, otherwise @var{retval} = 0 with an appropriate diagnostic +message printed to the screen. +@end deftypefn + +@deftypefn {Function File } {[@var{retval}, @var{U}] =} is_controllable (@var{sys}@{, @var{tol}@}) +@deftypefnx {Function File } {[@var{retval}, @var{U}] =} is_controllable (@var{a}@{, @var{b} ,@var{tol}@}) +Logical check for system controllability. + +@strong{Inputs} +@table @var +@item sys +system data structure +@item a, b +@var{n} by @var{n}, @var{n} by @var{m} matrices, respectively +@item tol +optional roundoff paramter. default value: @code{10*eps} +@end table + +@strong{Outputs} +@table @var +@item retval +Logical flag; returns true (1) if the system @var{sys} or the +pair (@var{a},@var{b}) is controllable, whichever was passed as input arguments. +@item U + U is an orthogonal basis of the controllable subspace. +@end table + +@strong{Method} +Controllability is determined by applying Arnoldi iteration with +complete re-orthogonalization to obtain an orthogonal basis of the +Krylov subspace +@example +span ([b,a*b,...,a^@{n-1@}*b]). +@end example +The Arnoldi iteration is executed with @code{krylov} if the system has a single input; otherwise a block Arnoldi iteration is performed with @code{krylovb}. + +@strong{See also} +@code{is_observable}, @code{is_stabilizable}, @code{is_detectable}, + @code{krylov}, @code{krylovb} + +@end deftypefn + +@deftypefn {Function File } { [@var{retval}, @var{U}] =} is_detectable (@var{a}, @var{c}@{, @var{tol}@}) +@deftypefnx {Function File } { [@var{retval}, @var{U}] =} is_detectable (@var{sys}@{, @var{tol}@}) +Test for detactability (observability of unstable modes) of (@var{a},@var{c}). + + Returns 1 if the system @var{a} or the pair (@var{a},@var{c})is + detectable, 0 if not. + +@strong{See} @code{is_stabilizable} for detailed description of arguments and +computational method. + +@end deftypefn + +@deftypefn {Function File } { [@var{retval}, @var{dgkf_struct} ] =} is_dgkf (@var{Asys}, @var{nu}, @var{ny}, @var{tol} ) + Determine whether a continuous time state space system meets + assumptions of DGKF algorithm. + Partitions system into: +@example +[dx/dt] = [A | Bw Bu ][w] +[ z ] [Cz | Dzw Dzu ][u] +[ y ] [Cy | Dyw Dyu ] +@end example +or similar discrete-time system. +If necessary, orthogonal transformations @var{Qw}, @var{Qz} and nonsingular + transformations @var{Ru}, @var{Ry} are applied to respective vectors +@var{w}, @var{z}, @var{u}, @var{y} in order to satisfy DGKF assumptions. +Loop shifting is used if @var{Dyu} block is nonzero. + +@strong{Inputs} +@table @var +@item Asys +system data structure +@item nu +number of controlled inputs +@item ny + number of measured outputs +@item tol + threshhold for 0. Default: 200@var{eps} +@end table +@strong{Outputs} +@table @var +@item retval + true(1) if system passes check, false(0) otherwise +@item dgkf_struct + data structure of @code{is_dgkf} results. Entries: +@table @var +@item nw, nz + dimensions of @var{w}, @var{z} +@item A + system @var{A} matrix +@item Bw + (@var{n} x @var{nw}) @var{Qw}-transformed disturbance input matrix +@item Bu + (@var{n} x @var{nu}) @var{Ru}-transformed controlled input matrix; + + @strong{Note} @math{B = [Bw Bu] } +@item Cz + (@var{nz} x @var{n}) Qz-transformed error output matrix +@item Cy + (@var{ny} x @var{n}) @var{Ry}-transformed measured output matrix + + @strong{Note} @math{C = [Cz; Cy] } +@item Dzu, Dyw + off-diagonal blocks of transformed @var{D} matrix that enter +@var{z}, @var{y} from @var{u}, @var{w} respectively +@item Ru + controlled input transformation matrix +@item Ry + observed output transformation matrix +@item Dyu_nz + nonzero if the @var{Dyu} block is nonzero. +@item Dyu + untransformed @var{Dyu} block +@item dflg + nonzero if the system is discrete-time + @end table +@end table +@code{is_dgkf} exits with an error if the system is mixed discrete/continuous + +@strong{References} +@table @strong +@item [1] + Doyle, Glover, Khargonekar, Francis, "State Space Solutions + to Standard H2 and Hinf Control Problems," IEEE TAC August 1989 +@item [2] + Maciejowksi, J.M.: "Multivariable feedback design," +@end table + +@end deftypefn + +@deftypefn {Function File } { @var{retval} =} is_digital ( @var{sys}) +Return nonzero if system is digital; +Exits with an error of sys is a mixed (continuous and discrete) system +@end deftypefn + +@deftypefn {Function File } { [@var{retval},@var{U}] =} is_observable (@var{a}, @var{c}@{,@var{tol}@}) +@deftypefnx {Function File } { [@var{retval},@var{U}] =} is_observable (@var{sys}@{, @var{tol}@}) +Logical check for system observability. + Returns 1 if the system @var{sys} or the pair (@var{a},@var{c}) is + observable, 0 if not. + +@strong{See} @code{is_controllable} for detailed description of arguments +and default values. +@end deftypefn + +@deftypefn {Function File } { @var{retval} =} is_sample (@var{Ts}) + return true if @var{Ts} is a legal sampling time + (real,scalar, > 0) +@end deftypefn + +@deftypefn {Function File } { @var{retval} =} is_siso (@var{sys}) +return nonzero if the system data structure +@var{sys} is single-input, single-output. +@end deftypefn + +@deftypefn {Function File } {[@var{retval}, @var{U}] =} is_stabilizable (@var{sys}@{, @var{tol}@}) +@deftypefnx {Function File } {[@var{retval}, @var{U}] =} is_stabilizable (@var{a}@{, @var{b} ,@var{tol}@}) +Logical check for system stabilizability (i.e., all unstable modes are controllable). + +@strong{See} @code{is_controllable} for description of inputs, outputs. +Test for stabilizability is performed via an ordered Schur decomposition +that reveals the unstable subspace of the system @var{A} matrix. + +@end deftypefn + +@deftypefn {Function File } {@var{flg} =} is_signal_list (@var{mylist}) +returns true if mylist is a list of individual strings (legal for input +to @var{syssetsignals}). +@end deftypefn + +@deftypefn {Function File } { @var{retval} =} is_stable (@var{a}@{,@var{tol},@var{dflg}@}) +@deftypefnx {Function File } { @var{retval} =} is_stable (@var{sys}@{,@var{tol}@}) + Returns retval = 1 if the matrix @var{a} or the system @var{sys} +is stable, or 0 if not. + +@strong{Inputs} +@table @var +@item tol +is a roundoff paramter, set to 200*@var{eps} if omitted. +@item dflg +Digital system flag (not required for system data structure): +@table @code +@item @var{dflg} != 0 +stable if eig(a) in unit circle + +@item @var{dflg} == 0 +stable if eig(a) in open LHP (default) +@end table +@end table +@end deftypefn + +@node systime, sysfreq, sysprop, Control Theory +@section System Analysis-Time Domain + +@deftypefn {Function File } { @var{dsys} =} c2d (@var{sys}@{, @var{opt}, @var{T}@}) +@deftypefnx {Function File } { @var{dsys} =} c2d (@var{sys}@{, @var{T}@}) + +@strong{Inputs} +@table @var +@item sys + system data structure (may have both continuous time and discrete time subsystems) +@item opt +string argument; conversion option (optional argument; +may be omitted as shown above) +@table @code +@item "ex" +use the matrix exponential (default) +@item "bi" +use the bilinear transformation +@end table +@example + 2(z-1) +s = ----- + T(z+1) +@end example +FIXME: This option exits with an error if @var{sys} is not purely +continuous. (The @code{ex} option can handle mixed systems.) +@item @var{T} +sampling time; required if sys is purely continuous. + +@strong{Note} If the 2nd argument is not a string, @code{c2d} assumes that +the 2nd argument is @var{T} and performs appropriate argument checks. +@end table + +@strong{Outputs} +@var{dsys} discrete time equivalent via zero-order hold, +sample each @var{T} sec. + +converts the system data structure describing +@example +. +x = Ac x + Bc u +@end example +into a discrete time equivalent model +@example +x[n+1] = Ad x[n] + Bd u[n] +@end example +via the matrix exponential or bilinear transform + +@strong{Note} This function adds the suffix @code{_d} +to the names of the new discrete states. +@end deftypefn + +@deftypefn {Function File } {@var{csys} =} d2c (@var{sys}@{,@var{tol}@}) +@deftypefnx {Function File } {@var{csys} =} d2c (@var{sys}, @var{opt}) +Convert discrete (sub)system to a purely continuous system. Sampling +time used is @code{sysgettsam(@var{sys})} + +@strong{Inputs} +@table @var +@item sys + system data structure with discrete components +@item tol +Scalar value. + tolerance for convergence of default @code{"log"} option (see below) +@item opt + conversion option. Choose from: +@table @code +@item "log" + (default) Conversion is performed via a matrix logarithm. +Due to some problems with this computation, it is +followed by a steepest descent algorithm to identify continuous time +@var{A}, @var{B}, to get a better fit to the original data. + +If called as @code{d2c}(@var{sys},@var{tol}), @var{tol=}positive scalar, + the @code{"log"} option is used. The default value for @var{tol} is + @code{1e-8}. +@item "bi" + Conversion is performed via bilinear transform +@math{z = (1 + s T / 2)/(1 - s T / 2)} where @var{T} is the +system sampling time (see @code{sysgettsam}). + +FIXME: bilinear option exits with an error if @var{sys} is not purely discrete + +@end table +@end table +@strong{Outputs} @var{csys} continuous time system (same dimensions and +signal names as in @var{sys}). +@end deftypefn + +@deftypefn {Function File } {[@var{dsys}, @var{fidx}] =} dmr2d (@var{sys}, @var{idx}, @var{sprefix}, @var{Ts2} @{,@var{cuflg}@}) + convert a multirate digital system to a single rate digital system + states specified by @var{idx}, @var{sprefix} are sampled at @var{Ts2}, all + others are assumed sampled at @var{Ts1} = @code{sysgettsam(@var{sys})}. + +@strong{Inputs} +@table @var +@item sys +discrete time system; +@code{dmr2d} exits with an error if @var{sys} is not discrete +@item idx +list of states with sampling time @code{sysgettsam(@var{sys})} (may be empty) +@item sprefix +list of string prefixes of states with sampling time @code{sysgettsam(@var{sys})} +(may be empty) +@item Ts2 +sampling time of states not specified by @var{idx}, @var{sprefix} +must be an integer multiple of @code{sysgettsam(@var{sys})} +@item cuflg +"constant u flag" if @var{cuflg} is nonzero then the system inputs are + assumed to be constant over the revised sampling interval @var{Ts2}. + Otherwise, since the inputs can change during the interval + @var{t} in @math{[k Ts2, (k+1) Ts2]}, an additional set of inputs is + included in the revised B matrix so that these intersample inputs + may be included in the single-rate system. + default + @var{cuflg} = 1. +@end table + +@strong{Outputs} +@table @var +@item dsys + equivalent discrete time system with sampling time @var{Ts2}. + + The sampling time of sys is updated to @var{Ts2}. + + if @var{cuflg}=0 then a set of additional inputs is added to + the system with suffixes _d1, ..., _dn to indicate their + delay from the starting time k @var{Ts2}, i.e. + u = [u_1; u_1_d1; ..., u_1_dn] where u_1_dk is the input + k*Ts1 units of time after u_1 is sampled. (Ts1 is + the original sampling time of discrete time sys and + @var{Ts2} = (n+1)*Ts1) + +@item fidx +indices of "formerly fast" states specified by @var{idx} and @var{sprefix}; +these states are updated to the new (slower) sampling interval @var{Ts2}. +@end table + +@strong{WARNING} Not thoroughly tested yet; especially when @var{cuflg} == 0. + +@end deftypefn + +@deftypefn {Function File } {} damp(@var{p}@{, @var{tsam}@}) + Displays eigenvalues, natural frequencies and damping ratios + of the eigenvalues of a matrix @var{p} or the @var{A}-matrix of a + system @var{p}, respectively. + If @var{p} is a system, @var{tsam} must not be specified. + If @var{p} is a matrix and @var{tsam} is specified, eigenvalues + of @var{p} are assumed to be in @var{z}-domain. + +See also: @code{eig} +@end deftypefn + +@deftypefn {Function File } {@var{gm} =} dcgain(@var{sys}@{, tol@}) + Returns dc-gain matrix. If dc-gain is infinite + an empty matrix is returned. + The argument @var{tol} is an optional tolerance for the condition + number of @var{A}-Matrix in @var{sys} (default @var{tol} = 1.0e-10) +@end deftypefn + +@deftypefn {Function File } {[@var{y}, @var{t}] =} impulse (@var{sys}@{, @var{inp},@var{tstop}, @var{n}@}) +Impulse response for a linear system. + The system can be discrete or multivariable (or both). +If no output arguments are specified, @code{impulse} + produces a plot or the step response data for system @var{sys}. + +@strong{Inputs} +@table @var +@item sys +System data structure. +@item inp +Index of input being excited +@item tstop + The argument @var{tstop} (scalar value) denotes the time when the + simulation should end. +@item n +the number of data values. + + Both parameters @var{tstop} and @var{n} can be omitted and will be + computed from the eigenvalues of the A-Matrix. +@end table +@strong{Outputs} +@var{y}, @var{t}: impulse response +@end deftypefn + +@deftypefn {Function File } {[@var{y}, @var{t}] =} step (@var{sys}@{, @var{inp},@var{tstop}, @var{n}@}) +Step response of a linear system; calling protocol is identical to +@code{impulse}. +@end deftypefn + +@deftypefn {Function File } { } stepimp ( ) +Used internally in @code{impulse}, @code{step}. +@end deftypefn + +@node sysfreq, cacsd, systime, Control Theory +@section System Analysis-Frequency Domain + +@strong{Demonstration/tutorial script} +@deftypefn {Function File } { } frdemo ( ) +@end deftypefn + + +@deftypefn {Function File } {[@var{mag}, @var{phase}, @var{w}] =} bode(@var{sys}@{,@var{w}, @var{out_idx}, @var{in_idx}@}) +If no output arguments are given: produce Bode plots of a system; otherwise, +compute the frequency response of a system data structure + +@strong{Inputs} +@table @var +@item sys + a system data structure (must be either purely continuous or discrete; + see is_digital) +@item w + frequency values for evaluation. + +if @var{sys} is continuous, then bode evaluates @math{G(jw)} where +@math{G(s)} is the system transfer function. + +if @var{sys} is discrete, then bode evaluates G(@code{exp}(jwT)), where +@itemize @bullet +@item @var{T}=@code{sysgettsam(@var{sys})} (the system sampling time) and +@item @math{G(z)} is the system transfer function. +@end itemize + +@strong{ Default} the default frequency range is selected as follows: (These + steps are NOT performed if @var{w} is specified) +@enumerate +@item via routine bodquist, isolate all poles and zeros away from +@var{w}=0 (@var{jw}=0 or @math{@code{exp}(jwT)}=1) and select the frequency +range based on the breakpoint locations of the frequencies. +@item if @var{sys} is discrete time, the frequency range is limited + to @math{jwT} in +@ifinfo +[0,2 pi /T] +@end ifinfo +@iftex +@tex +$[0,2\pi/T]$ +@end tex +@end iftex +@item A "smoothing" routine is used to ensure that the plot phase does + not change excessively from point to point and that singular + points (e.g., crossovers from +/- 180) are accurately shown. + +@end enumerate +@item out_idx, in_idx + the indices of the output(s) and input(s) to be used in + the frequency response; see @code{sysprune}. +@end table +@strong{Outputs} +@table @var +@item mag, phase + the magnitude and phase of the frequency response + @math{G(jw)} or @math{G(@code{exp}(jwT))} at the selected frequency values. +@item w +the vector of frequency values used +@end table + +@strong{Notes} +@enumerate +@item If no output arguments are given, e.g., +@example +bode(sys); +@end example +bode plots the results to the +screen. Descriptive labels are automatically placed. + +Failure to include a concluding semicolon will yield some garbage +being printed to the screen (@code{ans = []}). + +@item If the requested plot is for an MIMO system, mag is set to + @math{||G(jw)||} or @math{||G(@code{exp}(jwT))||} +and phase information is not computed. +@end enumerate +@end deftypefn + +@deftypefn {Function File } {[@var{wmin}, @var{wmax}] =} bode_bounds (@var{zer}, @var{pol}, @var{dflg}@{, @var{tsam} @}) +Get default range of frequencies based on cutoff frequencies of system +poles and zeros. +Frequency range is the interval [10^wmin,10^wmax] + +Used internally in freqresp (@code{bode}, @code{nyquist}) +@end deftypefn + +@deftypefn {Function File } { [@var{f}, @var{w}] =} bodquist (@var{sys}, @var{w}, @var{out_idx}, @var{in_idx}) + used internally by bode, nyquist; compute system frequency response. + +@strong{Inputs} +@table @var +@item sys +input system structure +@item w +range of frequencies; empty if user wants default +@item out_idx +list of outputs; empty if user wants all +@item in_idx +list of inputs; empty if user wants all +@item rname +name of routine that called bodquist ("bode" or "nyquist") +@end table +@strong{Outputs} +@table @var +@item w + list of frequencies +@item f + frequency response of sys; @math{f(ii) = f(omega(ii))} +@end table +@strong{Note} bodquist could easily be incorporated into a Nichols +plot function; this is in a "to do" list. +@end deftypefn + +@deftypefn {Function File } { @var{retval} =} freqchkw ( @var{w} ) +Used by @code{freqresp} to check that input frequency vector @var{w} is legal. +Returns boolean value. +@end deftypefn + +@deftypefn {Function File } { @var{out} =} freqresp (@var{sys},@var{USEW}@{,@var{w}@}); + Frequency response function - used internally by @code{bode}, @code{nyquist}. + minimal argument checking; "do not attempt to do this at home" + +@strong{Inputs} +@table @var +@item sys +system data structure +@item USEW +returned by @code{freqchkw} +@item optional + must be present if @var{USEW} is true (nonzero) +@end table +@strong{Outputs} +@table @var +@item @var{out} +vector of finite @math{G(j*w)} entries (or @math{||G(j*w)||} for MIMO) +@item w +vector of corresponding frequencies +@end table +@end deftypefn + +@deftypefn {Function File } {@var{out} =} ltifr (@var{A}, @var{B}, @var{w}) +@deftypefnx {Function File } {@var{out} =} ltifr (@var{sys}, @var{w}) +Linear time invariant frequency response of single input systems +@strong{Inputs} +@table @var +@item A, B +coefficient matrices of @math{dx/dt = A x + B u} +@item sys + system data structure +@item w + vector of frequencies +@end table +@strong{Outputs} +@var{out} +@example + -1 + G(s) = (jw I-A) B +@end example +for complex frequencies @math{s = jw}. +@end deftypefn + +@deftypefn {Function File } {[@var{realp}, @var{imagp}, @var{w}] =} nyquist (@var{sys}@{, @var{w}, @var{out_idx}, @var{in_idx}, @var{atol}@}) +@deftypefnx {Function File } {} nyquist (@var{sys}@{, @var{w}, @var{out_idx}, @var{in_idx}, @var{atol}@}) +Produce Nyquist plots of a system; if no output arguments are given, Nyquist +plot is printed to the screen. + +Arguments are identical to @code{bode} with exceptions as noted below: + +@strong{Inputs} (pass as empty to get default values) +@table @var +@item atol +for interactive nyquist plots: atol is a change-in-slope tolerance +for the of asymptotes (default = 0; 1e-2 is a good choice). This allows +the user to ``zoom in'' on portions of the Nyquist plot too small to be +seen with large asymptotes. +@end table +@strong{Outputs} +@table @var +@item realp, imagp +the real and imaginary parts of the frequency response + @math{G(jw)} or @math{G(exp(jwT))} at the selected frequency values. +@item w + the vector of frequency values used +@end table + + If no output arguments are given, nyquist plots the results to the screen. + If @var{atol} != 0 and asymptotes are detected then the user is asked + interactively if they wish to zoom in (remove asymptotes) + Descriptive labels are automatically placed. + + Note: if the requested plot is for an MIMO system, a warning message is + presented; the returned information is of the magnitude + ||G(jw)|| or ||G(exp(jwT))|| only; phase information is not computed. + +@end deftypefn + +@deftypefn {Function File} {} tzero (@var{a}, @var{b}, @var{c}, @var{d}@{, @var{opt}@}) +@deftypefnx {Function File} {} tzero (@var{sys}@{,@var{opt}@}) + Compute transmission zeros of a continuous +@example +. +x = Ax + Bu +y = Cx + Du +@end example +or discrete +@example +x(k+1) = A x(k) + B u(k) +y(k) = C x(k) + D u(k) +@end example +system. +@strong{Outputs} +@table @var +@item zer + transmission zeros of the system +@item gain +leading coefficient (pole-zero form) of SISO transfer function +returns gain=0 if system is multivariable +@end table +@strong{References} +@enumerate +@item Emami-Naeini and Van Dooren, Automatica, 1982. +@item Hodel, "Computation of Zeros with Balancing," 1992 Lin. Alg. Appl. +@end enumerate +@end deftypefn + +@deftypefn {Function File } { @var{zr} =} tzero2 (@var{a}, @var{b}, @var{c}, @var{d}, @var{bal}) +Compute the transmission zeros of a, b, c, d. + +bal = balancing option (see balance); default is "B". + +Needs to incorporate @code{mvzero} algorithm to isolate finite zeros; use +@code{tzero} instead. +@end deftypefn + +@node cacsd, misc, sysfreq, Control Theory +@section Controller Design + +@deftypefn {Function File } { } dgkfdemo ( ) + Octave Controls toolbox demo: H2/Hinfinity options demos +@end deftypefn +@deftypefn {Function File } { } hinfdemo ( ) +Non-trivial H_infinity design demo. + +H_infinity optimal controller for the jet707 plant; +Linearized state space model of a Boeing 707-321 aircraft +at v=80m/s. (M = 0.26, Ga0 = -3 deg, +alpha0 = 4 deg, kappa = 50 deg) +inputs: (1) thrust and (2) elevator angle +outputs: (1) airspeed and (2) pitch angle + +The optimal controller minimizes the H_infinity norm of the +augmented plant P (mixed-sensitivity problem): +@example +@group + w + 1 -----------+ + | +----+ + +---------------------->| W1 |----> z1 + w | | +----+ + 2 ------------------------+ + | | | + | v +----+ v +----+ + +--*-->o-->| G |-->o--*-->| W2 |---> z2 + | +----+ | +----+ + | | + ^ v + u (from y (to K) + controller + K) + ++ + + + +| z | | w | +| 1 | | 1 | +| z | = [ P ] * | w | +| 2 | | 2 | +| y | | u | ++ + + + +@end group +@end example +@end deftypefn + +@deftypefn {Function File} {[@var{l}, @var{m}, @var{p}, @var{e}] =} dlqe (@var{a}, @var{g}, @var{c}, @var{sigw}, @var{sigv}, @var{z}) +Construct the linear quadratic estimator (Kalman filter) for the +discrete time system +@iftex +@tex +$$ + x_{k+1} = A x_k + B u_k + G w_k +$$ +$$ + y_k = C x_k + D u_k + w_k +$$ +@end tex +@end iftex +@ifinfo + +@example +x[k+1] = A x[k] + B u[k] + G w[k] + y[k] = C x[k] + D u[k] + w[k] +@end example + +@end ifinfo +where @var{w}, @var{v} are zero-mean gaussian noise processes with +respective intensities @code{@var{sigw} = cov (@var{w}, @var{w})} and +@code{@var{sigv} = cov (@var{v}, @var{v})}. + +If specified, @var{z} is @code{cov (@var{w}, @var{v})}. Otherwise +@code{cov (@var{w}, @var{v}) = 0}. + +The observer structure is +@iftex +@tex +$$ + z_{k+1} = A z_k + B u_k + k (y_k - C z_k - D u_k) +$$ +@end tex +@end iftex +@ifinfo + +@example +z[k+1] = A z[k] + B u[k] + k (y[k] - C z[k] - D u[k]) +@end example +@end ifinfo + +@noindent +The following values are returned: + +@table @var +@item l +The observer gain, +@iftex +@tex +$(A - ALC)$. +@end tex +@end iftex +@ifinfo +(@var{a} - @var{a}@var{l}@var{c}). +@end ifinfo +is stable. + +@item m +The Riccati equation solution. + +@item p +The estimate error covariance after the measurement update. + +@item e +The closed loop poles of +@iftex +@tex +$(A - ALC)$. +@end tex +@end iftex +@ifinfo +(@var{a} - @var{a}@var{l}@var{c}). +@end ifinfo +@end table +@end deftypefn + +@deftypefn {Function File} {[@var{k}, @var{p}, @var{e}] =} dlqr (@var{a}, @var{b}, @var{q}, @var{r}, @var{z}) +Construct the linear quadratic regulator for the discrete time system +@iftex +@tex +$$ + x_{k+1} = A x_k + B u_k +$$ +@end tex +@end iftex +@ifinfo + +@example +x[k+1] = A x[k] + B u[k] +@end example + +@end ifinfo +to minimize the cost functional +@iftex +@tex +$$ + J = \sum x^T Q x + u^T R u +$$ +@end tex +@end iftex +@ifinfo + +@example +J = Sum (x' Q x + u' R u) +@end example +@end ifinfo + +@noindent +@var{z} omitted or +@iftex +@tex +$$ + J = \sum x^T Q x + u^T R u + 2 x^T Z u +$$ +@end tex +@end iftex +@ifinfo + +@example +J = Sum (x' Q x + u' R u + 2 x' Z u) +@end example + +@end ifinfo +@var{z} included. + +The following values are returned: + +@table @var +@item k +The state feedback gain, +@iftex +@tex +$(A - B K)$ +@end tex +@end iftex +@ifinfo +(@var{a} - @var{b}@var{k}) +@end ifinfo +is stable. + +@item p +The solution of algebraic Riccati equation. + +@item e +The closed loop poles of +@iftex +@tex +$(A - B K)$. +@end tex +@end iftex +@ifinfo +(@var{a} - @var{b}@var{k}). +@end ifinfo +@end table +@strong{References} +@enumerate +@item Anderson and Moore, Optimal Control: Linear Quadratic Methods, + Prentice-Hall, 1990, pp. 56-58 +@item Kuo, Digital Control Systems, Harcourt Brace Jovanovich, 1992, + section 11-5-2. +@end enumerate +@end deftypefn + +@deftypefn {Function File } {[K}, @var{gain}, @var{Kc}, @var{Kf}, @var{Pc}, @var{Pf}] = h2syn(@var{Asys}, @var{nu}, @var{ny}, @var{tol}) + Design H2 optimal controller per procedure in + Doyle, Glover, Khargonekar, Francis, "State Space Solutions to Standard + H2 and Hinf Control Problems", IEEE TAC August 1989 + +@strong{Inputs} input system is passed as either +@table @var +@item Asys +system data structure (see ss2sys, sys2ss) +@itemize @bullet +@item controller is implemented for continuous time systems +@item controller is NOT implemented for discrete time systems +@end itemize +@item nu +number of controlled inputs +@item ny +number of measured outputs +@item tol +threshhold for 0. Default: 200*eps +@end table + +@strong{Outputs} +@table @var +@item K +system controller +@item gain +optimal closed loop gain +@item Kc +full information control (packed) +@item Kf +state estimator (packed) +@item Pc +ARE solution matrix for regulator subproblem +@item Pf +ARE solution matrix for filter subproblem +@end table +@end deftypefn + +@deftypefn {Function File } {@var{K} =} hinf_ctr(@var{dgs}, @var{F}, @var{H}, @var{Z}, @var{g}) +Called by @code{hinfsyn} to compute the H_inf optimal controller. + +@strong{Inputs} +@table @var +@item dgs +data structure returned by @code{is_dgkf} +@item F, H +feedback and filter gain (not partitioned) +@item g +final gamma value +@end table +@strong{Outputs} +controller K (system data structure) + +Do not attempt to use this at home; no argument checking performed. +@end deftypefn + +@deftypefn {Function File } {[@var{K}, @var{g}, @var{GW}, @var{Xinf}, @var{Yinf}] =} hinfsyn(@var{Asys}, @var{nu}, @var{ny}, @var{gmin}, @var{gmax}, @var{gtol}@{, @var{ptol}, @var{tol}@}) + +@strong{Inputs} input system is passed as either +@table @var +@item Asys +system data structure (see ss2sys, sys2ss) +@itemize @bullet +@item controller is implemented for continuous time systems +@item controller is NOT implemented for discrete time systems (see +bilinear transforms in @code{c2d}, @code{d2c}) +@end itemize +@item nu +number of controlled inputs +@item ny +number of measured outputs +@item gmin +initial lower bound on H-infinity optimal gain +@item gmax +initial upper bound on H-infinity optimal gain +@item gtol +gain threshhold. Routine quits when gmax/gmin < 1+tol +@item ptol +poles with abs(real(pole)) < ptol*||H|| (H is appropriate +Hamiltonian) are considered to be on the imaginary axis. +Default: 1e-9 +@item tol +threshhold for 0. Default: 200*eps + +@var{gmax}, @var{min}, @var{tol}, and @var{tol} must all be postive scalars. +@end table +@strong{Outputs} +@table @var +@item K +system controller +@item g +designed gain value +@item GW +closed loop system +@item Xinf +ARE solution matrix for regulator subproblem +@item Yinf +ARE solution matrix for filter subproblem +@end table + +@enumerate +@item Doyle, Glover, Khargonekar, Francis, "State Space Solutions + to Standard H2 and Hinf Control Problems," IEEE TAC August 1989 + +@item Maciejowksi, J.M., "Multivariable feedback design," + Addison-Wesley, 1989, ISBN 0-201-18243-2 + +@item Keith Glover and John C. Doyle, "State-space formulae for all + stabilizing controllers that satisfy and h-infinity-norm bound + and relations to risk sensitivity," + Systems & Control Letters 11, Oct. 1988, pp 167-172. +@end enumerate +@end deftypefn + +@deftypefn {Function File } {[@var{xx}, @var{err}] =} hinfsyn_c (@var{nn}, @var{ptol}, @var{s1}@{, @var{s2}@}) +used internally in hinfsyn to evaluate hamiltonian/symplectic + eigenvalue problems. + +@strong{WARNING} Argument checking not performed. + +@strong{Inputs} +@table @var +@item s1 @r{(alone)} +hamiltonian matrix +@item (s1,s2) @r{ as a pair} +symplectic matrix pencil +@end table +@strong{Outputs} +@table @var +@item xx: positive (semi-)definite solution of DARE (set to 0 if err <=2) +@item code: error: +@table @strong +@item 0 +no error +@item 1 + (s1): eigenvalues on imaginary axis + + (s1,s2): gen. eigenvalues on unit circle +@item 2 + unequal number of stable/antistable (generalized) eigenvalues +@item 3 +(s1): infinite entries in solution x + +(s1,s2): infinite entires in solution x or (I + R X) singular +@item 4 +x is not symmetric +@item 5 +x has negative eigenvalues +@end table +@end table + +Solution method: Either Laub's schur method or Symplectic GEP approach; +uses Van Dooren's code to re-order qz decompostion +(www.netlib.com - toms/590) + +See also: Ran and Rodman, "Stable Hermitian Solutions of Discrete + Algebraic Riccati Equations," Mathematics of Control, Signals and + Systems, Vol 5, no 2 (1992) pp 165-194. + +@end deftypefn + +@deftypefn {Function File} {[@var{retval}, @var{Pc}, @var{Pf}] =} hinfsyn_chk(@var{A}, @var{B1}, @var{B2}, @var{C1}, @var{C2}, @var{D12}, @var{D21}, @var{g}, @var{ptol}) + Called by @code{hinfsyn} to see if gain @var{g} satisfies conditions in +Theorem 3 of + Doyle, Glover, Khargonekar, Francis, "State Space Solutions to Standard + H2 and Hinf Control Problems", IEEE TAC August 1989 + +@strong{Warning} Do not attempt to use this at home; no argument checking performed. + +@strong{Inputs} as returned by @code{is_dgkf}, except for: +@table @var +@item g +candidate gain level +@item ptol + as in @code{hinfsyn} +@end table + + Outputs: + retval: = 1 if g exceeds optimal Hinf closed loop gain, else 0 + Pc: solution of "regulator" H-inf ARE + Pf: solution of "filter" H-inf ARE + +@end deftypefn + +@deftypefn {Function File} {[@var{k}, @var{p}, @var{e}] =} lqe (@var{a}, @var{g}, @var{c}, @var{sigw}, @var{sigv}, @var{z}) +Construct the linear quadratic estimator (Kalman filter) for the +continuous time system +@iftex +@tex +$$ + {dx\over dt} = A x + B u +$$ +$$ + y = C x + D u +$$ +@end tex +@end iftex +@ifinfo + +@example +dx +-- = a x + b u +dt + +y = c x + d u +@end example + +@end ifinfo +where @var{w} and @var{v} are zero-mean gaussian noise processes with +respective intensities + +@example +sigw = cov (w, w) +sigv = cov (v, v) +@end example + +The optional argument @var{z} is the cross-covariance +@code{cov (@var{w}, @var{v})}. If it is omitted, +@code{cov (@var{w}, @var{v}) = 0} is assumed. + +Observer structure is @code{dz/dt = A z + B u + k (y - C z - D u)} + +The following values are returned: + +@table @var +@item k +The observer gain, +@iftex +@tex +$(A - K C)$ +@end tex +@end iftex +@ifinfo +(@var{a} - @var{k}@var{c}) +@end ifinfo +is stable. + +@item p +The solution of algebraic Riccati equation. + +@item e +The vector of closed loop poles of +@iftex +@tex +$(A - K C)$. +@end tex +@end iftex +@ifinfo +(@var{a} - @var{k}@var{c}). +@end ifinfo +@end table +@end deftypefn + +@deftypefn {Function File } {[@var{K}, @var{Q}, @var{P}, @var{Ee}, @var{Er}] =} lqg(@var{sys}, @var{Sigw}, @var{Sigv}, @var{Q}, @var{R}, @var{in_idx}) +Design a linear-quadratic-gaussian optimal controller for the system +@example +dx/dt = A x + B u + G w [w]=N(0,[Sigw 0 ]) + y = C x + v [v] ( 0 Sigv ]) +@end example +or +@example +x(k+1) = A x(k) + B u(k) + G w(k) [w]=N(0,[Sigw 0 ]) + y(k) = C x(k) + v(k) [v] ( 0 Sigv ]) +@end example + +@strong{Inputs} +@table @var +@item sys +system data structure +@item Sigw, Sigv +intensities of independent Gaussian noise processes (as above) +@item Q, R +state, control weighting respectively. Control ARE is +@item in_idx +indices of controlled inputs + + default: last dim(R) inputs are assumed to be controlled inputs, all + others are assumed to be noise inputs. +@end table +@strong{Outputs} +@table @var +@item K +system data structure format LQG optimal controller +(Obtain A,B,C matrices with @code{sys2ss}, @code{sys2tf}, or @code{sys2zp} as appropriate) +@item P +Solution of control (state feedback) algebraic Riccati equation +@item Q +Solution of estimation algebraic Riccati equation +@item Ee +estimator poles +@item Es +controller poles +@end table +@end deftypefn + +@deftypefn {Function File} {[@var{k}, @var{p}, @var{e}] =} lqr (@var{a}, @var{b}, @var{q}, @var{r}, @var{z}) +construct the linear quadratic regulator for the continuous time system +@iftex +@tex +$$ + {dx\over dt} = A x + B u +$$ +@end tex +@end iftex +@ifinfo + +@example +dx +-- = A x + B u +dt +@end example + +@end ifinfo +to minimize the cost functional +@iftex +@tex +$$ + J = \int_0^\infty x^T Q x + u^T R u +$$ +@end tex +@end iftex +@ifinfo + +@example + infinity + / + J = | x' Q x + u' R u + / + t=0 +@end example +@end ifinfo + +@noindent +@var{z} omitted or +@iftex +@tex +$$ + J = \int_0^\infty x^T Q x + u^T R u + 2 x^T Z u +$$ +@end tex +@end iftex +@ifinfo + +@example + infinity + / + J = | x' Q x + u' R u + 2 x' Z u + / + t=0 +@end example + +@end ifinfo +@var{z} included. + +The following values are returned: + +@table @var +@item k +The state feedback gain, +@iftex +@tex +$(A - B K)$ +@end tex +@end iftex +@ifinfo +(@var{a} - @var{b}@var{k}) +@end ifinfo +is stable. + +@item p +The stabilizing solution of appropriate algebraic Riccati equation. + +@item e +The vector of the closed loop poles of +@iftex +@tex +$(A - B K)$. +@end tex +@end iftex +@ifinfo +(@var{a} - @var{b}@var{k}). +@end ifinfo +@end table +@end deftypefn + +@deftypefn {Function File } { } lsim (@var{sys}, @var{u}, @var{t}@{,@var{x0}@}) +Produce output for a linear simulation of a system + +Produces a plot for the output of the system, sys. + +U is an array that contains the system's inputs. Each column in u +corresponds to a different time step. Each row in u corresponds to a +different input. T is an array that contains the time index of the +system. T should be regularly spaced. If initial conditions are required +on the system, the x0 vector should be added to the argument list. + +When the lsim function is invoked with output parameters: +[y,x] = lsim(sys,u,t,[x0]) +a plot is not displayed, however, the data is returned in y = system output +and x = system states. +@end deftypefn + +@deftypefn {Function File } { @var{K} =} place (@var{sys}, @var{P}) +Computes the matrix K such that if the state +is feedback with gain K, then the eigenvalues of the closed loop +system (i.e. A-BK) are those specified in the vector P. + +Version: Beta (May-1997): If you have any comments, please let me know. + (see the file place.m for my address) + +Written by: Jose Daniel Munoz Frias. +@end deftypefn + +@node misc, , cacsd, Control Theory +@section Miscellaneous Functions (Not yet properly filed/documented) + + +@deftypefn{Function File } { @var{axvec} =} axis2dlim (@var{axdata}) + determine axis limits for 2-d data(column vectors); leaves a 10% margin + around the plots. + puts in margins of +/- 0.1 if data is one dimensional (or a single point) + +@strong{Inputs} + @var{axdata} nx2 matrix of data [x,y] + +@strong{Outputs} + @var{axvec} vector of axis limits appropriate for call to axis() function +@end deftypefn + +@deftypefn {Function File } { outputs =} mb ( inputs ) +@format + $Revision: 1.9 $ + + +@end format +@end deftypefn + +@deftypefn {Function File } { outputs =} moddemo ( inputs ) +@format + Octave Controls toolbox demo: Model Manipulations demo + Written by David Clem August 15, 1994 + + +@end format +@end deftypefn + +@deftypefn {Function File } { outputs =} prompt ( inputs ) +@format + function prompt([str]) + Prompt user to continue + str: input string. Default value: "\n ---- Press a key to continue ---" + Written by David Clem August 15, 1994 + Modified A. S. Hodel June 1995 + + +@end format +@end deftypefn + +@deftypefn {Function File } { outputs =} rldemo ( inputs ) +@end deftypefn + +@deftypefn {Function File } { outputs =} rlocus ( inputs ) +@format + [rldata, k] = rlocus(sys[,increment,min_k,max_k]) + Displays root locus plot of the specified SISO system. + + ----- --- -------- + --->| + |---|k|---->| SISO |-----------> + ----- --- -------- | + - ^ | + |_____________________________| + +inputs: sys = system data structure + min_k, max_k,increment: minimum, maximum values of k and + the increment used in computing gain values + Outputs: plots the root locus to the screen. + rldata: Data points plotted column 1: real values, column 2: imaginary + values) + k: gains for real axis break points. + + +@end format +@end deftypefn + +@deftypefn {Function File } { outputs =} sortcom ( inputs ) +@format + [yy,idx] = sortcom(xx[,opt]): sort a complex vector + xx: complex vector + opt: sorting option: + "re": real part (default) + "mag": by magnitude + "im": by imaginary part + + if opt != "im" then complex conjugate pairs are grouped together, + a - jb followed by a + jb. + yy: sorted values + idx: permutation vector: yy = xx(idx) + + +@end format +@end deftypefn + +@deftypefn {Function File } { outputs =} ss2tf ( inputs ) +@format + [num,den] = ss2tf(a,b,c,d) + Conversion from tranfer function to state-space. + The state space system + . + x = Ax + Bu + y = Cx + Du + + is converted to a transfer function + + num(s) + G(s)=------- + den(s) + + used internally in system data structure format manipulations + + +@end format +@end deftypefn + +@deftypefn {Function File } { outputs =} ss2zp ( inputs ) +@format + Converts a state space representation to a set of poles and zeros. + + [pol,zer,k] = ss2zp(a,b,c,d) returns the poles and zeros of the state space + system (a,b,c,d). K is a gain associated with the zeros. + + used internally in system data structure format manipulations + + +@end format +@end deftypefn + +@deftypefn {Function File } { outputs =} starp ( inputs ) +@format + + [sys] = starp(P, K, ny, nu) + + Redheffer star product or upper/lower LFT, respectively. + + + +-------+ + --------->| |---------> + | P | + +--->| |---+ ny + | +-------+ | + +-------------------+ + | | + +----------------+ | + | | + | +-------+ | + +--->| |------+ nu + | K | + --------->| |---------> + +-------+ + + If ny and nu "consume" all inputs and outputs of K then the result + is a lower fractional transformation. If ny and nu "consume" all + inputs and outputs of P then the result is an upper fractional + transformation. + + ny and/or nu may be negative (= negative feedback) +@end format +@end deftypefn +@deftypefn {Function File } { outputs =} susball ( inputs ) +@format + +@end format +@end deftypefn +@deftypefn {Function File } { outputs =} swap ( inputs ) +@format + [a1,b1] = swap(a,b) + interchange a and b + + +@end format +@end deftypefn +@deftypefn {Function File } { outputs =} swapcols ( inputs ) +@format + function B = swapcols(A) + permute columns of A into reverse order + + +@end format +@end deftypefn +@deftypefn {Function File } { outputs =} swaprows ( inputs ) +@format + function B = swaprows(A) + permute rows of A into reverse order + + +@end format +@end deftypefn + +@deftypefn {Function File } { outputs =} tf2ss ( inputs ) +@format + Conversion from tranfer function to state-space. + The state space system + . + x = Ax + Bu + y = Cx + Du + + is obtained from a transfer function + + num(s) + G(s)=------- + den(s) + + via the function call [a,b,c,d] = tf2ss(num,den). + The vector 'den' must contain only one row, whereas the vector 'num' + may contain as many rows as there are outputs of the system 'y'. + The state space system matrices obtained from this function will be + in controllable canonical form as described in "Modern Control Theory", + [Brogan, 1991]. + + +@end format +@end deftypefn + + +@deftypefn {Function File } { outputs =} tf2zp ( inputs ) +@format + Converts transfer functions to poles / zeros. + + [zer,pol,k] = tf2zp(num,den) returns the zeros and poles of the SISO system + defined by num/den. K is a gain associated with the system zeros. + + +@end format +@end deftypefn + +@deftypefn {Function File } { } zp2ss +Conversion from zero / pole to state space. +The state space system +@example +. +x = Ax + Bu +y = Cx + Du +@end example +is obtained from a vector of zeros and a vector of poles via the +function call @code{[a,b,c,d] = zp2ss(zer,pol,k)}. +The vectors @samp{zer} and +@samp{pol} may either be row or column vectors. Each zero and pole that +has an imaginary part must have a conjugate in the list. +The number of zeros must not exceed the number of poles. +@samp{k} is @code{zp}-form leading coefficient. +@end deftypefn + +@deftypefn {Function File } { [@var{poly}, @var{rvals}] =} zp2ssg2 (@var{rvals}) +Used internally in @code{zp2ss} +Extract 2 values from @var{rvals} (if possible) and construct + a polynomial with those roots. +@end deftypefn + +@deftypefn {Function File } { } zp2tf + Converts zeros / poles to a transfer function. + +@code{[num,den] = zp2tf(zer,pol,k)} forms the transfer function +@code{num/den} from the vectors of poles and zeros. +@end deftypefn + diff --git a/doc/interpreter/cp-idx.texi b/doc/interpreter/cp-idx.texi deleted file mode 100644 --- a/doc/interpreter/cp-idx.texi +++ /dev/null @@ -1,8 +0,0 @@ -@c Copyright (C) 1996, 1997 John W. Eaton -@c This is part of the Octave manual. -@c For copying conditions, see the file gpl.texi. - -@node Concept Index, Variable Index, Copying, Top -@unnumbered Concept Index - -@printindex cp diff --git a/doc/interpreter/cp-idx.txi b/doc/interpreter/cp-idx.txi new file mode 100644 --- /dev/null +++ b/doc/interpreter/cp-idx.txi @@ -0,0 +1,8 @@ +@c Copyright (C) 1996, 1997 John W. Eaton +@c This is part of the Octave manual. +@c For copying conditions, see the file gpl.texi. + +@node Concept Index, Variable Index, Copying, Top +@unnumbered Concept Index + +@printindex cp diff --git a/doc/interpreter/data.texi b/doc/interpreter/data.texi deleted file mode 100644 --- a/doc/interpreter/data.texi +++ /dev/null @@ -1,174 +0,0 @@ -@c Copyright (C) 1996, 1997 John W. Eaton -@c This is part of the Octave manual. -@c For copying conditions, see the file gpl.texi. - -@node Data Types, Numeric Data Types, Getting Started, Top -@chapter Data Types -@cindex data types - -All versions of Octave include a number of built-in data types, -including real and complex scalars and matrices, character strings, and -a data structure type. - -It is also possible to define new specialized data types by writing a -small amount of C++ code. On some systems, new data types can be loaded -dynamically while Octave is running, so it is not necessary to recompile -all of Octave just to add a new type. @xref{Dynamically Linked -Functions} for more information about Octave's dynamic linking -capabilities. @ref{User-defined Data Types} describes what you must do -to define a new data type for Octave. - -@menu -* Built-in Data Types:: -* User-defined Data Types:: -* Object Sizes:: -@end menu - -@node Built-in Data Types, User-defined Data Types, Data Types, Data Types -@section Built-in Data Types -@cindex data types, built-in -@cindex built-in data types - -The standard built-in data types are real and complex scalars and -matrices, ranges, character strings, and a data structure type. -Additional built-in data types may be added in future versions. If you -need a specialized data type that is not currently provided as a -built-in type, you are encouraged to write your own user-defined data -type and contribute it for distribution in a future release of Octave. - -@menu -* Numeric Objects:: -* String Objects:: -* Data Structure Objects:: -@end menu - -@node Numeric Objects, String Objects, Built-in Data Types, Built-in Data Types -@subsection Numeric Objects -@cindex numeric constant -@cindex numeric value - -Octave's built-in numeric objects include real and complex scalars and -matrices. All built-in numeric data is currently stored as double -precision numbers. On systems that use the IEEE floating point format, -values in the range of approximately -@iftex -@tex - $2.2251\times10^{-308}$ to $1.7977\times10^{308}$ -@end tex -@end iftex -@ifinfo - 2.2251e-308 to 1.7977e+308 -@end ifinfo - can be stored, and the relative precision is approximately -@iftex -@tex - $2.2204\times10^{-16}$. -@end tex -@end iftex -@ifinfo - 2.2204e-16. -@end ifinfo -The exact values are given by the variables @code{realmin}, -@code{realmax}, and @code{eps}, respectively. - -Matrix objects can be of any size, and can be dynamically reshaped and -resized. It is easy to extract individual rows, columns, or submatrices -using a variety of powerful indexing features. @xref{Index Expressions}. - -@xref{Numeric Data Types}, for more information. - -@node String Objects, Data Structure Objects, Numeric Objects, Built-in Data Types -@subsection String Objects -@cindex strings -@cindex character strings -@opindex " -@opindex ' - -A character string in Octave consists of a sequence of characters -enclosed in either double-quote or single-quote marks. Internally, -Octave currently stores strings as matrices of characters. All the -indexing operations that work for matrix objects also work for strings. - -@xref{Strings}, for more information. - -@node Data Structure Objects, , String Objects, Built-in Data Types -@subsection Data Structure Objects -@cindex structures -@cindex data structures - -Octave's data structure type can help you to organize related objects of -different types. The current implementation uses an associative array -with indices limited to strings, but the syntax is more like C-style -structures. - -@xref{Data Structures}, for more information. - -@node User-defined Data Types, Object Sizes, Built-in Data Types, Data Types -@section User-defined Data Types -@cindex user-defined data types -@cindex data types, user-defined - -Someday I hope to expand this to include a complete description of -Octave's mechanism for managing user-defined data types. Until this -feature is documented here, you will have to make do by reading the code -in the @file{ov.h}, @file{ops.h}, and related files from Octave's -@file{src} directory. - -@node Object Sizes, , User-defined Data Types, Data Types -@section Object Sizes - -The following functions allow you to determine the size of a variable or -expression. These functions are defined for all objects. They return -@minus{}1 when the operation doesn't make sense. For example, Octave's -data structure type doesn't have rows or columns, so the @code{rows} and -@code{columns} functions return @minus{}1 for structure arguments. - -@deftypefn {Function File} {} columns (@var{a}) -Return the number of columns of @var{a}. -@end deftypefn - -@deftypefn {Function File} {} rows (@var{a}) -Return the number of rows of @var{a}. -@end deftypefn - -@deftypefn {Function File} {} length (@var{a}) -Return the number of rows of @var{a} or the number of columns of -@var{a}, whichever is larger. -@end deftypefn - -@deftypefn {Function File} {} size (@var{a}, @var{n}) -Return the number rows and columns of @var{a}. - -With one input argument and one output argument, the result is returned -in a 2 element row vector. If there are two output arguments, the -number of rows is assigned to the first, and the number of columns to -the second. For example, - -@example -@group -size ([1, 2; 3, 4; 5, 6]) - @result{} [ 3, 2 ] - -[nr, nc] = size ([1, 2; 3, 4; 5, 6]) - @result{} nr = 3 - @result{} nc = 2 -@end group -@end example - -If given a second argument of either 1 or 2, @code{size} will return -only the row or column dimension. For example - -@example -size ([1, 2; 3, 4; 5, 6], 2) - @result{} 2 -@end example - -@noindent -returns the number of columns in the given matrix. -@end deftypefn - -@deftypefn {Function File} {} isempty (@var{a}) -Return 1 if @var{a} is an empty matrix (either the number of rows, or -the number of columns, or both are zero). Otherwise, return 0. -@end deftypefn - diff --git a/doc/interpreter/data.txi b/doc/interpreter/data.txi new file mode 100644 --- /dev/null +++ b/doc/interpreter/data.txi @@ -0,0 +1,174 @@ +@c Copyright (C) 1996, 1997 John W. Eaton +@c This is part of the Octave manual. +@c For copying conditions, see the file gpl.texi. + +@node Data Types, Numeric Data Types, Getting Started, Top +@chapter Data Types +@cindex data types + +All versions of Octave include a number of built-in data types, +including real and complex scalars and matrices, character strings, and +a data structure type. + +It is also possible to define new specialized data types by writing a +small amount of C++ code. On some systems, new data types can be loaded +dynamically while Octave is running, so it is not necessary to recompile +all of Octave just to add a new type. @xref{Dynamically Linked +Functions} for more information about Octave's dynamic linking +capabilities. @ref{User-defined Data Types} describes what you must do +to define a new data type for Octave. + +@menu +* Built-in Data Types:: +* User-defined Data Types:: +* Object Sizes:: +@end menu + +@node Built-in Data Types, User-defined Data Types, Data Types, Data Types +@section Built-in Data Types +@cindex data types, built-in +@cindex built-in data types + +The standard built-in data types are real and complex scalars and +matrices, ranges, character strings, and a data structure type. +Additional built-in data types may be added in future versions. If you +need a specialized data type that is not currently provided as a +built-in type, you are encouraged to write your own user-defined data +type and contribute it for distribution in a future release of Octave. + +@menu +* Numeric Objects:: +* String Objects:: +* Data Structure Objects:: +@end menu + +@node Numeric Objects, String Objects, Built-in Data Types, Built-in Data Types +@subsection Numeric Objects +@cindex numeric constant +@cindex numeric value + +Octave's built-in numeric objects include real and complex scalars and +matrices. All built-in numeric data is currently stored as double +precision numbers. On systems that use the IEEE floating point format, +values in the range of approximately +@iftex +@tex + $2.2251\times10^{-308}$ to $1.7977\times10^{308}$ +@end tex +@end iftex +@ifinfo + 2.2251e-308 to 1.7977e+308 +@end ifinfo + can be stored, and the relative precision is approximately +@iftex +@tex + $2.2204\times10^{-16}$. +@end tex +@end iftex +@ifinfo + 2.2204e-16. +@end ifinfo +The exact values are given by the variables @code{realmin}, +@code{realmax}, and @code{eps}, respectively. + +Matrix objects can be of any size, and can be dynamically reshaped and +resized. It is easy to extract individual rows, columns, or submatrices +using a variety of powerful indexing features. @xref{Index Expressions}. + +@xref{Numeric Data Types}, for more information. + +@node String Objects, Data Structure Objects, Numeric Objects, Built-in Data Types +@subsection String Objects +@cindex strings +@cindex character strings +@opindex " +@opindex ' + +A character string in Octave consists of a sequence of characters +enclosed in either double-quote or single-quote marks. Internally, +Octave currently stores strings as matrices of characters. All the +indexing operations that work for matrix objects also work for strings. + +@xref{Strings}, for more information. + +@node Data Structure Objects, , String Objects, Built-in Data Types +@subsection Data Structure Objects +@cindex structures +@cindex data structures + +Octave's data structure type can help you to organize related objects of +different types. The current implementation uses an associative array +with indices limited to strings, but the syntax is more like C-style +structures. + +@xref{Data Structures}, for more information. + +@node User-defined Data Types, Object Sizes, Built-in Data Types, Data Types +@section User-defined Data Types +@cindex user-defined data types +@cindex data types, user-defined + +Someday I hope to expand this to include a complete description of +Octave's mechanism for managing user-defined data types. Until this +feature is documented here, you will have to make do by reading the code +in the @file{ov.h}, @file{ops.h}, and related files from Octave's +@file{src} directory. + +@node Object Sizes, , User-defined Data Types, Data Types +@section Object Sizes + +The following functions allow you to determine the size of a variable or +expression. These functions are defined for all objects. They return +@minus{}1 when the operation doesn't make sense. For example, Octave's +data structure type doesn't have rows or columns, so the @code{rows} and +@code{columns} functions return @minus{}1 for structure arguments. + +@deftypefn {Function File} {} columns (@var{a}) +Return the number of columns of @var{a}. +@end deftypefn + +@deftypefn {Function File} {} rows (@var{a}) +Return the number of rows of @var{a}. +@end deftypefn + +@deftypefn {Function File} {} length (@var{a}) +Return the number of rows of @var{a} or the number of columns of +@var{a}, whichever is larger. +@end deftypefn + +@deftypefn {Function File} {} size (@var{a}, @var{n}) +Return the number rows and columns of @var{a}. + +With one input argument and one output argument, the result is returned +in a 2 element row vector. If there are two output arguments, the +number of rows is assigned to the first, and the number of columns to +the second. For example, + +@example +@group +size ([1, 2; 3, 4; 5, 6]) + @result{} [ 3, 2 ] + +[nr, nc] = size ([1, 2; 3, 4; 5, 6]) + @result{} nr = 3 + @result{} nc = 2 +@end group +@end example + +If given a second argument of either 1 or 2, @code{size} will return +only the row or column dimension. For example + +@example +size ([1, 2; 3, 4; 5, 6], 2) + @result{} 2 +@end example + +@noindent +returns the number of columns in the given matrix. +@end deftypefn + +@deftypefn {Function File} {} isempty (@var{a}) +Return 1 if @var{a} is an empty matrix (either the number of rows, or +the number of columns, or both are zero). Otherwise, return 0. +@end deftypefn + diff --git a/doc/interpreter/diffeq.texi b/doc/interpreter/diffeq.texi deleted file mode 100644 --- a/doc/interpreter/diffeq.texi +++ /dev/null @@ -1,189 +0,0 @@ -@c Copyright (C) 1996, 1997 John W. Eaton -@c This is part of the Octave manual. -@c For copying conditions, see the file gpl.texi. - -@node Differential Equations, Optimization, Quadrature, Top -@chapter Differential Equations - -Octave has two built-in functions for solving differential equations. -Both are based on reliable ODE solvers written in Fortran. - -@menu -* Ordinary Differential Equations:: -* Differential-Algebraic Equations:: -@end menu - -@cindex Differential Equations -@cindex ODE -@cindex DAE - -@node Ordinary Differential Equations, Differential-Algebraic Equations, Differential Equations, Differential Equations -@section Ordinary Differential Equations - -The function @code{lsode} can be used to solve ODEs of the form -@iftex -@tex -$$ - {dx\over dt} = f (x, t) -$$ -@end tex -@end iftex -@ifinfo - -@example -dx --- = f (x, t) -dt -@end example -@end ifinfo - -@noindent -using Hindmarsh's ODE solver @sc{Lsode}. - -@deftypefn {Loadable Function} {} lsode (@var{fcn}, @var{x0}, @var{t}, @var{t_crit}) -Return a matrix of @var{x} as a function of @var{t}, given the initial -state of the system @var{x0}. Each row in the result matrix corresponds -to one of the elements in the vector @var{t}. The first element of -@var{t} corresponds to the initial state @var{x0}, so that the first row -of the output is @var{x0}. - -The first argument, @var{fcn}, is a string that names the function to -call to compute the vector of right hand sides for the set of equations. -It must have the form - -@example -@var{xdot} = f (@var{x}, @var{t}) -@end example - -@noindent -where @var{xdot} and @var{x} are vectors and @var{t} is a scalar. - -The fourth argument is optional, and may be used to specify a set of -times that the ODE solver should not integrate past. It is useful for -avoiding difficulties with singularities and points where there is a -discontinuity in the derivative. -@end deftypefn - -Here is an example of solving a set of three differential equations using -@code{lsode}. Given the function - -@cindex oregonator - -@example -@group -function xdot = f (x, t) - - xdot = zeros (3,1); - - xdot(1) = 77.27 * (x(2) - x(1)*x(2) + x(1) \ - - 8.375e-06*x(1)^2); - xdot(2) = (x(3) - x(1)*x(2) - x(2)) / 77.27; - xdot(3) = 0.161*(x(1) - x(3)); - -endfunction -@end group -@end example - -@noindent -and the initial condition @code{x0 = [ 4; 1.1; 4 ]}, the set of -equations can be integrated using the command - -@example -@group -t = linspace (0, 500, 1000); - -y = lsode ("f", x0, t); -@end group -@end example - -If you try this, you will see that the value of the result changes -dramatically between @var{t} = 0 and 5, and again around @var{t} = 305. -A more efficient set of output points might be - -@example -@group -t = [0, logspace (-1, log10(303), 150), \ - logspace (log10(304), log10(500), 150)]; -@end group -@end example - -@deftypefn {Loadable Function} {} lsode_options (@var{opt}, @var{val}) -When called with two arguments, this function allows you set options -parameters for the function @code{lsode}. Given one argument, -@code{lsode_options} returns the value of the corresponding option. If -no arguments are supplied, the names of all the available options and -their current values are displayed. -@end deftypefn - -See Alan C. Hindmarsh, @cite{ODEPACK, A Systematized Collection of ODE -Solvers}, in Scientific Computing, R. S. Stepleman, editor, (1983) for -more information about the inner workings of @code{lsode}. - -@node Differential-Algebraic Equations, , Ordinary Differential Equations, Differential Equations -@section Differential-Algebraic Equations - -The function @code{dassl} can be used to solve DAEs of the form -@iftex -@tex -$$ - 0 = f (\dot{x}, x, t), \qquad x(t=0) = x_0, \dot{x}(t=0) = \dot{x}_0 -$$ -@end tex -@end iftex -@ifinfo - -@example -0 = f (x-dot, x, t), x(t=0) = x_0, x-dot(t=0) = x-dot_0 -@end example -@end ifinfo - -@noindent -using Petzold's DAE solver @sc{Dassl}. - -@deftypefn {Loadable Function} {[@var{x}, @var{xdot}] =} dassl (@var{fcn}, @var{x0}, @var{xdot0}, @var{t}, @var{t_crit}) -Return a matrix of states and their first derivatives with respect to -@var{t}. Each row in the result matrices correspond to one of the -elements in the vector @var{t}. The first element of @var{t} -corresponds to the initial state @var{x0} and derivative @var{xdot0}, so -that the first row of the output @var{x} is @var{x0} and the first row -of the output @var{xdot} is @var{xdot0}. - -The first argument, @var{fcn}, is a string that names the function to -call to compute the vector of residuals for the set of equations. -It must have the form - -@example -@var{res} = f (@var{x}, @var{xdot}, @var{t}) -@end example - -@noindent -where @var{x}, @var{xdot}, and @var{res} are vectors, and @var{t} is a -scalar. - -The second and third arguments to @code{dassl} specify the initial -condition of the states and their derivatives, and the fourth argument -specifies a vector of output times at which the solution is desired, -including the time corresponding to the initial condition. - -The set of initial states and derivatives are not strictly required to -be consistent. In practice, however, @sc{Dassl} is not very good at -determining a consistent set for you, so it is best if you ensure that -the initial values result in the function evaluating to zero. - -The fifth argument is optional, and may be used to specify a set of -times that the DAE solver should not integrate past. It is useful for -avoiding difficulties with singularities and points where there is a -discontinuity in the derivative. -@end deftypefn - -@deftypefn {Loadable Function} {} dassl_options (@var{opt}, @var{val}) -When called with two arguments, this function allows you set options -parameters for the function @code{lsode}. Given one argument, -@code{dassl_options} returns the value of the corresponding option. If -no arguments are supplied, the names of all the available options and -their current values are displayed. -@end deftypefn - -See K. E. Brenan, et al., @cite{Numerical Solution of Initial-Value -Problems in Differential-Algebraic Equations}, North-Holland (1989) for -more information about the implementation of @sc{Dassl}. diff --git a/doc/interpreter/diffeq.txi b/doc/interpreter/diffeq.txi new file mode 100644 --- /dev/null +++ b/doc/interpreter/diffeq.txi @@ -0,0 +1,189 @@ +@c Copyright (C) 1996, 1997 John W. Eaton +@c This is part of the Octave manual. +@c For copying conditions, see the file gpl.texi. + +@node Differential Equations, Optimization, Quadrature, Top +@chapter Differential Equations + +Octave has two built-in functions for solving differential equations. +Both are based on reliable ODE solvers written in Fortran. + +@menu +* Ordinary Differential Equations:: +* Differential-Algebraic Equations:: +@end menu + +@cindex Differential Equations +@cindex ODE +@cindex DAE + +@node Ordinary Differential Equations, Differential-Algebraic Equations, Differential Equations, Differential Equations +@section Ordinary Differential Equations + +The function @code{lsode} can be used to solve ODEs of the form +@iftex +@tex +$$ + {dx\over dt} = f (x, t) +$$ +@end tex +@end iftex +@ifinfo + +@example +dx +-- = f (x, t) +dt +@end example +@end ifinfo + +@noindent +using Hindmarsh's ODE solver @sc{Lsode}. + +@deftypefn {Loadable Function} {} lsode (@var{fcn}, @var{x0}, @var{t}, @var{t_crit}) +Return a matrix of @var{x} as a function of @var{t}, given the initial +state of the system @var{x0}. Each row in the result matrix corresponds +to one of the elements in the vector @var{t}. The first element of +@var{t} corresponds to the initial state @var{x0}, so that the first row +of the output is @var{x0}. + +The first argument, @var{fcn}, is a string that names the function to +call to compute the vector of right hand sides for the set of equations. +It must have the form + +@example +@var{xdot} = f (@var{x}, @var{t}) +@end example + +@noindent +where @var{xdot} and @var{x} are vectors and @var{t} is a scalar. + +The fourth argument is optional, and may be used to specify a set of +times that the ODE solver should not integrate past. It is useful for +avoiding difficulties with singularities and points where there is a +discontinuity in the derivative. +@end deftypefn + +Here is an example of solving a set of three differential equations using +@code{lsode}. Given the function + +@cindex oregonator + +@example +@group +function xdot = f (x, t) + + xdot = zeros (3,1); + + xdot(1) = 77.27 * (x(2) - x(1)*x(2) + x(1) \ + - 8.375e-06*x(1)^2); + xdot(2) = (x(3) - x(1)*x(2) - x(2)) / 77.27; + xdot(3) = 0.161*(x(1) - x(3)); + +endfunction +@end group +@end example + +@noindent +and the initial condition @code{x0 = [ 4; 1.1; 4 ]}, the set of +equations can be integrated using the command + +@example +@group +t = linspace (0, 500, 1000); + +y = lsode ("f", x0, t); +@end group +@end example + +If you try this, you will see that the value of the result changes +dramatically between @var{t} = 0 and 5, and again around @var{t} = 305. +A more efficient set of output points might be + +@example +@group +t = [0, logspace (-1, log10(303), 150), \ + logspace (log10(304), log10(500), 150)]; +@end group +@end example + +@deftypefn {Loadable Function} {} lsode_options (@var{opt}, @var{val}) +When called with two arguments, this function allows you set options +parameters for the function @code{lsode}. Given one argument, +@code{lsode_options} returns the value of the corresponding option. If +no arguments are supplied, the names of all the available options and +their current values are displayed. +@end deftypefn + +See Alan C. Hindmarsh, @cite{ODEPACK, A Systematized Collection of ODE +Solvers}, in Scientific Computing, R. S. Stepleman, editor, (1983) for +more information about the inner workings of @code{lsode}. + +@node Differential-Algebraic Equations, , Ordinary Differential Equations, Differential Equations +@section Differential-Algebraic Equations + +The function @code{dassl} can be used to solve DAEs of the form +@iftex +@tex +$$ + 0 = f (\dot{x}, x, t), \qquad x(t=0) = x_0, \dot{x}(t=0) = \dot{x}_0 +$$ +@end tex +@end iftex +@ifinfo + +@example +0 = f (x-dot, x, t), x(t=0) = x_0, x-dot(t=0) = x-dot_0 +@end example +@end ifinfo + +@noindent +using Petzold's DAE solver @sc{Dassl}. + +@deftypefn {Loadable Function} {[@var{x}, @var{xdot}] =} dassl (@var{fcn}, @var{x0}, @var{xdot0}, @var{t}, @var{t_crit}) +Return a matrix of states and their first derivatives with respect to +@var{t}. Each row in the result matrices correspond to one of the +elements in the vector @var{t}. The first element of @var{t} +corresponds to the initial state @var{x0} and derivative @var{xdot0}, so +that the first row of the output @var{x} is @var{x0} and the first row +of the output @var{xdot} is @var{xdot0}. + +The first argument, @var{fcn}, is a string that names the function to +call to compute the vector of residuals for the set of equations. +It must have the form + +@example +@var{res} = f (@var{x}, @var{xdot}, @var{t}) +@end example + +@noindent +where @var{x}, @var{xdot}, and @var{res} are vectors, and @var{t} is a +scalar. + +The second and third arguments to @code{dassl} specify the initial +condition of the states and their derivatives, and the fourth argument +specifies a vector of output times at which the solution is desired, +including the time corresponding to the initial condition. + +The set of initial states and derivatives are not strictly required to +be consistent. In practice, however, @sc{Dassl} is not very good at +determining a consistent set for you, so it is best if you ensure that +the initial values result in the function evaluating to zero. + +The fifth argument is optional, and may be used to specify a set of +times that the DAE solver should not integrate past. It is useful for +avoiding difficulties with singularities and points where there is a +discontinuity in the derivative. +@end deftypefn + +@deftypefn {Loadable Function} {} dassl_options (@var{opt}, @var{val}) +When called with two arguments, this function allows you set options +parameters for the function @code{lsode}. Given one argument, +@code{dassl_options} returns the value of the corresponding option. If +no arguments are supplied, the names of all the available options and +their current values are displayed. +@end deftypefn + +See K. E. Brenan, et al., @cite{Numerical Solution of Initial-Value +Problems in Differential-Algebraic Equations}, North-Holland (1989) for +more information about the implementation of @sc{Dassl}. diff --git a/doc/interpreter/emacs.texi b/doc/interpreter/emacs.texi deleted file mode 100644 --- a/doc/interpreter/emacs.texi +++ /dev/null @@ -1,504 +0,0 @@ -@c Copyright (C) 1996, 1997 John W. Eaton -@c Written by Kurt Hornik on 1996/05/17. -@c Last updated by KH on 1997/07/31. -@c This is part of the Octave manual. -@c For copying conditions, see the file gpl.texi. - -@node Emacs, Grammar, Installation, Top -@appendix Emacs Octave Support - -The development of Octave code can greatly be facilitated using Emacs -with Octave mode, a major mode for editing Octave files which can e.g.@: -automatically indent the code, do some of the typing (with Abbrev mode) -and show keywords, comments, strings, etc.@: in different faces (with -Font-lock mode on devices that support it). - -It is also possible to run Octave from within Emacs, either by directly -entering commands at the prompt in a buffer in Inferior Octave mode, or -by interacting with Octave from within a file with Octave code. This is -useful in particular for debugging Octave code. - -Finally, you can convince Octave to use the Emacs info reader for -@kbd{help -i}. - -All functionality is provided by the Emacs Lisp package EOS (for ``Emacs -Octave Support''). This chapter describes how to set up and use this -package. - -Please contact if you have any questions -or suggestions on using EOS. - -@menu -* Installing EOS:: -* Using Octave Mode:: -* Running Octave From Within Emacs:: -* Using the Emacs Info Reader for Octave:: -@end menu - -@node Installing EOS, Using Octave Mode, Emacs, Emacs -@appendixsec Installing EOS - -The Emacs package EOS consists of the three files @file{octave-mod.el}, -@file{octave-inf.el}, and @file{octave-hlp.el}. These files, or better -yet their byte-compiled versions, should be somewhere in your Emacs -load-path. - -If you have GNU Emacs with a version number at least as high as 19.35, -you are all set up, because EOS is respectively will be part of GNU -Emacs as of version 19.35. - -Otherwise, copy the three files from the @file{emacs} subdirectory of -the Octave distribution to a place where Emacs can find them (this -depends on how your Emacs was installed). Byte-compile them for speed -if you want. - -@node Using Octave Mode, Running Octave From Within Emacs, Installing EOS, Emacs -@appendixsec Using Octave Mode - -If you are lucky, your sysadmins have already arranged everything so -that Emacs automatically goes into Octave mode whenever you visit an -Octave code file as characterized by its extension @file{.m}. If not, -proceed as follows. - -@enumerate -@item -To begin using Octave mode for all @file{.m} files you visit, add the -following lines to a file loaded by Emacs at startup time, typically -your @file{~/.emacs} file: - -@lisp -(autoload 'octave-mode "octave-mod" nil t) -(setq auto-mode-alist - (cons '("\\.m$" . octave-mode) auto-mode-alist)) -@end lisp - -@item -Finally, to turn on the abbrevs, auto-fill and font-lock features -automatically, also add the following lines to one of the Emacs startup -files: -@lisp -(add-hook 'octave-mode-hook - (lambda () - (abbrev-mode 1) - (auto-fill-mode 1) - (if (eq window-system 'x) - (font-lock-mode 1)))) -@end lisp -See the Emacs manual for more information about how to customize -Font-lock mode. -@end enumerate - -In Octave mode, the following special Emacs commands can be used in -addition to the standard Emacs commands. - -@table @kbd -@item C-h m -Describe the features of Octave mode. - -@item LFD -Reindent the current Octave line, insert a newline and indent the new -line (@code{octave-reindent-then-newline-and-indent}). An abbrev before -point is expanded if @code{abbrev-mode} is non-@code{nil}. - -@item TAB -Indents current Octave line based on its contents and on previous -lines (@code{indent-according-to-mode}). - -@item ; -Insert an ``electric'' semicolon (@code{octave-electric-semi}). If -@code{octave-auto-indent} is non-@code{nil}, reindent the current line. -If @code{octave-auto-newline} is non-@code{nil}, automagically insert a -newline and indent the new line. - -@item ` -Start entering an abbreviation (@code{octave-abbrev-start}). If Abbrev -mode is turned on, typing @kbd{`C-h} or @kbd{`?} lists all abbrevs. -Any other key combination is executed normally. Note that all Octave -abbrevs start with a grave accent. - -@item M-LFD -Break line at point and insert continuation marker and alignment -(@code{octave-split-line}). - -@item M-TAB -Perform completion on Octave symbol preceding point, comparing that -symbol against Octave's reserved words and builtin variables -(@code{octave-complete-symbol}). - -@item M-C-a -Move backward to the beginning of a function -(@code{octave-beginning-of-defun}). -With prefix argument @var{N}, do it that many times if @var{N} is -positive; otherwise, move forward to the @var{N}-th following beginning -of a function. - -@item M-C-e -Move forward to the end of a function (@code{octave-end-of-defun}). -With prefix argument @var{N}, do it that many times if @var{N} is -positive; otherwise, move back to the @var{N}-th preceding end of a -function. - -@item M-C-h -Puts point at beginning and mark at the end of the current Octave -function, i.e., the one containing point or following point -(@code{octave-mark-defun}). - -@item M-C-q -Properly indents the Octave function which contains point -(@code{octave-indent-defun}). - -@item M-; -If there is no comment already on this line, create a code-level comment -(started by two comment characters) if the line is empty, or an in-line -comment (started by one comment character) otherwise -(@code{octave-indent-for-comment}). -Point is left after the start of the comment which is properly aligned. - -@item C-c ; -Puts the comment character @samp{#} (more precisely, the string value of -@code{octave-comment-start}) at the beginning of every line in the -region (@code{octave-comment-region}). With just @kbd{C-u} prefix -argument, uncomment each line in the region. A numeric prefix argument -@var{N} means use @var{N} comment characters. - -@item C-c : -Uncomments every line in the region (@code{octave-uncomment-region}). - -@item C-c C-p -Move one line of Octave code backward, skipping empty and comment lines -(@code{octave-previous-code-line}). With numeric prefix argument -@var{N}, move that many code lines backward (forward if @var{N} is -negative). - -@item C-c C-n -Move one line of Octave code forward, skipping empty and comment lines -(@code{octave-next-code-line}). With numeric prefix argument @var{N}, -move that many code lines forward (backward if @var{N} is negative). - -@item C-c C-a -Move to the `real' beginning of the current line -(@code{octave-beginning-of-line}). If point is in an empty or comment -line, simply go to its beginning; otherwise, move backwards to the -beginning of the first code line which is not inside a continuation -statement, i.e., which does not follow a code line ending in @samp{...} -or @samp{\}, or is inside an open parenthesis list. - -@item C-c C-e -Move to the `real' end of the current line (@code{octave-end-of-line}). -If point is in a code line, move forward to the end of the first Octave -code line which does not end in @samp{...} or @samp{\} or is inside an -open parenthesis list. Otherwise, simply go to the end of the current -line. - -@item C-c M-C-n -Move forward across one balanced begin-end block of Octave code -(@code{octave-forward-block}). With numeric prefix argument @var{N}, -move forward across @var{n} such blocks (backward if @var{N} is -negative). - -@item C-c M-C-p -Move back across one balanced begin-end block of Octave code -(@code{octave-backward-block}). With numeric prefix argument @var{N}, -move backward across @var{N} such blocks (forward if @var{N} is -negative). - -@item C-c M-C-d -Move forward down one begin-end block level of Octave code -(@code{octave-down-block}). With numeric prefix argument, do it that -many times; a negative argument means move backward, but still go down -one level. - -@item C-c M-C-u -Move backward out of one begin-end block level of Octave code -(@code{octave-backward-up-block}). With numeric prefix argument, do it -that many times; a negative argument means move forward, but still to a -less deep spot. - -@item C-c M-C-h -Put point at the beginning of this block, mark at the end -(@code{octave-mark-block}). -The block marked is the one that contains point or follows point. - -@item C-c ] -Close the current block on a separate line (@code{octave-close-block}). -An error is signaled if no block to close is found. - -@item C-c f -Insert a function skeleton, prompting for the function's name, arguments -and return values which have to be entered without parens -(@code{octave-insert-defun}). - -@item C-c C-h -Search the function, operator and variable indices of all info files -with documentation for Octave for entries (@code{octave-help}). If used -interactively, the entry is prompted for with completion. If multiple -matches are found, one can cycle through them using the standard -@samp{,} (@code{Info-index-next}) command of the Info reader. - -The variable @code{octave-help-files} is a list of files to search -through and defaults to @code{'("octave")}. If there is also an Octave -Local Guide with corresponding info file, say, @file{octave-LG}, you can -have @code{octave-help} search both files by -@lisp -(setq octave-help-files '("octave" "octave-LG")) -@end lisp -@noindent -in one of your Emacs startup files. - -@end table - -A common problem is that the @key{RET} key does @emph{not} indent the -line to where the new text should go after inserting the newline. This -is because the standard Emacs convention is that @key{RET} (aka -@kbd{C-m}) just adds a newline, whereas @key{LFD} (aka @kbd{C-j}) adds a -newline and indents it. This is particularly inconvenient for users with -keyboards which do not have a special @key{LFD} key at all; in such -cases, it is typically more convenient to use @key{RET} as the @key{LFD} -key (rather than typing @kbd{C-j}). - -You can make @key{RET} do this by adding -@lisp -(define-key octave-mode-map "\C-m" - 'octave-reindent-then-newline-and-indent) -@end lisp -@noindent -to one of your Emacs startup files. Another, more generally applicable -solution is -@lisp -(defun RET-behaves-as-LFD () - (let ((x (key-binding "\C-j"))) - (local-set-key "\C-m" x))) -(add-hook 'octave-mode-hook 'RET-behaves-as-LFD) -@end lisp -@noindent -(this works for all modes by adding to the startup hooks, without having -to know the particular binding of @key{RET} in that mode!). Similar -considerations apply for using @key{M-RET} as @key{M-LFD}. As Barry -A. Warsaw says in the documentation for his -@code{cc-mode}, ``This is a very common question. @code{:-)} If you want -this to be the default behavior, don't lobby me, lobby RMS!'' - -The following variables can be used to customize Octave mode. - -@table @code -@item octave-auto-indent -Non-@code{nil} means auto-indent the current line after a semicolon or -space. Default is @code{nil}. - -@item octave-auto-newline -Non-@code{nil} means auto-insert a newline and indent after semicolons -are typed. The default value is @code{nil}. - -@item octave-blink-matching-block -Non-@code{nil} means show matching begin of block when inserting a space, -newline or @samp{;} after an else or end keyword. Default is @code{t}. -This is an extremely useful feature for automatically verifying that the -keywords match---if they don't, an error message is displayed. - -@item octave-block-offset -Extra indentation applied to statements in block structures. -Default is 2. - -@item octave-continuation-offset -Extra indentation applied to Octave continuation lines. -Default is 4. - -@item octave-continuation-string -String used for Octave continuation lines. -Normally @samp{\}. - -@item octave-mode-startup-message -If @code{t} (default), a startup message is displayed when Octave mode -is called. - -@end table - -If Font Lock mode is enabled, Octave mode will display -@itemize @bullet -@item -strings in @code{font-lock-string-face} -@item -comments in @code{font-lock-comment-face} -@item -the Octave reserved words (such as all block keywords) and the text -functions (such as @samp{cd} or @samp{who}) which are also reserved -using @code{font-lock-keyword-face} -@item -the builtin operators (@samp{&&}, @samp{<>}, @dots{}) using -@code{font-lock-reference-face} -@item -the builtin variables (such as @samp{prefer_column_vectors}, @samp{NaN} -or @samp{LOADPATH}) in @code{font-lock-variable-name-face} -@item -and the function names in function declarations in -@code{font-lock-function-name-face}. -@end itemize - -There is also rudimentary support for Imenu (currently, function names -can be indexed). - -@cindex TAGS -@cindex Emacs TAGS files -@cindex @code{otags} -You can generate TAGS files for Emacs from Octave @file{.m} files using -the shell script @code{otags} that is installed alongside your copy of -Octave. - -Customization of Octave mode can be performed by modification of the -variable @code{octave-mode-hook}. If the value of this variable is -non-@code{nil}, turning on Octave mode calls its value. - -If you discover a problem with Octave mode, you can conveniently send a -bug report using @kbd{C-c C-b} (@code{octave-submit-bug-report}). This -automatically sets up a mail buffer with version information already -added. You just need to add a description of the problem, including a -reproducible test case and send the message. - -@node Running Octave From Within Emacs, Using the Emacs Info Reader for Octave, Using Octave Mode, Emacs -@appendixsec Running Octave From Within Emacs - -The package @file{octave} provides commands for running an inferior -Octave process in a special Emacs buffer. Use -@lisp -M-x run-octave -@end lisp -@noindent -to directly start an inferior Octave process. If Emacs does not know -about this command, add the line -@lisp -(autoload 'run-octave "octave-inf" nil t) -@end lisp -@noindent -to your @file{.emacs} file. - -This will start Octave in a special buffer the name of which is -specified by the variable @code{inferior-octave-buffer} and defaults to -@code{"*Inferior Octave*"}. From within this buffer, you can -interact with the inferior Octave process `as usual', i.e., by entering -Octave commands at the prompt. The buffer is in Inferior Octave mode, -which is derived from the standard Comint mode, a major mode for -interacting with an inferior interpreter. See the documentation for -@code{comint-mode} for more details, and use @kbd{C-h b} to find out -about available special keybindings. - -You can also communicate with an inferior Octave process from within -files with Octave code (i.e., buffers in Octave mode), using the -following commands. - -@table @kbd -@item C-c i l -Send the current line to the inferior Octave process -(@code{octave-send-line}). -With positive prefix argument @var{N}, send that many lines. -If @code{octave-send-line-auto-forward} is non-@code{nil}, go to the -next unsent code line. -@item C-c i b -Send the current block to the inferior Octave process -(@code{octave-send-block}). -@item C-c i f -Send the current function to the inferior Octave process -(@code{octave-send-defun}). -@item C-c i r -Send the region to the inferior Octave process -(@code{octave-send-region}). -@item C-c i s -Make sure that `inferior-octave-buffer' is displayed -(@code{octave-show-process-buffer}). -@item C-c i h -Delete all windows that display the inferior Octave buffer -(@code{octave-hide-process-buffer}). -@item C-c i k -Kill the inferior Octave process and its buffer -(@code{octave-kill-process}). -@end table - -The effect of the commands which send code to the Octave process can be -customized by the following variables. -@table @code -@item octave-send-echo-input -Non-@code{nil} means echo input sent to the inferior Octave process. -Default is @code{t}. - -@item octave-send-show-buffer -Non-@code{nil} means display the buffer running the Octave process after -sending a command (but without selecting it). -Default is @code{t}. -@end table - -If you send code and there is no inferior Octave process yet, it will be -started automatically. - -The startup of the inferior Octave process is highly customizable. -The variable @code{inferior-octave-startup-args} can be used for -specifying command lines arguments to be passed to Octave on startup -as a list of strings. For example, to suppress the startup message and -use `traditional' mode, set this to @code{'("-q" "--traditional")}. -You can also specify a startup file of Octave commands to be loaded on -startup; note that these commands will not produce any visible output -in the process buffer. Which file to use is controlled by the variable -@code{inferior-octave-startup-file}. If this is @code{nil}, the file -@file{~/.emacs-octave} is used if it exists. - -And finally, @code{inferior-octave-mode-hook} is run after starting the -process and putting its buffer into Inferior Octave mode. Hence, if you -like the up and down arrow keys to behave in the interaction buffer as -in the shell, and you want this buffer to use nice colors, add -@lisp -(add-hook 'inferior-octave-mode-hook - (lambda () - (turn-on-font-lock) - (define-key inferior-octave-mode-map [up] - 'comint-previous-input) - (define-key inferior-octave-mode-map [down] - 'comint-next-input))) -@end lisp -@noindent -to your @file{.emacs} file. You could also swap the roles of @kbd{C-a} -(@code{beginning-of-line}) and @code{C-c C-a} (@code{comint-bol}) using -this hook. - -@quotation -@strong{Note:} -If you set your Octave prompts to something different from the defaults, -make sure that @code{inferior-octave-prompt} matches them. -Otherwise, @emph{nothing} will work, because Emacs will have no idea -when Octave is waiting for input, or done sending output. -@end quotation - -@node Using the Emacs Info Reader for Octave, , Running Octave From Within Emacs, Emacs -@appendixsec Using the Emacs Info Reader for Octave - -You can also set up the Emacs Info reader for dealing with the results -of Octave's @samp{help -i}. For this, the package @file{gnuserv} needs -to be installed, which unfortunately still does not come with GNU Emacs -(it does with XEmacs). It can be retrieved from any GNU Emacs Lisp Code -Directory archive, e.g.@: -@url{ftp://ftp.cis.ohio-state.edu/pub/gnu/emacs/elisp-archive}, -in the @file{packages} subdirectory. The alpha version of an enhanced -version of gnuserv is available at -@url{ftp://ftp.wellfleet.com/netman/psmith/emacs/gnuserv-2.1alpha.tar.gz}. - -If @file{gnuserv} is installed, add the lines -@lisp -(autoload 'octave-help "octave-hlp" nil t) -(require 'gnuserv) -(gnuserv-start) -@end lisp -@noindent -to your @file{.emacs} file. - -You can use either `plain' Emacs Info or the function @code{octave-help} -as your Octave info reader (for @samp{help -i}). In the former case, -set the Octave variable @code{INFO_PROGRAM} to @code{"info-emacs-info"}. -The latter is perhaps more attractive because it allows to look up keys -in the indices of @emph{several} info files related to Octave (provided -that the Emacs variable @code{octave-help-files} is set correctly). In -this case, set @code{INFO_PROGRAM} to @code{"info-emacs-octave-help"}. - -If you use Octave from within Emacs, these settings are best done in the -@file{~/.emacs-octave} startup file (or the file pointed to by the Emacs -variable @code{inferior-octave-startup-file}). - -@c Local Variables: -@c TeX-command-default: "Texinfo" -@c End: diff --git a/doc/interpreter/emacs.txi b/doc/interpreter/emacs.txi new file mode 100644 --- /dev/null +++ b/doc/interpreter/emacs.txi @@ -0,0 +1,504 @@ +@c Copyright (C) 1996, 1997 John W. Eaton +@c Written by Kurt Hornik on 1996/05/17. +@c Last updated by KH on 1997/07/31. +@c This is part of the Octave manual. +@c For copying conditions, see the file gpl.texi. + +@node Emacs, Grammar, Installation, Top +@appendix Emacs Octave Support + +The development of Octave code can greatly be facilitated using Emacs +with Octave mode, a major mode for editing Octave files which can e.g.@: +automatically indent the code, do some of the typing (with Abbrev mode) +and show keywords, comments, strings, etc.@: in different faces (with +Font-lock mode on devices that support it). + +It is also possible to run Octave from within Emacs, either by directly +entering commands at the prompt in a buffer in Inferior Octave mode, or +by interacting with Octave from within a file with Octave code. This is +useful in particular for debugging Octave code. + +Finally, you can convince Octave to use the Emacs info reader for +@kbd{help -i}. + +All functionality is provided by the Emacs Lisp package EOS (for ``Emacs +Octave Support''). This chapter describes how to set up and use this +package. + +Please contact if you have any questions +or suggestions on using EOS. + +@menu +* Installing EOS:: +* Using Octave Mode:: +* Running Octave From Within Emacs:: +* Using the Emacs Info Reader for Octave:: +@end menu + +@node Installing EOS, Using Octave Mode, Emacs, Emacs +@appendixsec Installing EOS + +The Emacs package EOS consists of the three files @file{octave-mod.el}, +@file{octave-inf.el}, and @file{octave-hlp.el}. These files, or better +yet their byte-compiled versions, should be somewhere in your Emacs +load-path. + +If you have GNU Emacs with a version number at least as high as 19.35, +you are all set up, because EOS is respectively will be part of GNU +Emacs as of version 19.35. + +Otherwise, copy the three files from the @file{emacs} subdirectory of +the Octave distribution to a place where Emacs can find them (this +depends on how your Emacs was installed). Byte-compile them for speed +if you want. + +@node Using Octave Mode, Running Octave From Within Emacs, Installing EOS, Emacs +@appendixsec Using Octave Mode + +If you are lucky, your sysadmins have already arranged everything so +that Emacs automatically goes into Octave mode whenever you visit an +Octave code file as characterized by its extension @file{.m}. If not, +proceed as follows. + +@enumerate +@item +To begin using Octave mode for all @file{.m} files you visit, add the +following lines to a file loaded by Emacs at startup time, typically +your @file{~/.emacs} file: + +@lisp +(autoload 'octave-mode "octave-mod" nil t) +(setq auto-mode-alist + (cons '("\\.m$" . octave-mode) auto-mode-alist)) +@end lisp + +@item +Finally, to turn on the abbrevs, auto-fill and font-lock features +automatically, also add the following lines to one of the Emacs startup +files: +@lisp +(add-hook 'octave-mode-hook + (lambda () + (abbrev-mode 1) + (auto-fill-mode 1) + (if (eq window-system 'x) + (font-lock-mode 1)))) +@end lisp +See the Emacs manual for more information about how to customize +Font-lock mode. +@end enumerate + +In Octave mode, the following special Emacs commands can be used in +addition to the standard Emacs commands. + +@table @kbd +@item C-h m +Describe the features of Octave mode. + +@item LFD +Reindent the current Octave line, insert a newline and indent the new +line (@code{octave-reindent-then-newline-and-indent}). An abbrev before +point is expanded if @code{abbrev-mode} is non-@code{nil}. + +@item TAB +Indents current Octave line based on its contents and on previous +lines (@code{indent-according-to-mode}). + +@item ; +Insert an ``electric'' semicolon (@code{octave-electric-semi}). If +@code{octave-auto-indent} is non-@code{nil}, reindent the current line. +If @code{octave-auto-newline} is non-@code{nil}, automagically insert a +newline and indent the new line. + +@item ` +Start entering an abbreviation (@code{octave-abbrev-start}). If Abbrev +mode is turned on, typing @kbd{`C-h} or @kbd{`?} lists all abbrevs. +Any other key combination is executed normally. Note that all Octave +abbrevs start with a grave accent. + +@item M-LFD +Break line at point and insert continuation marker and alignment +(@code{octave-split-line}). + +@item M-TAB +Perform completion on Octave symbol preceding point, comparing that +symbol against Octave's reserved words and builtin variables +(@code{octave-complete-symbol}). + +@item M-C-a +Move backward to the beginning of a function +(@code{octave-beginning-of-defun}). +With prefix argument @var{N}, do it that many times if @var{N} is +positive; otherwise, move forward to the @var{N}-th following beginning +of a function. + +@item M-C-e +Move forward to the end of a function (@code{octave-end-of-defun}). +With prefix argument @var{N}, do it that many times if @var{N} is +positive; otherwise, move back to the @var{N}-th preceding end of a +function. + +@item M-C-h +Puts point at beginning and mark at the end of the current Octave +function, i.e., the one containing point or following point +(@code{octave-mark-defun}). + +@item M-C-q +Properly indents the Octave function which contains point +(@code{octave-indent-defun}). + +@item M-; +If there is no comment already on this line, create a code-level comment +(started by two comment characters) if the line is empty, or an in-line +comment (started by one comment character) otherwise +(@code{octave-indent-for-comment}). +Point is left after the start of the comment which is properly aligned. + +@item C-c ; +Puts the comment character @samp{#} (more precisely, the string value of +@code{octave-comment-start}) at the beginning of every line in the +region (@code{octave-comment-region}). With just @kbd{C-u} prefix +argument, uncomment each line in the region. A numeric prefix argument +@var{N} means use @var{N} comment characters. + +@item C-c : +Uncomments every line in the region (@code{octave-uncomment-region}). + +@item C-c C-p +Move one line of Octave code backward, skipping empty and comment lines +(@code{octave-previous-code-line}). With numeric prefix argument +@var{N}, move that many code lines backward (forward if @var{N} is +negative). + +@item C-c C-n +Move one line of Octave code forward, skipping empty and comment lines +(@code{octave-next-code-line}). With numeric prefix argument @var{N}, +move that many code lines forward (backward if @var{N} is negative). + +@item C-c C-a +Move to the `real' beginning of the current line +(@code{octave-beginning-of-line}). If point is in an empty or comment +line, simply go to its beginning; otherwise, move backwards to the +beginning of the first code line which is not inside a continuation +statement, i.e., which does not follow a code line ending in @samp{...} +or @samp{\}, or is inside an open parenthesis list. + +@item C-c C-e +Move to the `real' end of the current line (@code{octave-end-of-line}). +If point is in a code line, move forward to the end of the first Octave +code line which does not end in @samp{...} or @samp{\} or is inside an +open parenthesis list. Otherwise, simply go to the end of the current +line. + +@item C-c M-C-n +Move forward across one balanced begin-end block of Octave code +(@code{octave-forward-block}). With numeric prefix argument @var{N}, +move forward across @var{n} such blocks (backward if @var{N} is +negative). + +@item C-c M-C-p +Move back across one balanced begin-end block of Octave code +(@code{octave-backward-block}). With numeric prefix argument @var{N}, +move backward across @var{N} such blocks (forward if @var{N} is +negative). + +@item C-c M-C-d +Move forward down one begin-end block level of Octave code +(@code{octave-down-block}). With numeric prefix argument, do it that +many times; a negative argument means move backward, but still go down +one level. + +@item C-c M-C-u +Move backward out of one begin-end block level of Octave code +(@code{octave-backward-up-block}). With numeric prefix argument, do it +that many times; a negative argument means move forward, but still to a +less deep spot. + +@item C-c M-C-h +Put point at the beginning of this block, mark at the end +(@code{octave-mark-block}). +The block marked is the one that contains point or follows point. + +@item C-c ] +Close the current block on a separate line (@code{octave-close-block}). +An error is signaled if no block to close is found. + +@item C-c f +Insert a function skeleton, prompting for the function's name, arguments +and return values which have to be entered without parens +(@code{octave-insert-defun}). + +@item C-c C-h +Search the function, operator and variable indices of all info files +with documentation for Octave for entries (@code{octave-help}). If used +interactively, the entry is prompted for with completion. If multiple +matches are found, one can cycle through them using the standard +@samp{,} (@code{Info-index-next}) command of the Info reader. + +The variable @code{octave-help-files} is a list of files to search +through and defaults to @code{'("octave")}. If there is also an Octave +Local Guide with corresponding info file, say, @file{octave-LG}, you can +have @code{octave-help} search both files by +@lisp +(setq octave-help-files '("octave" "octave-LG")) +@end lisp +@noindent +in one of your Emacs startup files. + +@end table + +A common problem is that the @key{RET} key does @emph{not} indent the +line to where the new text should go after inserting the newline. This +is because the standard Emacs convention is that @key{RET} (aka +@kbd{C-m}) just adds a newline, whereas @key{LFD} (aka @kbd{C-j}) adds a +newline and indents it. This is particularly inconvenient for users with +keyboards which do not have a special @key{LFD} key at all; in such +cases, it is typically more convenient to use @key{RET} as the @key{LFD} +key (rather than typing @kbd{C-j}). + +You can make @key{RET} do this by adding +@lisp +(define-key octave-mode-map "\C-m" + 'octave-reindent-then-newline-and-indent) +@end lisp +@noindent +to one of your Emacs startup files. Another, more generally applicable +solution is +@lisp +(defun RET-behaves-as-LFD () + (let ((x (key-binding "\C-j"))) + (local-set-key "\C-m" x))) +(add-hook 'octave-mode-hook 'RET-behaves-as-LFD) +@end lisp +@noindent +(this works for all modes by adding to the startup hooks, without having +to know the particular binding of @key{RET} in that mode!). Similar +considerations apply for using @key{M-RET} as @key{M-LFD}. As Barry +A. Warsaw says in the documentation for his +@code{cc-mode}, ``This is a very common question. @code{:-)} If you want +this to be the default behavior, don't lobby me, lobby RMS!'' + +The following variables can be used to customize Octave mode. + +@table @code +@item octave-auto-indent +Non-@code{nil} means auto-indent the current line after a semicolon or +space. Default is @code{nil}. + +@item octave-auto-newline +Non-@code{nil} means auto-insert a newline and indent after semicolons +are typed. The default value is @code{nil}. + +@item octave-blink-matching-block +Non-@code{nil} means show matching begin of block when inserting a space, +newline or @samp{;} after an else or end keyword. Default is @code{t}. +This is an extremely useful feature for automatically verifying that the +keywords match---if they don't, an error message is displayed. + +@item octave-block-offset +Extra indentation applied to statements in block structures. +Default is 2. + +@item octave-continuation-offset +Extra indentation applied to Octave continuation lines. +Default is 4. + +@item octave-continuation-string +String used for Octave continuation lines. +Normally @samp{\}. + +@item octave-mode-startup-message +If @code{t} (default), a startup message is displayed when Octave mode +is called. + +@end table + +If Font Lock mode is enabled, Octave mode will display +@itemize @bullet +@item +strings in @code{font-lock-string-face} +@item +comments in @code{font-lock-comment-face} +@item +the Octave reserved words (such as all block keywords) and the text +functions (such as @samp{cd} or @samp{who}) which are also reserved +using @code{font-lock-keyword-face} +@item +the builtin operators (@samp{&&}, @samp{<>}, @dots{}) using +@code{font-lock-reference-face} +@item +the builtin variables (such as @samp{prefer_column_vectors}, @samp{NaN} +or @samp{LOADPATH}) in @code{font-lock-variable-name-face} +@item +and the function names in function declarations in +@code{font-lock-function-name-face}. +@end itemize + +There is also rudimentary support for Imenu (currently, function names +can be indexed). + +@cindex TAGS +@cindex Emacs TAGS files +@cindex @code{otags} +You can generate TAGS files for Emacs from Octave @file{.m} files using +the shell script @code{otags} that is installed alongside your copy of +Octave. + +Customization of Octave mode can be performed by modification of the +variable @code{octave-mode-hook}. If the value of this variable is +non-@code{nil}, turning on Octave mode calls its value. + +If you discover a problem with Octave mode, you can conveniently send a +bug report using @kbd{C-c C-b} (@code{octave-submit-bug-report}). This +automatically sets up a mail buffer with version information already +added. You just need to add a description of the problem, including a +reproducible test case and send the message. + +@node Running Octave From Within Emacs, Using the Emacs Info Reader for Octave, Using Octave Mode, Emacs +@appendixsec Running Octave From Within Emacs + +The package @file{octave} provides commands for running an inferior +Octave process in a special Emacs buffer. Use +@lisp +M-x run-octave +@end lisp +@noindent +to directly start an inferior Octave process. If Emacs does not know +about this command, add the line +@lisp +(autoload 'run-octave "octave-inf" nil t) +@end lisp +@noindent +to your @file{.emacs} file. + +This will start Octave in a special buffer the name of which is +specified by the variable @code{inferior-octave-buffer} and defaults to +@code{"*Inferior Octave*"}. From within this buffer, you can +interact with the inferior Octave process `as usual', i.e., by entering +Octave commands at the prompt. The buffer is in Inferior Octave mode, +which is derived from the standard Comint mode, a major mode for +interacting with an inferior interpreter. See the documentation for +@code{comint-mode} for more details, and use @kbd{C-h b} to find out +about available special keybindings. + +You can also communicate with an inferior Octave process from within +files with Octave code (i.e., buffers in Octave mode), using the +following commands. + +@table @kbd +@item C-c i l +Send the current line to the inferior Octave process +(@code{octave-send-line}). +With positive prefix argument @var{N}, send that many lines. +If @code{octave-send-line-auto-forward} is non-@code{nil}, go to the +next unsent code line. +@item C-c i b +Send the current block to the inferior Octave process +(@code{octave-send-block}). +@item C-c i f +Send the current function to the inferior Octave process +(@code{octave-send-defun}). +@item C-c i r +Send the region to the inferior Octave process +(@code{octave-send-region}). +@item C-c i s +Make sure that `inferior-octave-buffer' is displayed +(@code{octave-show-process-buffer}). +@item C-c i h +Delete all windows that display the inferior Octave buffer +(@code{octave-hide-process-buffer}). +@item C-c i k +Kill the inferior Octave process and its buffer +(@code{octave-kill-process}). +@end table + +The effect of the commands which send code to the Octave process can be +customized by the following variables. +@table @code +@item octave-send-echo-input +Non-@code{nil} means echo input sent to the inferior Octave process. +Default is @code{t}. + +@item octave-send-show-buffer +Non-@code{nil} means display the buffer running the Octave process after +sending a command (but without selecting it). +Default is @code{t}. +@end table + +If you send code and there is no inferior Octave process yet, it will be +started automatically. + +The startup of the inferior Octave process is highly customizable. +The variable @code{inferior-octave-startup-args} can be used for +specifying command lines arguments to be passed to Octave on startup +as a list of strings. For example, to suppress the startup message and +use `traditional' mode, set this to @code{'("-q" "--traditional")}. +You can also specify a startup file of Octave commands to be loaded on +startup; note that these commands will not produce any visible output +in the process buffer. Which file to use is controlled by the variable +@code{inferior-octave-startup-file}. If this is @code{nil}, the file +@file{~/.emacs-octave} is used if it exists. + +And finally, @code{inferior-octave-mode-hook} is run after starting the +process and putting its buffer into Inferior Octave mode. Hence, if you +like the up and down arrow keys to behave in the interaction buffer as +in the shell, and you want this buffer to use nice colors, add +@lisp +(add-hook 'inferior-octave-mode-hook + (lambda () + (turn-on-font-lock) + (define-key inferior-octave-mode-map [up] + 'comint-previous-input) + (define-key inferior-octave-mode-map [down] + 'comint-next-input))) +@end lisp +@noindent +to your @file{.emacs} file. You could also swap the roles of @kbd{C-a} +(@code{beginning-of-line}) and @code{C-c C-a} (@code{comint-bol}) using +this hook. + +@quotation +@strong{Note:} +If you set your Octave prompts to something different from the defaults, +make sure that @code{inferior-octave-prompt} matches them. +Otherwise, @emph{nothing} will work, because Emacs will have no idea +when Octave is waiting for input, or done sending output. +@end quotation + +@node Using the Emacs Info Reader for Octave, , Running Octave From Within Emacs, Emacs +@appendixsec Using the Emacs Info Reader for Octave + +You can also set up the Emacs Info reader for dealing with the results +of Octave's @samp{help -i}. For this, the package @file{gnuserv} needs +to be installed, which unfortunately still does not come with GNU Emacs +(it does with XEmacs). It can be retrieved from any GNU Emacs Lisp Code +Directory archive, e.g.@: +@url{ftp://ftp.cis.ohio-state.edu/pub/gnu/emacs/elisp-archive}, +in the @file{packages} subdirectory. The alpha version of an enhanced +version of gnuserv is available at +@url{ftp://ftp.wellfleet.com/netman/psmith/emacs/gnuserv-2.1alpha.tar.gz}. + +If @file{gnuserv} is installed, add the lines +@lisp +(autoload 'octave-help "octave-hlp" nil t) +(require 'gnuserv) +(gnuserv-start) +@end lisp +@noindent +to your @file{.emacs} file. + +You can use either `plain' Emacs Info or the function @code{octave-help} +as your Octave info reader (for @samp{help -i}). In the former case, +set the Octave variable @code{INFO_PROGRAM} to @code{"info-emacs-info"}. +The latter is perhaps more attractive because it allows to look up keys +in the indices of @emph{several} info files related to Octave (provided +that the Emacs variable @code{octave-help-files} is set correctly). In +this case, set @code{INFO_PROGRAM} to @code{"info-emacs-octave-help"}. + +If you use Octave from within Emacs, these settings are best done in the +@file{~/.emacs-octave} startup file (or the file pointed to by the Emacs +variable @code{inferior-octave-startup-file}). + +@c Local Variables: +@c TeX-command-default: "Texinfo" +@c End: diff --git a/doc/interpreter/eos.txi b/doc/interpreter/eos.txi new file mode 100644 --- /dev/null +++ b/doc/interpreter/eos.txi @@ -0,0 +1,497 @@ +@c Copyright (C) 1996, 1997 John W. Eaton +@c Written by Kurt Hornik on 1996/05/17. +@c Last updated by KH on 1997/07/31. +@c This is part of the Octave manual. +@c For copying conditions, see the file gpl.texi. + +@node Emacs +@chapter Emacs Octave Support + +The development of Octave code can greatly be facilitated using Emacs +with Octave mode, a major mode for editing Octave files which can e.g.@: +automatically indent the code, do some of the typing (with Abbrev mode) +and show keywords, comments, strings, etc.@: in different faces (with +Font-lock mode on devices that support it). + +It is also possible to run Octave from within Emacs, either by directly +entering commands at the prompt in a buffer in Inferior Octave mode, or +by interacting with Octave from within a file with Octave code. This is +useful in particular for debugging Octave code. + +Finally, you can convince Octave to use the Emacs info reader for +@kbd{help -i}. + +All functionality is provided by the Emacs Lisp package EOS (for ``Emacs +Octave Support''). This chapter describes how to set up and use this +package. + +Please contact if you have any questions +or suggestions on using EOS. + +@menu +* Installing EOS:: +* Using Octave Mode:: +* Running Octave From Within Emacs:: +* Using the Emacs Info Reader for Octave:: +@end menu + +@node Installing EOS, Using Octave Mode, Emacs, Emacs +@section Installing EOS + +The Emacs package EOS consists of the three files @file{octave-mod.el}, +@file{octave-inf.el}, and @file{octave-hlp.el}. These files, or better +yet their byte-compiled versions, should be somewhere in your Emacs +load-path. + +If you have GNU Emacs with a version number at least as high as 19.35, +you are all set up, because EOS is respectively will be part of GNU +Emacs as of version 19.35. + +Otherwise, copy the three files from the @file{emacs} subdirectory of +the Octave distribution to a place where Emacs can find them (this +depends on how your Emacs was installed). Byte-compile them for speed +if you want. + +@node Using Octave Mode, Running Octave From Within Emacs, Installing EOS, Emacs +@section Using Octave Mode + +If you are lucky, your sysadmins have already arranged everything so +that Emacs automatically goes into Octave mode whenever you visit an +Octave code file as characterized by its extension @file{.m}. If not, +proceed as follows. + +@enumerate +@item +To begin using Octave mode for all @file{.m} files you visit, add the +following lines to a file loaded by Emacs at startup time, typically +your @file{~/.emacs} file: + +@lisp +(autoload 'octave-mode "octave-mod" nil t) +(setq auto-mode-alist + (cons '(\"\\\\.m$\" . octave-mode) auto-mode-alist)) +@end lisp + +@item +Finally, to turn on the abbrevs, auto-fill and font-lock features +automatically, also add the following lines to one of the Emacs startup +files: +@lisp +(add-hook 'octave-mode-hook + (lambda () + (abbrev-mode 1) + (auto-fill-mode 1) + (if (eq window-system 'x) + (font-lock-mode 1)))) +@end lisp +See the Emacs manual for more information about how to customize +Font-lock mode. +@end enumerate + +In Octave mode, the following special Emacs commands can be used in +addition to the standard Emacs commands. + +@table @kbd +@item C-h m +Describe the features of Octave mode. + +@item LFD +Reindent the current Octave line, insert a newline and indent the new +line (@code{octave-reindent-then-newline-and-indent}). An abbrev before +point is expanded if @code{abbrev-mode} is non-@code{nil}. + +@item TAB +Indents current Octave line based on its contents and on previous +lines (@code{indent-according-to-mode}). + +@item ; +Insert an ``electric'' semicolon (@code{octave-electric-semi}). If +@code{octave-auto-indent} is non-@code{nil}, reindent the current line. +If @code{octave-auto-newline} is non-@code{nil}, automagically insert a +newline and indent the new line. + +@item ` +Start entering an abbreviation (@code{octave-abbrev-start}). If Abbrev +mode is turned on, typing @kbd{`C-h} or @kbd{`?} lists all abbrevs. +Any other key combination is executed normally. Note that all Octave +abbrevs start with a grave accent. + +@item M-LFD +Break line at point and insert continuation marker and alignment +(@code{octave-split-line}). + +@item M-TAB +Perform completion on Octave symbol preceding point, comparing that +symbol against Octave's reserved words and builtin variables +(@code{octave-complete-symbol}). + +@item M-C-a +Move backward to the beginning of a function +(@code{octave-beginning-of-defun}). +With prefix argument @var{N}, do it that many times if @var{N} is +positive; otherwise, move forward to the @var{N}-th following beginning +of a function. + +@item M-C-e +Move forward to the end of a function (@code{octave-end-of-defun}). +With prefix argument @var{N}, do it that many times if @var{N} is +positive; otherwise, move back to the @var{N}-th preceding end of a +function. + +@item M-C-h +Puts point at beginning and mark at the end of the current Octave +function, i.e., the one containing point or following point +(@code{octave-mark-defun}). + +@item M-C-q +Properly indents the Octave function which contains point +(@code{octave-indent-defun}). + +@item M-; +If there is no comment already on this line, create a code-level comment +(started by two comment characters) if the line is empty, or an in-line +comment (started by one comment character) otherwise +(@code{octave-indent-for-comment}). +Point is left after the start of the comment which is properly aligned. + +@item C-c ; +Puts the comment character @samp{#} (more precisely, the string value of +@code{octave-comment-start}) at the beginning of every line in the +region (@code{octave-comment-region}). With just @kbd{C-u} prefix +argument, uncomment each line in the region. A numeric prefix argument +@var{N} means use @var{N} comment characters. + +@item C-c : +Uncomments every line in the region (@code{octave-uncomment-region}). + +@item C-c C-p +Move one line of Octave code backward, skipping empty and comment lines +(@code{octave-previous-code-line}). With numeric prefix argument +@var{N}, move that many code lines backward (forward if @var{N} is +negative). + +@item C-c C-n +Move one line of Octave code forward, skipping empty and comment lines +(@code{octave-next-code-line}). With numeric prefix argument @var{N}, +move that many code lines forward (backward if @var{N} is negative). + +@item C-c C-a +Move to the `real' beginning of the current line +(@code{octave-beginning-of-line}). If point is in an empty or comment +line, simply go to its beginning; otherwise, move backwards to the +beginning of the first code line which is not inside a continuation +statement, i.e., which does not follow a code line ending in @samp{...} +or @samp{\}, or is inside an open parenthesis list. + +@item C-c C-e +Move to the `real' end of the current line (@code{octave-end-of-line}). +If point is in a code line, move forward to the end of the first Octave +code line which does not end in @samp{...} or @samp{\} or is inside an +open parenthesis list. Otherwise, simply go to the end of the current +line. + +@item C-c M-C-n +Move forward across one balanced begin-end block of Octave code +(@code{octave-forward-block}). With numeric prefix argument @var{N}, +move forward across @var{n} such blocks (backward if @var{N} is +negative). + +@item C-c M-C-p +Move back across one balanced begin-end block of Octave code +(@code{octave-backward-block}). With numeric prefix argument @var{N}, +move backward across @var{N} such blocks (forward if @var{N} is +negative). + +@item C-c M-C-d +Move forward down one begin-end block level of Octave code +(@code{octave-down-block}). With numeric prefix argument, do it that +many times; a negative argument means move backward, but still go down +one level. + +@item C-c M-C-u +Move backward out of one begin-end block level of Octave code +(@code{octave-backward-up-block}). With numeric prefix argument, do it +that many times; a negative argument means move forward, but still to a +less deep spot. + +@item C-c M-C-h +Put point at the beginning of this block, mark at the end +(@code{octave-mark-block}). +The block marked is the one that contains point or follows point. + +@item C-c ] +Close the current block on a separate line (@code{octave-close-block}). +An error is signaled if no block to close is found. + +@item C-c f +Insert a function skeleton, prompting for the function's name, arguments +and return values which have to be entered without parens +(@code{octave-insert-defun}). + +@item C-c C-h +Search the function, operator and variable indices of all info files +with documentation for Octave for entries (@code{octave-help}). If used +interactively, the entry is prompted for with completion. If multiple +matches are found, one can cycle through them using the standard +@samp{,} (@code{Info-index-next}) command of the Info reader. + +The variable @code{octave-help-files} is a list of files to search +through and defaults to @code{'("octave")}. If there is also an Octave +Local Guide with corresponding info file, say, @file{octave-LG}, you can +have @code{octave-help} search both files by +@lisp +(setq octave-help-files '("octave" "octave-LG")) +@end lisp +@noindent +in one of your Emacs startup files. + +@end table + +A common problem is that the @key{RET} key does @emph{not} indent the +line to where the new text should go after inserting the newline. This +is because the standard Emacs convention is that @key{RET} (aka +@kbd{C-m}) just adds a newline, whereas @key{LFD} (aka @kbd{C-j}) adds a +newline and indents it. This is particularly inconvenient for users with +keyboards which do not have a special @key{LFD} key at all; in such +cases, it is typically more convenient to use @key{RET} as the @key{LFD} +key (rather than typing @kbd{C-j}). + +You can make @key{RET} do this by adding +@lisp +(define-key octave-mode-map "\C-m" + 'octave-reindent-then-newline-and-indent) +@end lisp +@noindent +to one of your Emacs startup files. Another, more generally applicable +solution is +@lisp +(defun RET-behaves-as-LFD () + (let ((x (key-binding "\C-j"))) + (local-set-key "\C-m" x))) +(add-hook 'octave-mode-hook 'RET-behaves-as-LFD) +@end lisp +@noindent +(this works for all modes by adding to the startup hooks, without having +to know the particular binding of @key{RET} in that mode!). Similar +considerations apply for using @key{M-RET} as @key{M-LFD}. As Barry +A. Warsaw says in the documentation for his +@code{cc-mode}, ``This is a very common question. @code{:-)} If you want +this to be the default behavior, don't lobby me, lobby RMS!'' + +The following variables can be used to customize Octave mode. + +@table @code +@item octave-auto-indent +Non-@code{nil} means auto-indent the current line after a semicolon or +space. Default is @code{nil}. + +@item octave-auto-newline +Non-@code{nil} means auto-insert a newline and indent after semicolons +are typed. The default value is @code{nil}. + +@item octave-blink-matching-block +Non-@code{nil} means show matching begin of block when inserting a space, +newline or @samp{;} after an else or end keyword. Default is @code{t}. +This is an extremely useful feature for automatically verifying that the +keywords match---if they don't, an error message is displayed. + +@item octave-block-offset +Extra indentation applied to statements in block structures. +Default is 2. + +@item octave-continuation-offset +Extra indentation applied to Octave continuation lines. +Default is 4. + +@item octave-continuation-string +String used for Octave continuation lines. +Normally @samp{\}. + +@item octave-mode-startup-message +If @code{t} (default), a startup message is displayed when Octave mode +is called. + +@end table + +If Font Lock mode is enabled, Octave mode will display +@itemize @bullet +@item +strings in @code{font-lock-string-face} +@item +comments in @code{font-lock-comment-face} +@item +the Octave reserved words (such as all block keywords) and the text +functions (such as @samp{cd} or @samp{who}) which are also reserved +using @code{font-lock-keyword-face} +@item +the builtin operators (@samp{&&}, @samp{<>}, @dots{}) using +@code{font-lock-reference-face} +@item +the builtin variables (such as @samp{prefer_column_vectors}, @samp{NaN} +or @samp{LOADPATH}) in @code{font-lock-variable-name-face} +@item +and the function names in function declarations in +@code{font-lock-function-name-face}. +@end itemize + +There is also rudimentary support for Imenu (currently, function names +can be indexed). + +Customization of Octave mode can be performed by modification of the +variable @code{octave-mode-hook}. It the value of this variable is +non-@code{nil}, turning on Octave mode calls its value. + +If you discover a problem with Octave mode, you can conveniently send a +bug report using @kbd{C-c C-b} (@code{octave-submit-bug-report}). This +automatically sets up a mail buffer with version information already +added. You just need to add a description of the problem, including a +reproducible test case and send the message. + +@node Running Octave From Within Emacs, Using the Emacs Info Reader for Octave, Using Octave Mode, Emacs +@section Running Octave From Within Emacs + +The package @file{octave} provides commands for running an inferior +Octave process in a special Emacs buffer. Use +@lisp +M-x run-octave +@end lisp +@noindent +to directly start an inferior Octave process. If Emacs does not know +about this command, add the line +@lisp +(autoload 'run-octave "octave-inf" nil t) +@end lisp +@noindent +to your @file{.emacs} file. + +This will start Octave in a special buffer the name of which is +specified by the variable @code{inferior-octave-buffer} and defaults to +@code{"*Inferior Octave*"}. From within this buffer, you can +interact with the inferior Octave process `as usual', i.e., by entering +Octave commands at the prompt. The buffer is in Inferior Octave mode, +which is derived from the standard Comint mode, a major mode for +interacting with an inferior interpreter. See the documentation for +@code{comint-mode} for more details, and use @kbd{C-h b} to find out +about available special keybindings. + +You can also communicate with an inferior Octave process from within +files with Octave code (i.e., buffers in Octave mode), using the +following commands. + +@table @kbd +@item C-c i l +Send the current line to the inferior Octave process +(@code{octave-send-line}). +With positive prefix argument @var{N}, send that many lines. +If @code{octave-send-line-auto-forward} is non-@code{nil}, go to the +next unsent code line. +@item C-c i b +Send the current block to the inferior Octave process +(@code{octave-send-block}). +@item C-c i f +Send the current function to the inferior Octave process +(@code{octave-send-defun}). +@item C-c i r +Send the region to the inferior Octave process +(@code{octave-send-region}). +@item C-c i s +Make sure that `inferior-octave-buffer' is displayed +(@code{octave-show-process-buffer}). +@item C-c i h +Delete all windows that display the inferior Octave buffer +(@code{octave-hide-process-buffer}). +@item C-c i k +Kill the inferior Octave process and its buffer +(@code{octave-kill-process}). +@end table + +The effect of the commands which send code to the Octave process can be +customized by the following variables. +@table @code +@item octave-send-echo-input +Non-@code{nil} means echo input sent to the inferior Octave process. +Default is @code{t}. + +@item octave-send-show-buffer +Non-@code{nil} means display the buffer running the Octave process after +sending a command (but without selecting it). +Default is @code{t}. +@end table + +If you send code and there is no inferior Octave process yet, it will be +started automatically. + +The startup of the inferior Octave process is highly customizable. +The variable @code{inferior-octave-startup-args} can be used for +specifying command lines arguments to be passed to Octave on startup +as a list of strings. For example, to suppress the startup message and +use `traditional' mode, set this to @code{'("-q" "--traditional")}. +You can also specify a startup file of Octave commands to be loaded on +startup; note that these commands will not produce any visible output +in the process buffer. Which file to use is controlled by the variable +@code{inferior-octave-startup-file}. If this is @code{nil}, the file +@file{~/.emacs-octave} is used if it exists. + +And finally, @code{inferior-octave-mode-hook} is run after starting the +process and putting its buffer into Inferior Octave mode. Hence, if you +like the up and down arrow keys to behave in the interaction buffer as +in the shell, and you want this buffer to use nice colors, add +@lisp +(add-hook 'inferior-octave-mode-hook + (lambda () + (turn-on-font-lock) + (define-key inferior-octave-mode-map [up] + 'comint-previous-input) + (define-key inferior-octave-mode-map [down] + 'comint-next-input))) +@end lisp +@noindent +to your @file{.emacs} file. You could also swap the roles of @kbd{C-a} +(@code{beginning-of-line}) and @code{C-c C-a} (@code{comint-bol}) using +this hook. + +@quotation +@strong{Note:} +If you set your Octave prompts to something different from the defaults, +make sure that @code{inferior-octave-prompt} matches them. +Otherwise, @emph{nothing} will work, because Emacs will have no idea +when Octave is waiting for input, or done sending output. +@end quotation + +@node Using the Emacs Info Reader for Octave, , Running Octave From Within Emacs, Emacs +@section Using the Emacs Info Reader for Octave + +You can also set up the Emacs Info reader for dealing with the results +of Octave's @samp{help -i}. For this, the package @file{gnuserv} needs +to be installed, which unfortunately still does not come with GNU Emacs +(it does with XEmacs). It can be retrieved from any GNU Emacs Lisp Code +Directory archive, e.g.@: +@url{ftp://ftp.cis.ohio-state.edu/pub/gnu/emacs/elisp-archive}, +in the @file{packages} subdirectory. The alpha version of an enhanced +version of gnuserv is available at +@url{ftp://ftp.wellfleet.com/netman/psmith/emacs/gnuserv-2.1alpha.tar.gz}. + +If @file{gnuserv} is installed, add the lines +@lisp +(autoload 'octave-help "octave-hlp" nil t) +(require 'gnuserv) +(gnuserv-start) +@end lisp +@noindent +to your @file{.emacs} file. + +You can use either `plain' Emacs Info or the function @code{octave-help} +as your Octave info reader (for @samp{help -i}). In the former case, +set the Octave variable @code{INFO_PROGRAM} to @code{"info-emacs-info"}. +The latter is perhaps more attractive because it allows to look up keys +in the indices of @emph{several} info files related to Octave (provided +that the Emacs variable @code{octave-help-files} is set correctly). In +this case, set @code{INFO_PROGRAM} to @code{"info-emacs-octave-help"}. + +If you use Octave from within Emacs, these settings are best done in the +@file{~/.emacs-octave} startup file (or the file pointed to by the Emacs +variable @code{inferior-octave-startup-file}). + +@c Local Variables: +@c TeX-command-default: "Texinfo" +@c End: diff --git a/doc/interpreter/errors.texi b/doc/interpreter/errors.texi deleted file mode 100644 --- a/doc/interpreter/errors.texi +++ /dev/null @@ -1,140 +0,0 @@ -@c Copyright (C) 1996, 1997 John W. Eaton -@c This is part of the Octave manual. -@c For copying conditions, see the file gpl.texi. - -@node Error Handling, Input and Output, Functions and Scripts, Top -@chapter Error Handling - -Octave includes several functions for printing error and warning -messages. When you write functions that need to take special action -when they encounter abnormal conditions, you should print the error -messages using the functions described in this chapter. - -@deftypefn {Built-in Function} {} error (@var{template}, @dots{}) -The @code{error} function formats the optional arguments under the -control of the template string @var{template} using the same rules as -the @code{printf} family of functions (@pxref{Formatted Output}). -The resulting message is prefixed by the string @samp{error: } and -printed on the @code{stderr} stream. - -Calling @code{error} also sets Octave's internal error state such that -control will return to the top level without evaluating any more -commands. This is useful for aborting from functions or scripts. - -If the error message does not end with a new line character, Octave will -print a traceback of all the function calls leading to the error. For -example, given the following function definitions: - -@example -@group -function f () g () end -function g () h () end -function h () nargin == 1 || error ("nargin != 1"); end -@end group -@end example - -@noindent -calling the function @code{f} will result in a list of messages that -can help you to quickly locate the exact location of the error: - -@example -@group -f () -error: nargin != 1 -error: evaluating index expression near line 1, column 30 -error: evaluating binary operator `||' near line 1, column 27 -error: called from `h' -error: called from `g' -error: called from `f' -@end group -@end example - -If the error message ends in a new line character, Octave will print the -message but will not display any traceback messages as it returns -control to the top level. For example, modifying the error message -in the previous example to end in a new line causes Octave to only print -a single message: - -@example -@group -function h () nargin == 1 || error ("nargin != 1\n"); end -f () -error: nargin != 1 -@end group -@end example -@end deftypefn - -@defvr {Built-in Variable} error_text -This variable contains the text of error messages that would have -been printed in the body of the most recent @code{unwind_protect} or -@code{try} statement or the @var{try} part of the most recent call to -the @code{eval} function. Outside of the @code{unwind_protect} and -@code{try} statements or the @code{eval} function, or if no error has -occurred within them, the value of @code{error_text} is guaranteed to be -the empty string. - -Note that the message does not include the first @samp{error: } prefix, -so that it may easily be passed to the @code{error} function without -additional processing@footnote{Yes, it's a kluge, but it seems to be a -reasonably useful one.}. - -@xref{The try Statement} and @ref{The unwind_protect Statement}. -@end defvr - -@defvr {Built-in Variable} beep_on_error -If the value of @code{beep_on_error} is nonzero, Octave will try -to ring your terminal's bell before printing an error message. The -default value is 0. -@end defvr - -@deftypefn {Built-in Function} {} warning (@var{msg}) -Print a warning message @var{msg} prefixed by the string @samp{warning: }. -After printing the warning message, Octave will continue to execute -commands. You should use this function should when you want to notify -the user of an unusual condition, but only when it makes sense for your -program to go on. -@end deftypefn - -@deftypefn {Built-in Function} {} usage (@var{msg}) -Print the message @var{msg}, prefixed by the string @samp{usage: }, and -set Octave's internal error state such that control will return to the -top level without evaluating any more commands. This is useful for -aborting from functions. - -After @code{usage} is evaluated, Octave will print a traceback of all -the function calls leading to the usage message. - -You should use this function for reporting problems errors that result -from an improper call to a function, such as calling a function with an -incorrect number of arguments, or with arguments of the wrong type. For -example, most functions distributed with Octave begin with code like -this - -@example -@group -if (nargin != 2) - usage ("foo (a, b)"); -endif -@end group -@end example - -@noindent -to check for the proper number of arguments. -@end deftypefn - -The following pair of functions are of limited usefulness, and may be -removed from future versions of Octave. - -@deftypefn {Function File} {} perror (@var{name}, @var{num}) -Print the error message for function @var{name} corresponding to the -error number @var{num}. This function is intended to be used to print -useful error messages for those functions that return numeric error -codes. -@end deftypefn - -@deftypefn {Function File} {} strerror (@var{name}, @var{num}) -Return the text of an error message for function @var{name} -corresponding to the error number @var{num}. This function is intended -to be used to print useful error messages for those functions that -return numeric error codes. -@end deftypefn diff --git a/doc/interpreter/errors.txi b/doc/interpreter/errors.txi new file mode 100644 --- /dev/null +++ b/doc/interpreter/errors.txi @@ -0,0 +1,140 @@ +@c Copyright (C) 1996, 1997 John W. Eaton +@c This is part of the Octave manual. +@c For copying conditions, see the file gpl.texi. + +@node Error Handling, Input and Output, Functions and Scripts, Top +@chapter Error Handling + +Octave includes several functions for printing error and warning +messages. When you write functions that need to take special action +when they encounter abnormal conditions, you should print the error +messages using the functions described in this chapter. + +@deftypefn {Built-in Function} {} error (@var{template}, @dots{}) +The @code{error} function formats the optional arguments under the +control of the template string @var{template} using the same rules as +the @code{printf} family of functions (@pxref{Formatted Output}). +The resulting message is prefixed by the string @samp{error: } and +printed on the @code{stderr} stream. + +Calling @code{error} also sets Octave's internal error state such that +control will return to the top level without evaluating any more +commands. This is useful for aborting from functions or scripts. + +If the error message does not end with a new line character, Octave will +print a traceback of all the function calls leading to the error. For +example, given the following function definitions: + +@example +@group +function f () g () end +function g () h () end +function h () nargin == 1 || error ("nargin != 1"); end +@end group +@end example + +@noindent +calling the function @code{f} will result in a list of messages that +can help you to quickly locate the exact location of the error: + +@example +@group +f () +error: nargin != 1 +error: evaluating index expression near line 1, column 30 +error: evaluating binary operator `||' near line 1, column 27 +error: called from `h' +error: called from `g' +error: called from `f' +@end group +@end example + +If the error message ends in a new line character, Octave will print the +message but will not display any traceback messages as it returns +control to the top level. For example, modifying the error message +in the previous example to end in a new line causes Octave to only print +a single message: + +@example +@group +function h () nargin == 1 || error ("nargin != 1\n"); end +f () +error: nargin != 1 +@end group +@end example +@end deftypefn + +@defvr {Built-in Variable} error_text +This variable contains the text of error messages that would have +been printed in the body of the most recent @code{unwind_protect} or +@code{try} statement or the @var{try} part of the most recent call to +the @code{eval} function. Outside of the @code{unwind_protect} and +@code{try} statements or the @code{eval} function, or if no error has +occurred within them, the value of @code{error_text} is guaranteed to be +the empty string. + +Note that the message does not include the first @samp{error: } prefix, +so that it may easily be passed to the @code{error} function without +additional processing@footnote{Yes, it's a kluge, but it seems to be a +reasonably useful one.}. + +@xref{The try Statement} and @ref{The unwind_protect Statement}. +@end defvr + +@defvr {Built-in Variable} beep_on_error +If the value of @code{beep_on_error} is nonzero, Octave will try +to ring your terminal's bell before printing an error message. The +default value is 0. +@end defvr + +@deftypefn {Built-in Function} {} warning (@var{msg}) +Print a warning message @var{msg} prefixed by the string @samp{warning: }. +After printing the warning message, Octave will continue to execute +commands. You should use this function should when you want to notify +the user of an unusual condition, but only when it makes sense for your +program to go on. +@end deftypefn + +@deftypefn {Built-in Function} {} usage (@var{msg}) +Print the message @var{msg}, prefixed by the string @samp{usage: }, and +set Octave's internal error state such that control will return to the +top level without evaluating any more commands. This is useful for +aborting from functions. + +After @code{usage} is evaluated, Octave will print a traceback of all +the function calls leading to the usage message. + +You should use this function for reporting problems errors that result +from an improper call to a function, such as calling a function with an +incorrect number of arguments, or with arguments of the wrong type. For +example, most functions distributed with Octave begin with code like +this + +@example +@group +if (nargin != 2) + usage ("foo (a, b)"); +endif +@end group +@end example + +@noindent +to check for the proper number of arguments. +@end deftypefn + +The following pair of functions are of limited usefulness, and may be +removed from future versions of Octave. + +@deftypefn {Function File} {} perror (@var{name}, @var{num}) +Print the error message for function @var{name} corresponding to the +error number @var{num}. This function is intended to be used to print +useful error messages for those functions that return numeric error +codes. +@end deftypefn + +@deftypefn {Function File} {} strerror (@var{name}, @var{num}) +Return the text of an error message for function @var{name} +corresponding to the error number @var{num}. This function is intended +to be used to print useful error messages for those functions that +return numeric error codes. +@end deftypefn diff --git a/doc/interpreter/eval.texi b/doc/interpreter/eval.texi deleted file mode 100644 --- a/doc/interpreter/eval.texi +++ /dev/null @@ -1,116 +0,0 @@ -@c Copyright (C) 1996, 1997 John W. Eaton -@c This is part of the Octave manual. -@c For copying conditions, see the file gpl.texi. - -@node Evaluation, Statements, Expressions, Top -@chapter Evaluation - -Normally, you evaluate expressions simply by typing them at the Octave -prompt, or by asking Octave to interpret commands that you have saved in -a file. - -Sometimes, you may find it necessary to evaluate an expression that has -been computed and stored in a string, or use a string as the name of a -function to call. The @code{eval} and @code{feval} functions allow you -to do just that, and are necessary in order to evaluate commands that -are not known until run time, or to write functions that will need to -call user-supplied functions. - -@deftypefn {Built-in Function} {} eval (@var{command}) -Parse the string @var{command} and evaluate it as if it were an Octave -program, returning the last value computed. The @var{command} is -evaluated in the current context, so any results remain available after -@code{eval} returns. For example, - -@example -@group -eval ("a = 13") - @print{} a = 13 - @result{} 13 -@end group -@end example - -In this case, the value of the evaluated expression is printed and it is -also returned returned from @code{eval}. Just as with any other -expression, you can turn printing off by ending the expression in a -semicolon. For example, - -@example -eval ("a = 13;") - @result{} 13 -@end example - -In this example, the variable @code{a} has been given the value 13, but -the value of the expression is not printed. You can also turn off -automatic printing for all expressions executed by @code{eval} using the -variable @code{default_eval_print_flag}. -@end deftypefn - -@defvr {Built-in Variable} default_eval_print_flag -If the value of this variable is nonzero, Octave prints the results of -commands executed by @code{eval} that do not end with semicolons. If it -is zero, automatic printing is suppressed. The default value is 1. -@end defvr - -@deftypefn {Built-in Function} {} feval (@var{name}, @dots{}) -Evaluate the function named @var{name}. Any arguments after the first -are passed on to the named function. For example, - -@example -feval ("acos", -1) - @result{} 3.1416 -@end example - -@noindent -calls the function @code{acos} with the argument @samp{-1}. - -The function @code{feval} is necessary in order to be able to write -functions that call user-supplied functions, because Octave does not -have a way to declare a pointer to a function (like C) or to declare a -special kind of variable that can be used to hold the name of a function -(like @code{EXTERNAL} in Fortran). Instead, you must refer to functions -by name, and use @code{feval} to call them. -@end deftypefn - -Here is a simple-minded function using @code{feval} that finds the root -of a user-supplied function of one variable using Newton's method. - -@example -@group -@cindex Fordyce, A. P. -@findex newtroot -function result = newtroot (fname, x) - -# usage: newtroot (fname, x) -# -# fname : a string naming a function f(x). -# x : initial guess - - delta = tol = sqrt (eps); - maxit = 200; - fx = feval (fname, x); - for i = 1:maxit - if (abs (fx) < tol) - result = x; - return; - else - fx_new = feval (fname, x + delta); - deriv = (fx_new - fx) / delta; - x = x - fx / deriv; - fx = fx_new; - endif - endfor - - result = x; - -endfunction -@end group -@end example - -Note that this is only meant to be an example of calling user-supplied -functions and should not be taken too seriously. In addition to using a -more robust algorithm, any serious code would check the number and type -of all the arguments, ensure that the supplied function really was a -function, etc. See @xref{Predicates for Numeric Objects}, for example, -for a list of predicates for numeric objects, and @xref{Status of -Variables}, for a description of the @code{exist} function. diff --git a/doc/interpreter/eval.txi b/doc/interpreter/eval.txi new file mode 100644 --- /dev/null +++ b/doc/interpreter/eval.txi @@ -0,0 +1,116 @@ +@c Copyright (C) 1996, 1997 John W. Eaton +@c This is part of the Octave manual. +@c For copying conditions, see the file gpl.texi. + +@node Evaluation, Statements, Expressions, Top +@chapter Evaluation + +Normally, you evaluate expressions simply by typing them at the Octave +prompt, or by asking Octave to interpret commands that you have saved in +a file. + +Sometimes, you may find it necessary to evaluate an expression that has +been computed and stored in a string, or use a string as the name of a +function to call. The @code{eval} and @code{feval} functions allow you +to do just that, and are necessary in order to evaluate commands that +are not known until run time, or to write functions that will need to +call user-supplied functions. + +@deftypefn {Built-in Function} {} eval (@var{command}) +Parse the string @var{command} and evaluate it as if it were an Octave +program, returning the last value computed. The @var{command} is +evaluated in the current context, so any results remain available after +@code{eval} returns. For example, + +@example +@group +eval ("a = 13") + @print{} a = 13 + @result{} 13 +@end group +@end example + +In this case, the value of the evaluated expression is printed and it is +also returned returned from @code{eval}. Just as with any other +expression, you can turn printing off by ending the expression in a +semicolon. For example, + +@example +eval ("a = 13;") + @result{} 13 +@end example + +In this example, the variable @code{a} has been given the value 13, but +the value of the expression is not printed. You can also turn off +automatic printing for all expressions executed by @code{eval} using the +variable @code{default_eval_print_flag}. +@end deftypefn + +@defvr {Built-in Variable} default_eval_print_flag +If the value of this variable is nonzero, Octave prints the results of +commands executed by @code{eval} that do not end with semicolons. If it +is zero, automatic printing is suppressed. The default value is 1. +@end defvr + +@deftypefn {Built-in Function} {} feval (@var{name}, @dots{}) +Evaluate the function named @var{name}. Any arguments after the first +are passed on to the named function. For example, + +@example +feval ("acos", -1) + @result{} 3.1416 +@end example + +@noindent +calls the function @code{acos} with the argument @samp{-1}. + +The function @code{feval} is necessary in order to be able to write +functions that call user-supplied functions, because Octave does not +have a way to declare a pointer to a function (like C) or to declare a +special kind of variable that can be used to hold the name of a function +(like @code{EXTERNAL} in Fortran). Instead, you must refer to functions +by name, and use @code{feval} to call them. +@end deftypefn + +Here is a simple-minded function using @code{feval} that finds the root +of a user-supplied function of one variable using Newton's method. + +@example +@group +@cindex Fordyce, A. P. +@findex newtroot +function result = newtroot (fname, x) + +# usage: newtroot (fname, x) +# +# fname : a string naming a function f(x). +# x : initial guess + + delta = tol = sqrt (eps); + maxit = 200; + fx = feval (fname, x); + for i = 1:maxit + if (abs (fx) < tol) + result = x; + return; + else + fx_new = feval (fname, x + delta); + deriv = (fx_new - fx) / delta; + x = x - fx / deriv; + fx = fx_new; + endif + endfor + + result = x; + +endfunction +@end group +@end example + +Note that this is only meant to be an example of calling user-supplied +functions and should not be taken too seriously. In addition to using a +more robust algorithm, any serious code would check the number and type +of all the arguments, ensure that the supplied function really was a +function, etc. See @xref{Predicates for Numeric Objects}, for example, +for a list of predicates for numeric objects, and @xref{Status of +Variables}, for a description of the @code{exist} function. diff --git a/doc/interpreter/expr.texi b/doc/interpreter/expr.texi deleted file mode 100644 --- a/doc/interpreter/expr.texi +++ /dev/null @@ -1,1131 +0,0 @@ -@c Copyright (C) 1996, 1997 John W. Eaton -@c This is part of the Octave manual. -@c For copying conditions, see the file gpl.texi. - -@node Expressions, Evaluation, Variables, Top -@chapter Expressions -@cindex expressions - -Expressions are the basic building block of statements in Octave. An -expression evaluates to a value, which you can print, test, store in a -variable, pass to a function, or assign a new value to a variable with -an assignment operator. - -An expression can serve as a statement on its own. Most other kinds of -statements contain one or more expressions which specify data to be -operated on. As in other languages, expressions in Octave include -variables, array references, constants, and function calls, as well as -combinations of these with various operators. - -@menu -* Index Expressions:: -* Calling Functions:: -* Arithmetic Ops:: -* Comparison Ops:: -* Boolean Expressions:: -* Assignment Ops:: -* Increment Ops:: -* Operator Precedence:: -@end menu - -@node Index Expressions, Calling Functions, Expressions, Expressions -@section Index Expressions - -@opindex ( -@opindex ) - -An @dfn{index expression} allows you to reference or extract selected -elements of a matrix or vector. - -Indices may be scalars, vectors, ranges, or the special operator -@samp{:}, which may be used to select entire rows or columns. - -Vectors are indexed using a single expression. Matrices require two -indices unless the value of the built-in variable -@code{do_fortran_indexing} is nonzero, in which case matrices may -also be indexed by a single expression. - -@defvr {Built-in Variable} do_fortran_indexing -If the value of @code{do_fortran_indexing} is nonzero, Octave allows -you to select elements of a two-dimensional matrix using a single index -by treating the matrix as a single vector created from the columns of -the matrix. The default value is 0. -@end defvr - -Given the matrix - -@example -a = [1, 2; 3, 4] -@end example - -@noindent -all of the following expressions are equivalent - -@example -@group -a (1, [1, 2]) -a (1, 1:2) -a (1, :) -@end group -@end example - -@noindent -and select the first row of the matrix. - -A special form of indexing may be used to select elements of a matrix or -vector. If the indices are vectors made up of only ones and zeros, the -result is a new matrix whose elements correspond to the elements of the -index vector that are equal to one. For example, - -@example -@group -a = [1, 2; 3, 4]; -a ([1, 0], :) -@end group -@end example - -@noindent -selects the first row of the matrix @code{a}. - -This operation can be useful for selecting elements of a matrix based on -some condition, since the comparison operators return matrices of ones -and zeros. - -This special zero-one form of indexing leads to a conflict with the -standard indexing operation. For example, should the following -statements - -@example -@group -a = [1, 2; 3, 4]; -a ([1, 1], :) -@end group -@end example - -@noindent -return the original matrix, or the matrix formed by selecting the first -row twice? Although this conflict is not likely to arise very often in -practice, you may select the behavior you prefer by setting the built-in -variable @code{prefer_zero_one_indexing}. - -@defvr {Built-in Variable} prefer_zero_one_indexing -If the value of @code{prefer_zero_one_indexing} is nonzero, Octave -will perform zero-one style indexing when there is a conflict with the -normal indexing rules. @xref{Index Expressions}. For example, given a -matrix - -@example -a = [1, 2, 3, 4] -@end example - -@noindent -with @code{prefer_zero_one_indexing} is set to nonzero, the -expression - -@example -a ([1, 1, 1, 1]) -@end example - -@noindent -results in the matrix @code{[ 1, 2, 3, 4 ]}. If the value of -@code{prefer_zero_one_indexing} set to 0, the result would be -the matrix @code{[ 1, 1, 1, 1 ]}. - -In the first case, Octave is selecting each element corresponding to a -@samp{1} in the index vector. In the second, Octave is selecting the -first element multiple times. - -The default value for @code{prefer_zero_one_indexing} is 0. -@end defvr - -Finally, indexing a scalar with a vector of ones can be used to create a -vector the same size as the index vector, with each element equal to -the value of the original scalar. For example, the following statements - -@example -@group -a = 13; -a ([1, 1, 1, 1]) -@end group -@end example - -@noindent -produce a vector whose four elements are all equal to 13. - -Similarly, indexing a scalar with two vectors of ones can be used to -create a matrix. For example the following statements - -@example -@group -a = 13; -a ([1, 1], [1, 1, 1]) -@end group -@end example - -@noindent -create a 2 by 3 matrix with all elements equal to 13. - -This is an obscure notation and should be avoided. It is better to -use the function @code{ones} to generate a matrix of the appropriate -size whose elements are all one, and then to scale it to produce the -desired result. @xref{Special Utility Matrices}. - -@defvr {Built-in Variable} prefer_column_vectors -If @code{prefer_column_vectors} is nonzero, operations like - -@example -for i = 1:10 - a (i) = i; -endfor -@end example - -@noindent -(for @code{a} previously undefined) produce column vectors. Otherwise, row -vectors are preferred. The default value is 1. - -If a variable is already defined to be a vector (a matrix with a single -row or column), the original orientation is respected, regardless of the -value of @code{prefer_column_vectors}. -@end defvr - -@defvr {Built-in Variable} resize_on_range_error -If the value of @code{resize_on_range_error} is nonzero, expressions -like - -@example -for i = 1:10 - a (i) = sqrt (i); -endfor -@end example - -@noindent -(for @code{a} previously undefined) result in the variable @code{a} -being resized to be just large enough to hold the new value. New -elements that have not been given a value are set to zero. If the value -of @code{resize_on_range_error} is 0, an error message is printed and -control is returned to the top level. The default value is 1. -@end defvr - -Note that it is quite inefficient to create a vector using a loop like -the one shown in the example above. In this particular case, it would -have been much more efficient to use the expression - -@example -a = sqrt (1:10); -@end example - -@noindent -thus avoiding the loop entirely. In cases where a loop is still -required, or a number of values must be combined to form a larger -matrix, it is generally much faster to set the size of the matrix first, -and then insert elements using indexing commands. For example, given a -matrix @code{a}, - -@example -@group -[nr, nc] = size (a); -x = zeros (nr, n * nc); -for i = 1:n - x(:,(i-1)*n+1:i*n) = a; -endfor -@end group -@end example - -@noindent -is considerably faster than - -@example -@group -x = a; -for i = 1:n-1 - x = [x, a]; -endfor -@end group -@end example - -@noindent -particularly for large matrices because Octave does not have to -repeatedly resize the result. - -@node Calling Functions, Arithmetic Ops, Index Expressions, Expressions -@section Calling Functions - -A @dfn{function} is a name for a particular calculation. Because it has -a name, you can ask for it by name at any point in the program. For -example, the function @code{sqrt} computes the square root of a number. - -A fixed set of functions are @dfn{built-in}, which means they are -available in every Octave program. The @code{sqrt} function is one of -these. In addition, you can define your own functions. -@xref{Functions and Scripts}, for information about how to do this. - -@cindex arguments in function call -The way to use a function is with a @dfn{function call} expression, -which consists of the function name followed by a list of -@dfn{arguments} in parentheses. The arguments are expressions which give -the raw materials for the calculation that the function will do. When -there is more than one argument, they are separated by commas. If there -are no arguments, you can omit the parentheses, but it is a good idea to -include them anyway, to clearly indicate that a function call was -intended. Here are some examples: - -@example -@group -sqrt (x^2 + y^2) # @r{One argument} -ones (n, m) # @r{Two arguments} -rand () # @r{No arguments} -@end group -@end example - -Each function expects a particular number of arguments. For example, the -@code{sqrt} function must be called with a single argument, the number -to take the square root of: - -@example -sqrt (@var{argument}) -@end example - -Some of the built-in functions take a variable number of arguments, -depending on the particular usage, and their behavior is different -depending on the number of arguments supplied. - -Like every other expression, the function call has a value, which is -computed by the function based on the arguments you give it. In this -example, the value of @code{sqrt (@var{argument})} is the square root of -the argument. A function can also have side effects, such as assigning -the values of certain variables or doing input or output operations. - -Unlike most languages, functions in Octave may return multiple values. -For example, the following statement - -@example -[u, s, v] = svd (a) -@end example - -@noindent -computes the singular value decomposition of the matrix @code{a} and -assigns the three result matrices to @code{u}, @code{s}, and @code{v}. - -The left side of a multiple assignment expression is itself a list of -expressions, and is allowed to be a list of variable names or index -expressions. See also @ref{Index Expressions}, and @ref{Assignment Ops}. - -@menu -* Call by Value:: -* Recursion:: -@end menu - -@node Call by Value, Recursion, Calling Functions, Calling Functions -@subsection Call by Value - -In Octave, unlike Fortran, function arguments are passed by value, which -means that each argument in a function call is evaluated and assigned to -a temporary location in memory before being passed to the function. -There is currently no way to specify that a function parameter should be -passed by reference instead of by value. This means that it is -impossible to directly alter the value of function parameter in the -calling function. It can only change the local copy within the function -body. For example, the function - -@example -@group -function f (x, n) - while (n-- > 0) - disp (x); - endwhile -endfunction -@end group -@end example - -@noindent -displays the value of the first argument @var{n} times. In this -function, the variable @var{n} is used as a temporary variable without -having to worry that its value might also change in the calling -function. Call by value is also useful because it is always possible to -pass constants for any function parameter without first having to -determine that the function will not attempt to modify the parameter. - -The caller may use a variable as the expression for the argument, but -the called function does not know this: it only knows what value the -argument had. For example, given a function called as - -@example -@group -foo = "bar"; -fcn (foo) -@end group -@end example - -@noindent -you should not think of the argument as being ``the variable -@code{foo}.'' Instead, think of the argument as the string value, -@code{"bar"}. - -Even though Octave uses pass-by-value semantics for function arguments, -values are not copied unnecessarily. For example, - -@example -@group -x = rand (1000); -f (x); -@end group -@end example - -@noindent -does not actually force two 1000 by 1000 element matrices to exist -@emph{unless} the function @code{f} modifies the value of its -argument. Then Octave must create a copy to avoid changing the -value outside the scope of the function @code{f}, or attempting (and -probably failing!) to modify the value of a constant or the value of a -temporary result. - -@node Recursion, , Call by Value, Calling Functions -@subsection Recursion -@cindex factorial function - -With some restrictions@footnote{Some of Octave's function are -implemented in terms of functions that cannot be called recursively. -For example, the ODE solver @code{lsode} is ultimately implemented in a -Fortran subroutine that cannot be called recursively, so @code{lsode} -should not be called either directly or indirectly from within the -user-supplied function that @code{lsode} requires. Doing so will result -in undefined behavior.}, recursive function calls are allowed. A -@dfn{recursive function} is one which calls itself, either directly or -indirectly. For example, here is an inefficient@footnote{It would be -much better to use @code{prod (1:n)}, or @code{gamma (n+1)} instead, -after first checking to ensure that the value @code{n} is actually a -positive integer.} way to compute the factorial of a given integer: - -@example -@group -function retval = fact (n) - if (n > 0) - retval = n * fact (n-1); - else - retval = 1; - endif -endfunction -@end group -@end example - -This function is recursive because it calls itself directly. It -eventually terminates because each time it calls itself, it uses an -argument that is one less than was used for the previous call. Once the -argument is no longer greater than zero, it does not call itself, and -the recursion ends. - -The built-in variable @code{max_recursion_depth} specifies a limit to -the recursion depth and prevents Octave from recursing infinitely. - -@defvr max_recursion_depth -Limit the number of times a function may be called recursively. -If the limit is exceeded, an error message is printed and control -returns to the top level. - -The default value is 256. -@end defvr - -@node Arithmetic Ops, Comparison Ops, Calling Functions, Expressions -@section Arithmetic Operators -@cindex arithmetic operators -@cindex operators, arithmetic -@cindex addition -@cindex subtraction -@cindex multiplication -@cindex matrix multiplication -@cindex division -@cindex quotient -@cindex negation -@cindex unary minus -@cindex exponentiation -@cindex transpose -@cindex Hermitian operator -@cindex transpose, complex-conjugate -@cindex complex-conjugate transpose - -The following arithmetic operators are available, and work on scalars -and matrices. - -@table @code -@item @var{x} + @var{y} -@opindex + -Addition. If both operands are matrices, the number of rows and columns -must both agree. If one operand is a scalar, its value is added to -all the elements of the other operand. - -@item @var{x} .+ @var{y} -@opindex .+ -Element by element addition. This operator is equivalent to @code{+}. - -@item @var{x} - @var{y} -@opindex - -Subtraction. If both operands are matrices, the number of rows and -columns of both must agree. - -@item @var{x} .- @var{y} -Element by element subtraction. This operator is equivalent to @code{-}. - -@item @var{x} * @var{y} -@opindex * -Matrix multiplication. The number of columns of @var{x} must agree -with the number of rows of @var{y}. - -@item @var{x} .* @var{y} -@opindex .* -Element by element multiplication. If both operands are matrices, the -number of rows and columns must both agree. - -@item @var{x} / @var{y} -@opindex / -Right division. This is conceptually equivalent to the expression - -@example -(inverse (y') * x')' -@end example - -@noindent -but it is computed without forming the inverse of @var{y'}. - -If the system is not square, or if the coefficient matrix is singular, -a minimum norm solution is computed. - -@item @var{x} ./ @var{y} -@opindex ./ -Element by element right division. - -@item @var{x} \ @var{y} -@opindex \ -Left division. This is conceptually equivalent to the expression - -@example -inverse (x) * y -@end example - -@noindent -but it is computed without forming the inverse of @var{x}. - -If the system is not square, or if the coefficient matrix is singular, -a minimum norm solution is computed. - -@item @var{x} .\ @var{y} -@opindex .\ -Element by element left division. Each element of @var{y} is divided -by each corresponding element of @var{x}. - -@item @var{x} ^ @var{y} -@itemx @var{x} ** @var{y} -@opindex ** -@opindex ^ -Power operator. If @var{x} and @var{y} are both scalars, this operator -returns @var{x} raised to the power @var{y}. If @var{x} is a scalar and -@var{y} is a square matrix, the result is computed using an eigenvalue -expansion. If @var{x} is a square matrix. the result is computed by -repeated multiplication if @var{y} is an integer, and by an eigenvalue -expansion if @var{y} is not an integer. An error results if both -@var{x} and @var{y} are matrices. - -The implementation of this operator needs to be improved. - -@item @var{x} .^ @var{y} -@item @var{x} .** @var{y} -@opindex .** -@opindex .^ -Element by element power operator. If both operands are matrices, the -number of rows and columns must both agree. - -@item -@var{x} -@opindex - -Negation. - -@item +@var{x} -@opindex + -Unary plus. This operator has no effect on the operand. - -@item @var{x}' -@opindex ' -Complex conjugate transpose. For real arguments, this operator is the -same as the transpose operator. For complex arguments, this operator is -equivalent to the expression - -@example -conj (x.') -@end example - -@item @var{x}.' -@opindex .' -Transpose. -@end table - -Note that because Octave's element by element operators begin with a -@samp{.}, there is a possible ambiguity for statements like - -@example -1./m -@end example - -@noindent -because the period could be interpreted either as part of the constant -or as part of the operator. To resolve this conflict, Octave treats the -expression as if you had typed - -@example -(1) ./ m -@end example - -@noindent -and not - -@example -(1.) / m -@end example - -@noindent -Although this is inconsistent with the normal behavior of Octave's -lexer, which usually prefers to break the input into tokens by -preferring the longest possible match at any given point, it is more -useful in this case. - -@defvr {Built-in Variable} warn_divide_by_zero -If the value of @code{warn_divide_by_zero} is nonzero, a warning -is issued when Octave encounters a division by zero. If the value is -0, the warning is omitted. The default value is 1. -@end defvr - -@node Comparison Ops, Boolean Expressions, Arithmetic Ops, Expressions -@section Comparison Operators -@cindex comparison expressions -@cindex expressions, comparison -@cindex relational operators -@cindex operators, relational -@cindex less than operator -@cindex greater than operator -@cindex equality operator -@cindex tests for equality -@cindex equality, tests for - -@dfn{Comparison operators} compare numeric values for relationships -such as equality. They are written using -@emph{relational operators}. - -All of Octave's comparison operators return a value of 1 if the -comparison is true, or 0 if it is false. For matrix values, they all -work on an element-by-element basis. For example, - -@example -@group -[1, 2; 3, 4] == [1, 3; 2, 4] - @result{} 1 0 - 0 1 -@end group -@end example - -If one operand is a scalar and the other is a matrix, the scalar is -compared to each element of the matrix in turn, and the result is the -same size as the matrix. - -@table @code -@item @var{x} < @var{y} -@opindex < -True if @var{x} is less than @var{y}. - -@item @var{x} <= @var{y} -@opindex <= -True if @var{x} is less than or equal to @var{y}. - -@item @var{x} == @var{y} -@opindex == -True if @var{x} is equal to @var{y}. - -@item @var{x} >= @var{y} -@opindex >= -True if @var{x} is greater than or equal to @var{y}. - -@item @var{x} > @var{y} -@opindex > -True if @var{x} is greater than @var{y}. - -@item @var{x} != @var{y} -@itemx @var{x} ~= @var{y} -@itemx @var{x} <> @var{y} -@opindex != -@opindex ~= -@opindex <> -True if @var{x} is not equal to @var{y}. -@end table - -String comparisons may also be performed with the @code{strcmp} -function, not with the comparison operators listed above. -@xref{Strings}. - -@node Boolean Expressions, Assignment Ops, Comparison Ops, Expressions -@section Boolean Expressions -@cindex expressions, boolean -@cindex boolean expressions -@cindex expressions, logical -@cindex logical expressions -@cindex operators, boolean -@cindex boolean operators -@cindex logical operators -@cindex operators, logical -@cindex and operator -@cindex or operator -@cindex not operator - -@menu -* Element-by-element Boolean Operators:: -* Short-circuit Boolean Operators:: -@end menu - -@node Element-by-element Boolean Operators, Short-circuit Boolean Operators, Boolean Expressions, Boolean Expressions -@subsection Element-by-element Boolean Operators -@cindex element-by-element evaluation - -An @dfn{element-by-element boolean expression} is a combination of -comparison expressions using the boolean -operators ``or'' (@samp{|}), ``and'' (@samp{&}), and ``not'' (@samp{!}), -along with parentheses to control nesting. The truth of the boolean -expression is computed by combining the truth values of the -corresponding elements of the component expressions. A value is -considered to be false if it is zero, and true otherwise. - -Element-by-element boolean expressions can be used wherever comparison -expressions can be used. They can be used in @code{if} and @code{while} -statements. However, if a matrix value used as the condition in an -@code{if} or @code{while} statement is only true if @emph{all} of its -elements are nonzero. - -Like comparison operations, each element of an element-by-element -boolean expression also has a numeric value (1 if true, 0 if false) that -comes into play if the result of the boolean expression is stored in a -variable, or used in arithmetic. - -Here are descriptions of the three element-by-element boolean operators. - -@table @code -@item @var{boolean1} & @var{boolean2} -@opindex & -Elements of the result are true if both corresponding elements of -@var{boolean1} and @var{boolean2} are true. - -@item @var{boolean1} | @var{boolean2} -@opindex | -Elements of the result are true if either of the corresponding elements -of @var{boolean1} or @var{boolean2} is true. - -@item ! @var{boolean} -@itemx ~ @var{boolean} -@opindex ~ -@opindex ! -Each element of the result is true if the corresponding element of -@var{boolean} is false. -@end table - -For matrix operands, these operators work on an element-by-element -basis. For example, the expression - -@example -[1, 0; 0, 1] & [1, 0; 2, 3] -@end example - -@noindent -returns a two by two identity matrix. - -For the binary operators, the dimensions of the operands must conform if -both are matrices. If one of the operands is a scalar and the other a -matrix, the operator is applied to the scalar and each element of the -matrix. - -For the binary element-by-element boolean operators, both subexpressions -@var{boolean1} and @var{boolean2} are evaluated before computing the -result. This can make a difference when the expressions have side -effects. For example, in the expression - -@example -a & b++ -@end example - -@noindent -the value of the variable @var{b} is incremented even if the variable -@var{a} is zero. - -This behavior is necessary for the boolean operators to work as -described for matrix-valued operands. - -@node Short-circuit Boolean Operators, , Element-by-element Boolean Operators, Boolean Expressions -@subsection Short-circuit Boolean Operators -@cindex short-circuit evaluation - -Combined with the implicit conversion to scalar values in @code{if} and -@code{while} conditions, Octave's element-by-element boolean operators -are often sufficient for performing most logical operations. However, -it is sometimes desirable to stop evaluating a boolean expression as -soon as the overall truth value can be determined. Octave's -@dfn{short-circuit} boolean operators work this way. - -@table @code -@item @var{boolean1} && @var{boolean2} -@opindex && -The expression @var{boolean1} is evaluated and converted to a scalar -using the equivalent of the operation @code{all (all (@var{boolean1}))}. -If it is false, the result of the overall expression is 0. If it is -true, the expression @var{boolean2} is evaluated and converted to a -scalar using the equivalent of the operation @code{all (all -(@var{boolean1}))}. If it is true, the result of the overall expression -is 1. Otherwise, the result of the overall expression is 0. - -@item @var{boolean1} || @var{boolean2} -@opindex || -The expression @var{boolean1} is evaluated and converted to a scalar -using the equivalent of the operation @code{all (all (@var{boolean1}))}. -If it is true, the result of the overall expression is 1. If it is -false, the expression @var{boolean2} is evaluated and converted to a -scalar using the equivalent of the operation @code{all (all -(@var{boolean1}))}. If it is true, the result of the overall expression -is 1. Otherwise, the result of the overall expression is 0. -@end table - -The fact that both operands may not be evaluated before determining the -overall truth value of the expression can be important. For example, in -the expression - -@example -a && b++ -@end example - -@noindent -the value of the variable @var{b} is only incremented if the variable -@var{a} is nonzero. - -This can be used to write somewhat more concise code. For example, it -is possible write - -@example -@group -function f (a, b, c) - if (nargin > 2 && isstr (c)) - @dots{} -@end group -@end example - -@noindent -instead of having to use two @code{if} statements to avoid attempting to -evaluate an argument that doesn't exist. For example, without the -short-circuit feature, it would be necessary to write - -@example -@group -function f (a, b, c) - if (nargin > 2) - if (isstr (c)) - @dots{} -@end group -@end example - -Writing - -@example -@group -function f (a, b, c) - if (nargin > 2 & isstr (c)) - @dots{} -@end group -@end example - -@noindent -would result in an error if @code{f} were called with one or two -arguments because Octave would be forced to try to evaluate both of the -operands for the operator @samp{&}. - -@node Assignment Ops, Increment Ops, Boolean Expressions, Expressions -@section Assignment Expressions -@cindex assignment expressions -@cindex assignment operators -@cindex operators, assignment -@cindex expressions, assignment - -@opindex = - -An @dfn{assignment} is an expression that stores a new value into a -variable. For example, the following expression assigns the value 1 to -the variable @code{z}: - -@example -z = 1 -@end example - -After this expression is executed, the variable @code{z} has the value 1. -Whatever old value @code{z} had before the assignment is forgotten. -The @samp{=} sign is called an @dfn{assignment operator}. - -Assignments can store string values also. For example, the following -expression would store the value @code{"this food is good"} in the -variable @code{message}: - -@example -@group -thing = "food" -predicate = "good" -message = [ "this " , thing , " is " , predicate ] -@end group -@end example - -@noindent -(This also illustrates concatenation of strings.) - -@cindex side effect -Most operators (addition, concatenation, and so on) have no effect -except to compute a value. If you ignore the value, you might as well -not use the operator. An assignment operator is different. It does -produce a value, but even if you ignore the value, the assignment still -makes itself felt through the alteration of the variable. We call this -a @dfn{side effect}. - -@cindex lvalue -The left-hand operand of an assignment need not be a variable -(@pxref{Variables}). It can also be an element of a matrix -(@pxref{Index Expressions}) or a list of return values -(@pxref{Calling Functions}). These are all called @dfn{lvalues}, which -means they can appear on the left-hand side of an assignment operator. -The right-hand operand may be any expression. It produces the new value -which the assignment stores in the specified variable, matrix element, -or list of return values. - -It is important to note that variables do @emph{not} have permanent types. -The type of a variable is simply the type of whatever value it happens -to hold at the moment. In the following program fragment, the variable -@code{foo} has a numeric value at first, and a string value later on: - -@example -@group -octave:13> foo = 1 -foo = 1 -octave:13> foo = "bar" -foo = bar -@end group -@end example - -@noindent -When the second assignment gives @code{foo} a string value, the fact that -it previously had a numeric value is forgotten. - -Assignment of a scalar to an indexed matrix sets all of the elements -that are referenced by the indices to the scalar value. For example, if -@code{a} is a matrix with at least two columns, - -@example -@group -a(:, 2) = 5 -@end group -@end example - -@noindent -sets all the elements in the second column of @code{a} to 5. - -Assigning an empty matrix @samp{[]} works in most cases to allow you to -delete rows or columns of matrices and vectors. @xref{Empty Matrices}. -For example, given a 4 by 5 matrix @var{A}, the assignment - -@example -A (3, :) = [] -@end example - -@noindent -deletes the third row of @var{A}, and the assignment - -@example -A (:, 1:2:5) = [] -@end example - -@noindent -deletes the first, third, and fifth columns. - -An assignment is an expression, so it has a value. Thus, @code{z = 1} -as an expression has the value 1. One consequence of this is that you -can write multiple assignments together: - -@example -x = y = z = 0 -@end example - -@noindent -stores the value 0 in all three variables. It does this because the -value of @code{z = 0}, which is 0, is stored into @code{y}, and then -the value of @code{y = z = 0}, which is 0, is stored into @code{x}. - -This is also true of assignments to lists of values, so the following is -a valid expression - -@example -[a, b, c] = [u, s, v] = svd (a) -@end example - -@noindent -that is exactly equivalent to - -@example -@group -[u, s, v] = svd (a) -a = u -b = s -c = v -@end group -@end example - -In expressions like this, the number of values in each part of the -expression need not match. For example, the expression - -@example -[a, b, c, d] = [u, s, v] = svd (a) -@end example - -@noindent -is equivalent to the expression above, except that the value of the -variable @samp{d} is left unchanged, and the expression - -@example -[a, b] = [u, s, v] = svd (a) -@end example - -@noindent -is equivalent to - -@example -@group -[u, s, v] = svd (a) -a = u -b = s -@end group -@end example - -You can use an assignment anywhere an expression is called for. For -example, it is valid to write @code{x != (y = 1)} to set @code{y} to 1 -and then test whether @code{x} equals 1. But this style tends to make -programs hard to read. Except in a one-shot program, you should rewrite -it to get rid of such nesting of assignments. This is never very hard. - -@cindex increment operator -@cindex decrement operator -@cindex operators, increment -@cindex operators, decrement - -@node Increment Ops, Operator Precedence, Assignment Ops, Expressions -@section Increment Operators - -@emph{Increment operators} increase or decrease the value of a variable -by 1. The operator to increment a variable is written as @samp{++}. It -may be used to increment a variable either before or after taking its -value. - -For example, to pre-increment the variable @var{x}, you would write -@code{++@var{x}}. This would add one to @var{x} and then return the new -value of @var{x} as the result of the expression. It is exactly the -same as the expression @code{@var{x} = @var{x} + 1}. - -To post-increment a variable @var{x}, you would write @code{@var{x}++}. -This adds one to the variable @var{x}, but returns the value that -@var{x} had prior to incrementing it. For example, if @var{x} is equal -to 2, the result of the expression @code{@var{x}++} is 2, and the new -value of @var{x} is 3. - -For matrix and vector arguments, the increment and decrement operators -work on each element of the operand. - -Here is a list of all the increment and decrement expressions. - -@table @code -@item ++@var{x} -@opindex ++ -This expression increments the variable @var{x}. The value of the -expression is the @emph{new} value of @var{x}. It is equivalent to the -expression @code{@var{x} = @var{x} + 1}. - -@item --@var{x} -@opindex @code{--} -This expression decrements the variable @var{x}. The value of the -expression is the @emph{new} value of @var{x}. It is equivalent to the -expression @code{@var{x} = @var{x} - 1}. - -@item @var{x}++ -@opindex ++ -This expression causes the variable @var{x} to be incremented. The -value of the expression is the @emph{old} value of @var{x}. - -@item @var{x}-- -@opindex @code{--} -This expression causes the variable @var{x} to be decremented. The -value of the expression is the @emph{old} value of @var{x}. -@end table - -It is not currently possible to increment index expressions. For -example, you might expect that the expression @code{@var{v}(4)++} would -increment the fourth element of the vector @var{v}, but instead it -results in a parse error. This problem may be fixed in a future -release of Octave. - -@node Operator Precedence, , Increment Ops, Expressions -@section Operator Precedence -@cindex operator precedence - -@dfn{Operator precedence} determines how operators are grouped, when -different operators appear close by in one expression. For example, -@samp{*} has higher precedence than @samp{+}. Thus, the expression -@code{a + b * c} means to multiply @code{b} and @code{c}, and then add -@code{a} to the product (i.e., @code{a + (b * c)}). - -You can overrule the precedence of the operators by using parentheses. -You can think of the precedence rules as saying where the parentheses -are assumed if you do not write parentheses yourself. In fact, it is -wise to use parentheses whenever you have an unusual combination of -operators, because other people who read the program may not remember -what the precedence is in this case. You might forget as well, and then -you too could make a mistake. Explicit parentheses will help prevent -any such mistake. - -When operators of equal precedence are used together, the leftmost -operator groups first, except for the assignment and exponentiation -operators, which group in the opposite order. Thus, the expression -@code{a - b + c} groups as @code{(a - b) + c}, but the expression -@code{a = b = c} groups as @code{a = (b = c)}. - -The precedence of prefix unary operators is important when another -operator follows the operand. For example, @code{-x^2} means -@code{-(x^2)}, because @samp{-} has lower precedence than @samp{^}. - -Here is a table of the operators in Octave, in order of increasing -precedence. - -@table @code -@item statement separators -@samp{;}, @samp{,}. - -@item assignment -@samp{=}. This operator groups right to left. - -@item logical "or" and "and" -@samp{||}, @samp{&&}. - -@item element-wise "or" and "and" -@samp{|}, @samp{&}. - -@item relational -@samp{<}, @samp{<=}, @samp{==}, @samp{>=}, @samp{>}, @samp{!=}, -@samp{~=}, @samp{<>}. - -@item colon -@samp{:}. - -@item add, subtract -@samp{+}, @samp{-}. - -@item multiply, divide -@samp{*}, @samp{/}, @samp{\}, @samp{.\}, @samp{.*}, @samp{./}. - -@item transpose -@samp{'}, @samp{.'} - -@item unary plus, minus, increment, decrement, and ``not'' -@samp{+}, @samp{-}, @samp{++}, @samp{--}, @samp{!}, @samp{~}. - -@item exponentiation -@samp{^}, @samp{**}, @samp{.^}, @samp{.**}. -@end table diff --git a/doc/interpreter/expr.txi b/doc/interpreter/expr.txi new file mode 100644 --- /dev/null +++ b/doc/interpreter/expr.txi @@ -0,0 +1,1131 @@ +@c Copyright (C) 1996, 1997 John W. Eaton +@c This is part of the Octave manual. +@c For copying conditions, see the file gpl.texi. + +@node Expressions, Evaluation, Variables, Top +@chapter Expressions +@cindex expressions + +Expressions are the basic building block of statements in Octave. An +expression evaluates to a value, which you can print, test, store in a +variable, pass to a function, or assign a new value to a variable with +an assignment operator. + +An expression can serve as a statement on its own. Most other kinds of +statements contain one or more expressions which specify data to be +operated on. As in other languages, expressions in Octave include +variables, array references, constants, and function calls, as well as +combinations of these with various operators. + +@menu +* Index Expressions:: +* Calling Functions:: +* Arithmetic Ops:: +* Comparison Ops:: +* Boolean Expressions:: +* Assignment Ops:: +* Increment Ops:: +* Operator Precedence:: +@end menu + +@node Index Expressions, Calling Functions, Expressions, Expressions +@section Index Expressions + +@opindex ( +@opindex ) + +An @dfn{index expression} allows you to reference or extract selected +elements of a matrix or vector. + +Indices may be scalars, vectors, ranges, or the special operator +@samp{:}, which may be used to select entire rows or columns. + +Vectors are indexed using a single expression. Matrices require two +indices unless the value of the built-in variable +@code{do_fortran_indexing} is nonzero, in which case matrices may +also be indexed by a single expression. + +@defvr {Built-in Variable} do_fortran_indexing +If the value of @code{do_fortran_indexing} is nonzero, Octave allows +you to select elements of a two-dimensional matrix using a single index +by treating the matrix as a single vector created from the columns of +the matrix. The default value is 0. +@end defvr + +Given the matrix + +@example +a = [1, 2; 3, 4] +@end example + +@noindent +all of the following expressions are equivalent + +@example +@group +a (1, [1, 2]) +a (1, 1:2) +a (1, :) +@end group +@end example + +@noindent +and select the first row of the matrix. + +A special form of indexing may be used to select elements of a matrix or +vector. If the indices are vectors made up of only ones and zeros, the +result is a new matrix whose elements correspond to the elements of the +index vector that are equal to one. For example, + +@example +@group +a = [1, 2; 3, 4]; +a ([1, 0], :) +@end group +@end example + +@noindent +selects the first row of the matrix @code{a}. + +This operation can be useful for selecting elements of a matrix based on +some condition, since the comparison operators return matrices of ones +and zeros. + +This special zero-one form of indexing leads to a conflict with the +standard indexing operation. For example, should the following +statements + +@example +@group +a = [1, 2; 3, 4]; +a ([1, 1], :) +@end group +@end example + +@noindent +return the original matrix, or the matrix formed by selecting the first +row twice? Although this conflict is not likely to arise very often in +practice, you may select the behavior you prefer by setting the built-in +variable @code{prefer_zero_one_indexing}. + +@defvr {Built-in Variable} prefer_zero_one_indexing +If the value of @code{prefer_zero_one_indexing} is nonzero, Octave +will perform zero-one style indexing when there is a conflict with the +normal indexing rules. @xref{Index Expressions}. For example, given a +matrix + +@example +a = [1, 2, 3, 4] +@end example + +@noindent +with @code{prefer_zero_one_indexing} is set to nonzero, the +expression + +@example +a ([1, 1, 1, 1]) +@end example + +@noindent +results in the matrix @code{[ 1, 2, 3, 4 ]}. If the value of +@code{prefer_zero_one_indexing} set to 0, the result would be +the matrix @code{[ 1, 1, 1, 1 ]}. + +In the first case, Octave is selecting each element corresponding to a +@samp{1} in the index vector. In the second, Octave is selecting the +first element multiple times. + +The default value for @code{prefer_zero_one_indexing} is 0. +@end defvr + +Finally, indexing a scalar with a vector of ones can be used to create a +vector the same size as the index vector, with each element equal to +the value of the original scalar. For example, the following statements + +@example +@group +a = 13; +a ([1, 1, 1, 1]) +@end group +@end example + +@noindent +produce a vector whose four elements are all equal to 13. + +Similarly, indexing a scalar with two vectors of ones can be used to +create a matrix. For example the following statements + +@example +@group +a = 13; +a ([1, 1], [1, 1, 1]) +@end group +@end example + +@noindent +create a 2 by 3 matrix with all elements equal to 13. + +This is an obscure notation and should be avoided. It is better to +use the function @code{ones} to generate a matrix of the appropriate +size whose elements are all one, and then to scale it to produce the +desired result. @xref{Special Utility Matrices}. + +@defvr {Built-in Variable} prefer_column_vectors +If @code{prefer_column_vectors} is nonzero, operations like + +@example +for i = 1:10 + a (i) = i; +endfor +@end example + +@noindent +(for @code{a} previously undefined) produce column vectors. Otherwise, row +vectors are preferred. The default value is 1. + +If a variable is already defined to be a vector (a matrix with a single +row or column), the original orientation is respected, regardless of the +value of @code{prefer_column_vectors}. +@end defvr + +@defvr {Built-in Variable} resize_on_range_error +If the value of @code{resize_on_range_error} is nonzero, expressions +like + +@example +for i = 1:10 + a (i) = sqrt (i); +endfor +@end example + +@noindent +(for @code{a} previously undefined) result in the variable @code{a} +being resized to be just large enough to hold the new value. New +elements that have not been given a value are set to zero. If the value +of @code{resize_on_range_error} is 0, an error message is printed and +control is returned to the top level. The default value is 1. +@end defvr + +Note that it is quite inefficient to create a vector using a loop like +the one shown in the example above. In this particular case, it would +have been much more efficient to use the expression + +@example +a = sqrt (1:10); +@end example + +@noindent +thus avoiding the loop entirely. In cases where a loop is still +required, or a number of values must be combined to form a larger +matrix, it is generally much faster to set the size of the matrix first, +and then insert elements using indexing commands. For example, given a +matrix @code{a}, + +@example +@group +[nr, nc] = size (a); +x = zeros (nr, n * nc); +for i = 1:n + x(:,(i-1)*n+1:i*n) = a; +endfor +@end group +@end example + +@noindent +is considerably faster than + +@example +@group +x = a; +for i = 1:n-1 + x = [x, a]; +endfor +@end group +@end example + +@noindent +particularly for large matrices because Octave does not have to +repeatedly resize the result. + +@node Calling Functions, Arithmetic Ops, Index Expressions, Expressions +@section Calling Functions + +A @dfn{function} is a name for a particular calculation. Because it has +a name, you can ask for it by name at any point in the program. For +example, the function @code{sqrt} computes the square root of a number. + +A fixed set of functions are @dfn{built-in}, which means they are +available in every Octave program. The @code{sqrt} function is one of +these. In addition, you can define your own functions. +@xref{Functions and Scripts}, for information about how to do this. + +@cindex arguments in function call +The way to use a function is with a @dfn{function call} expression, +which consists of the function name followed by a list of +@dfn{arguments} in parentheses. The arguments are expressions which give +the raw materials for the calculation that the function will do. When +there is more than one argument, they are separated by commas. If there +are no arguments, you can omit the parentheses, but it is a good idea to +include them anyway, to clearly indicate that a function call was +intended. Here are some examples: + +@example +@group +sqrt (x^2 + y^2) # @r{One argument} +ones (n, m) # @r{Two arguments} +rand () # @r{No arguments} +@end group +@end example + +Each function expects a particular number of arguments. For example, the +@code{sqrt} function must be called with a single argument, the number +to take the square root of: + +@example +sqrt (@var{argument}) +@end example + +Some of the built-in functions take a variable number of arguments, +depending on the particular usage, and their behavior is different +depending on the number of arguments supplied. + +Like every other expression, the function call has a value, which is +computed by the function based on the arguments you give it. In this +example, the value of @code{sqrt (@var{argument})} is the square root of +the argument. A function can also have side effects, such as assigning +the values of certain variables or doing input or output operations. + +Unlike most languages, functions in Octave may return multiple values. +For example, the following statement + +@example +[u, s, v] = svd (a) +@end example + +@noindent +computes the singular value decomposition of the matrix @code{a} and +assigns the three result matrices to @code{u}, @code{s}, and @code{v}. + +The left side of a multiple assignment expression is itself a list of +expressions, and is allowed to be a list of variable names or index +expressions. See also @ref{Index Expressions}, and @ref{Assignment Ops}. + +@menu +* Call by Value:: +* Recursion:: +@end menu + +@node Call by Value, Recursion, Calling Functions, Calling Functions +@subsection Call by Value + +In Octave, unlike Fortran, function arguments are passed by value, which +means that each argument in a function call is evaluated and assigned to +a temporary location in memory before being passed to the function. +There is currently no way to specify that a function parameter should be +passed by reference instead of by value. This means that it is +impossible to directly alter the value of function parameter in the +calling function. It can only change the local copy within the function +body. For example, the function + +@example +@group +function f (x, n) + while (n-- > 0) + disp (x); + endwhile +endfunction +@end group +@end example + +@noindent +displays the value of the first argument @var{n} times. In this +function, the variable @var{n} is used as a temporary variable without +having to worry that its value might also change in the calling +function. Call by value is also useful because it is always possible to +pass constants for any function parameter without first having to +determine that the function will not attempt to modify the parameter. + +The caller may use a variable as the expression for the argument, but +the called function does not know this: it only knows what value the +argument had. For example, given a function called as + +@example +@group +foo = "bar"; +fcn (foo) +@end group +@end example + +@noindent +you should not think of the argument as being ``the variable +@code{foo}.'' Instead, think of the argument as the string value, +@code{"bar"}. + +Even though Octave uses pass-by-value semantics for function arguments, +values are not copied unnecessarily. For example, + +@example +@group +x = rand (1000); +f (x); +@end group +@end example + +@noindent +does not actually force two 1000 by 1000 element matrices to exist +@emph{unless} the function @code{f} modifies the value of its +argument. Then Octave must create a copy to avoid changing the +value outside the scope of the function @code{f}, or attempting (and +probably failing!) to modify the value of a constant or the value of a +temporary result. + +@node Recursion, , Call by Value, Calling Functions +@subsection Recursion +@cindex factorial function + +With some restrictions@footnote{Some of Octave's function are +implemented in terms of functions that cannot be called recursively. +For example, the ODE solver @code{lsode} is ultimately implemented in a +Fortran subroutine that cannot be called recursively, so @code{lsode} +should not be called either directly or indirectly from within the +user-supplied function that @code{lsode} requires. Doing so will result +in undefined behavior.}, recursive function calls are allowed. A +@dfn{recursive function} is one which calls itself, either directly or +indirectly. For example, here is an inefficient@footnote{It would be +much better to use @code{prod (1:n)}, or @code{gamma (n+1)} instead, +after first checking to ensure that the value @code{n} is actually a +positive integer.} way to compute the factorial of a given integer: + +@example +@group +function retval = fact (n) + if (n > 0) + retval = n * fact (n-1); + else + retval = 1; + endif +endfunction +@end group +@end example + +This function is recursive because it calls itself directly. It +eventually terminates because each time it calls itself, it uses an +argument that is one less than was used for the previous call. Once the +argument is no longer greater than zero, it does not call itself, and +the recursion ends. + +The built-in variable @code{max_recursion_depth} specifies a limit to +the recursion depth and prevents Octave from recursing infinitely. + +@defvr max_recursion_depth +Limit the number of times a function may be called recursively. +If the limit is exceeded, an error message is printed and control +returns to the top level. + +The default value is 256. +@end defvr + +@node Arithmetic Ops, Comparison Ops, Calling Functions, Expressions +@section Arithmetic Operators +@cindex arithmetic operators +@cindex operators, arithmetic +@cindex addition +@cindex subtraction +@cindex multiplication +@cindex matrix multiplication +@cindex division +@cindex quotient +@cindex negation +@cindex unary minus +@cindex exponentiation +@cindex transpose +@cindex Hermitian operator +@cindex transpose, complex-conjugate +@cindex complex-conjugate transpose + +The following arithmetic operators are available, and work on scalars +and matrices. + +@table @code +@item @var{x} + @var{y} +@opindex + +Addition. If both operands are matrices, the number of rows and columns +must both agree. If one operand is a scalar, its value is added to +all the elements of the other operand. + +@item @var{x} .+ @var{y} +@opindex .+ +Element by element addition. This operator is equivalent to @code{+}. + +@item @var{x} - @var{y} +@opindex - +Subtraction. If both operands are matrices, the number of rows and +columns of both must agree. + +@item @var{x} .- @var{y} +Element by element subtraction. This operator is equivalent to @code{-}. + +@item @var{x} * @var{y} +@opindex * +Matrix multiplication. The number of columns of @var{x} must agree +with the number of rows of @var{y}. + +@item @var{x} .* @var{y} +@opindex .* +Element by element multiplication. If both operands are matrices, the +number of rows and columns must both agree. + +@item @var{x} / @var{y} +@opindex / +Right division. This is conceptually equivalent to the expression + +@example +(inverse (y') * x')' +@end example + +@noindent +but it is computed without forming the inverse of @var{y'}. + +If the system is not square, or if the coefficient matrix is singular, +a minimum norm solution is computed. + +@item @var{x} ./ @var{y} +@opindex ./ +Element by element right division. + +@item @var{x} \ @var{y} +@opindex \ +Left division. This is conceptually equivalent to the expression + +@example +inverse (x) * y +@end example + +@noindent +but it is computed without forming the inverse of @var{x}. + +If the system is not square, or if the coefficient matrix is singular, +a minimum norm solution is computed. + +@item @var{x} .\ @var{y} +@opindex .\ +Element by element left division. Each element of @var{y} is divided +by each corresponding element of @var{x}. + +@item @var{x} ^ @var{y} +@itemx @var{x} ** @var{y} +@opindex ** +@opindex ^ +Power operator. If @var{x} and @var{y} are both scalars, this operator +returns @var{x} raised to the power @var{y}. If @var{x} is a scalar and +@var{y} is a square matrix, the result is computed using an eigenvalue +expansion. If @var{x} is a square matrix. the result is computed by +repeated multiplication if @var{y} is an integer, and by an eigenvalue +expansion if @var{y} is not an integer. An error results if both +@var{x} and @var{y} are matrices. + +The implementation of this operator needs to be improved. + +@item @var{x} .^ @var{y} +@item @var{x} .** @var{y} +@opindex .** +@opindex .^ +Element by element power operator. If both operands are matrices, the +number of rows and columns must both agree. + +@item -@var{x} +@opindex - +Negation. + +@item +@var{x} +@opindex + +Unary plus. This operator has no effect on the operand. + +@item @var{x}' +@opindex ' +Complex conjugate transpose. For real arguments, this operator is the +same as the transpose operator. For complex arguments, this operator is +equivalent to the expression + +@example +conj (x.') +@end example + +@item @var{x}.' +@opindex .' +Transpose. +@end table + +Note that because Octave's element by element operators begin with a +@samp{.}, there is a possible ambiguity for statements like + +@example +1./m +@end example + +@noindent +because the period could be interpreted either as part of the constant +or as part of the operator. To resolve this conflict, Octave treats the +expression as if you had typed + +@example +(1) ./ m +@end example + +@noindent +and not + +@example +(1.) / m +@end example + +@noindent +Although this is inconsistent with the normal behavior of Octave's +lexer, which usually prefers to break the input into tokens by +preferring the longest possible match at any given point, it is more +useful in this case. + +@defvr {Built-in Variable} warn_divide_by_zero +If the value of @code{warn_divide_by_zero} is nonzero, a warning +is issued when Octave encounters a division by zero. If the value is +0, the warning is omitted. The default value is 1. +@end defvr + +@node Comparison Ops, Boolean Expressions, Arithmetic Ops, Expressions +@section Comparison Operators +@cindex comparison expressions +@cindex expressions, comparison +@cindex relational operators +@cindex operators, relational +@cindex less than operator +@cindex greater than operator +@cindex equality operator +@cindex tests for equality +@cindex equality, tests for + +@dfn{Comparison operators} compare numeric values for relationships +such as equality. They are written using +@emph{relational operators}. + +All of Octave's comparison operators return a value of 1 if the +comparison is true, or 0 if it is false. For matrix values, they all +work on an element-by-element basis. For example, + +@example +@group +[1, 2; 3, 4] == [1, 3; 2, 4] + @result{} 1 0 + 0 1 +@end group +@end example + +If one operand is a scalar and the other is a matrix, the scalar is +compared to each element of the matrix in turn, and the result is the +same size as the matrix. + +@table @code +@item @var{x} < @var{y} +@opindex < +True if @var{x} is less than @var{y}. + +@item @var{x} <= @var{y} +@opindex <= +True if @var{x} is less than or equal to @var{y}. + +@item @var{x} == @var{y} +@opindex == +True if @var{x} is equal to @var{y}. + +@item @var{x} >= @var{y} +@opindex >= +True if @var{x} is greater than or equal to @var{y}. + +@item @var{x} > @var{y} +@opindex > +True if @var{x} is greater than @var{y}. + +@item @var{x} != @var{y} +@itemx @var{x} ~= @var{y} +@itemx @var{x} <> @var{y} +@opindex != +@opindex ~= +@opindex <> +True if @var{x} is not equal to @var{y}. +@end table + +String comparisons may also be performed with the @code{strcmp} +function, not with the comparison operators listed above. +@xref{Strings}. + +@node Boolean Expressions, Assignment Ops, Comparison Ops, Expressions +@section Boolean Expressions +@cindex expressions, boolean +@cindex boolean expressions +@cindex expressions, logical +@cindex logical expressions +@cindex operators, boolean +@cindex boolean operators +@cindex logical operators +@cindex operators, logical +@cindex and operator +@cindex or operator +@cindex not operator + +@menu +* Element-by-element Boolean Operators:: +* Short-circuit Boolean Operators:: +@end menu + +@node Element-by-element Boolean Operators, Short-circuit Boolean Operators, Boolean Expressions, Boolean Expressions +@subsection Element-by-element Boolean Operators +@cindex element-by-element evaluation + +An @dfn{element-by-element boolean expression} is a combination of +comparison expressions using the boolean +operators ``or'' (@samp{|}), ``and'' (@samp{&}), and ``not'' (@samp{!}), +along with parentheses to control nesting. The truth of the boolean +expression is computed by combining the truth values of the +corresponding elements of the component expressions. A value is +considered to be false if it is zero, and true otherwise. + +Element-by-element boolean expressions can be used wherever comparison +expressions can be used. They can be used in @code{if} and @code{while} +statements. However, if a matrix value used as the condition in an +@code{if} or @code{while} statement is only true if @emph{all} of its +elements are nonzero. + +Like comparison operations, each element of an element-by-element +boolean expression also has a numeric value (1 if true, 0 if false) that +comes into play if the result of the boolean expression is stored in a +variable, or used in arithmetic. + +Here are descriptions of the three element-by-element boolean operators. + +@table @code +@item @var{boolean1} & @var{boolean2} +@opindex & +Elements of the result are true if both corresponding elements of +@var{boolean1} and @var{boolean2} are true. + +@item @var{boolean1} | @var{boolean2} +@opindex | +Elements of the result are true if either of the corresponding elements +of @var{boolean1} or @var{boolean2} is true. + +@item ! @var{boolean} +@itemx ~ @var{boolean} +@opindex ~ +@opindex ! +Each element of the result is true if the corresponding element of +@var{boolean} is false. +@end table + +For matrix operands, these operators work on an element-by-element +basis. For example, the expression + +@example +[1, 0; 0, 1] & [1, 0; 2, 3] +@end example + +@noindent +returns a two by two identity matrix. + +For the binary operators, the dimensions of the operands must conform if +both are matrices. If one of the operands is a scalar and the other a +matrix, the operator is applied to the scalar and each element of the +matrix. + +For the binary element-by-element boolean operators, both subexpressions +@var{boolean1} and @var{boolean2} are evaluated before computing the +result. This can make a difference when the expressions have side +effects. For example, in the expression + +@example +a & b++ +@end example + +@noindent +the value of the variable @var{b} is incremented even if the variable +@var{a} is zero. + +This behavior is necessary for the boolean operators to work as +described for matrix-valued operands. + +@node Short-circuit Boolean Operators, , Element-by-element Boolean Operators, Boolean Expressions +@subsection Short-circuit Boolean Operators +@cindex short-circuit evaluation + +Combined with the implicit conversion to scalar values in @code{if} and +@code{while} conditions, Octave's element-by-element boolean operators +are often sufficient for performing most logical operations. However, +it is sometimes desirable to stop evaluating a boolean expression as +soon as the overall truth value can be determined. Octave's +@dfn{short-circuit} boolean operators work this way. + +@table @code +@item @var{boolean1} && @var{boolean2} +@opindex && +The expression @var{boolean1} is evaluated and converted to a scalar +using the equivalent of the operation @code{all (all (@var{boolean1}))}. +If it is false, the result of the overall expression is 0. If it is +true, the expression @var{boolean2} is evaluated and converted to a +scalar using the equivalent of the operation @code{all (all +(@var{boolean1}))}. If it is true, the result of the overall expression +is 1. Otherwise, the result of the overall expression is 0. + +@item @var{boolean1} || @var{boolean2} +@opindex || +The expression @var{boolean1} is evaluated and converted to a scalar +using the equivalent of the operation @code{all (all (@var{boolean1}))}. +If it is true, the result of the overall expression is 1. If it is +false, the expression @var{boolean2} is evaluated and converted to a +scalar using the equivalent of the operation @code{all (all +(@var{boolean1}))}. If it is true, the result of the overall expression +is 1. Otherwise, the result of the overall expression is 0. +@end table + +The fact that both operands may not be evaluated before determining the +overall truth value of the expression can be important. For example, in +the expression + +@example +a && b++ +@end example + +@noindent +the value of the variable @var{b} is only incremented if the variable +@var{a} is nonzero. + +This can be used to write somewhat more concise code. For example, it +is possible write + +@example +@group +function f (a, b, c) + if (nargin > 2 && isstr (c)) + @dots{} +@end group +@end example + +@noindent +instead of having to use two @code{if} statements to avoid attempting to +evaluate an argument that doesn't exist. For example, without the +short-circuit feature, it would be necessary to write + +@example +@group +function f (a, b, c) + if (nargin > 2) + if (isstr (c)) + @dots{} +@end group +@end example + +Writing + +@example +@group +function f (a, b, c) + if (nargin > 2 & isstr (c)) + @dots{} +@end group +@end example + +@noindent +would result in an error if @code{f} were called with one or two +arguments because Octave would be forced to try to evaluate both of the +operands for the operator @samp{&}. + +@node Assignment Ops, Increment Ops, Boolean Expressions, Expressions +@section Assignment Expressions +@cindex assignment expressions +@cindex assignment operators +@cindex operators, assignment +@cindex expressions, assignment + +@opindex = + +An @dfn{assignment} is an expression that stores a new value into a +variable. For example, the following expression assigns the value 1 to +the variable @code{z}: + +@example +z = 1 +@end example + +After this expression is executed, the variable @code{z} has the value 1. +Whatever old value @code{z} had before the assignment is forgotten. +The @samp{=} sign is called an @dfn{assignment operator}. + +Assignments can store string values also. For example, the following +expression would store the value @code{"this food is good"} in the +variable @code{message}: + +@example +@group +thing = "food" +predicate = "good" +message = [ "this " , thing , " is " , predicate ] +@end group +@end example + +@noindent +(This also illustrates concatenation of strings.) + +@cindex side effect +Most operators (addition, concatenation, and so on) have no effect +except to compute a value. If you ignore the value, you might as well +not use the operator. An assignment operator is different. It does +produce a value, but even if you ignore the value, the assignment still +makes itself felt through the alteration of the variable. We call this +a @dfn{side effect}. + +@cindex lvalue +The left-hand operand of an assignment need not be a variable +(@pxref{Variables}). It can also be an element of a matrix +(@pxref{Index Expressions}) or a list of return values +(@pxref{Calling Functions}). These are all called @dfn{lvalues}, which +means they can appear on the left-hand side of an assignment operator. +The right-hand operand may be any expression. It produces the new value +which the assignment stores in the specified variable, matrix element, +or list of return values. + +It is important to note that variables do @emph{not} have permanent types. +The type of a variable is simply the type of whatever value it happens +to hold at the moment. In the following program fragment, the variable +@code{foo} has a numeric value at first, and a string value later on: + +@example +@group +octave:13> foo = 1 +foo = 1 +octave:13> foo = "bar" +foo = bar +@end group +@end example + +@noindent +When the second assignment gives @code{foo} a string value, the fact that +it previously had a numeric value is forgotten. + +Assignment of a scalar to an indexed matrix sets all of the elements +that are referenced by the indices to the scalar value. For example, if +@code{a} is a matrix with at least two columns, + +@example +@group +a(:, 2) = 5 +@end group +@end example + +@noindent +sets all the elements in the second column of @code{a} to 5. + +Assigning an empty matrix @samp{[]} works in most cases to allow you to +delete rows or columns of matrices and vectors. @xref{Empty Matrices}. +For example, given a 4 by 5 matrix @var{A}, the assignment + +@example +A (3, :) = [] +@end example + +@noindent +deletes the third row of @var{A}, and the assignment + +@example +A (:, 1:2:5) = [] +@end example + +@noindent +deletes the first, third, and fifth columns. + +An assignment is an expression, so it has a value. Thus, @code{z = 1} +as an expression has the value 1. One consequence of this is that you +can write multiple assignments together: + +@example +x = y = z = 0 +@end example + +@noindent +stores the value 0 in all three variables. It does this because the +value of @code{z = 0}, which is 0, is stored into @code{y}, and then +the value of @code{y = z = 0}, which is 0, is stored into @code{x}. + +This is also true of assignments to lists of values, so the following is +a valid expression + +@example +[a, b, c] = [u, s, v] = svd (a) +@end example + +@noindent +that is exactly equivalent to + +@example +@group +[u, s, v] = svd (a) +a = u +b = s +c = v +@end group +@end example + +In expressions like this, the number of values in each part of the +expression need not match. For example, the expression + +@example +[a, b, c, d] = [u, s, v] = svd (a) +@end example + +@noindent +is equivalent to the expression above, except that the value of the +variable @samp{d} is left unchanged, and the expression + +@example +[a, b] = [u, s, v] = svd (a) +@end example + +@noindent +is equivalent to + +@example +@group +[u, s, v] = svd (a) +a = u +b = s +@end group +@end example + +You can use an assignment anywhere an expression is called for. For +example, it is valid to write @code{x != (y = 1)} to set @code{y} to 1 +and then test whether @code{x} equals 1. But this style tends to make +programs hard to read. Except in a one-shot program, you should rewrite +it to get rid of such nesting of assignments. This is never very hard. + +@cindex increment operator +@cindex decrement operator +@cindex operators, increment +@cindex operators, decrement + +@node Increment Ops, Operator Precedence, Assignment Ops, Expressions +@section Increment Operators + +@emph{Increment operators} increase or decrease the value of a variable +by 1. The operator to increment a variable is written as @samp{++}. It +may be used to increment a variable either before or after taking its +value. + +For example, to pre-increment the variable @var{x}, you would write +@code{++@var{x}}. This would add one to @var{x} and then return the new +value of @var{x} as the result of the expression. It is exactly the +same as the expression @code{@var{x} = @var{x} + 1}. + +To post-increment a variable @var{x}, you would write @code{@var{x}++}. +This adds one to the variable @var{x}, but returns the value that +@var{x} had prior to incrementing it. For example, if @var{x} is equal +to 2, the result of the expression @code{@var{x}++} is 2, and the new +value of @var{x} is 3. + +For matrix and vector arguments, the increment and decrement operators +work on each element of the operand. + +Here is a list of all the increment and decrement expressions. + +@table @code +@item ++@var{x} +@opindex ++ +This expression increments the variable @var{x}. The value of the +expression is the @emph{new} value of @var{x}. It is equivalent to the +expression @code{@var{x} = @var{x} + 1}. + +@item --@var{x} +@opindex @code{--} +This expression decrements the variable @var{x}. The value of the +expression is the @emph{new} value of @var{x}. It is equivalent to the +expression @code{@var{x} = @var{x} - 1}. + +@item @var{x}++ +@opindex ++ +This expression causes the variable @var{x} to be incremented. The +value of the expression is the @emph{old} value of @var{x}. + +@item @var{x}-- +@opindex @code{--} +This expression causes the variable @var{x} to be decremented. The +value of the expression is the @emph{old} value of @var{x}. +@end table + +It is not currently possible to increment index expressions. For +example, you might expect that the expression @code{@var{v}(4)++} would +increment the fourth element of the vector @var{v}, but instead it +results in a parse error. This problem may be fixed in a future +release of Octave. + +@node Operator Precedence, , Increment Ops, Expressions +@section Operator Precedence +@cindex operator precedence + +@dfn{Operator precedence} determines how operators are grouped, when +different operators appear close by in one expression. For example, +@samp{*} has higher precedence than @samp{+}. Thus, the expression +@code{a + b * c} means to multiply @code{b} and @code{c}, and then add +@code{a} to the product (i.e., @code{a + (b * c)}). + +You can overrule the precedence of the operators by using parentheses. +You can think of the precedence rules as saying where the parentheses +are assumed if you do not write parentheses yourself. In fact, it is +wise to use parentheses whenever you have an unusual combination of +operators, because other people who read the program may not remember +what the precedence is in this case. You might forget as well, and then +you too could make a mistake. Explicit parentheses will help prevent +any such mistake. + +When operators of equal precedence are used together, the leftmost +operator groups first, except for the assignment and exponentiation +operators, which group in the opposite order. Thus, the expression +@code{a - b + c} groups as @code{(a - b) + c}, but the expression +@code{a = b = c} groups as @code{a = (b = c)}. + +The precedence of prefix unary operators is important when another +operator follows the operand. For example, @code{-x^2} means +@code{-(x^2)}, because @samp{-} has lower precedence than @samp{^}. + +Here is a table of the operators in Octave, in order of increasing +precedence. + +@table @code +@item statement separators +@samp{;}, @samp{,}. + +@item assignment +@samp{=}. This operator groups right to left. + +@item logical "or" and "and" +@samp{||}, @samp{&&}. + +@item element-wise "or" and "and" +@samp{|}, @samp{&}. + +@item relational +@samp{<}, @samp{<=}, @samp{==}, @samp{>=}, @samp{>}, @samp{!=}, +@samp{~=}, @samp{<>}. + +@item colon +@samp{:}. + +@item add, subtract +@samp{+}, @samp{-}. + +@item multiply, divide +@samp{*}, @samp{/}, @samp{\}, @samp{.\}, @samp{.*}, @samp{./}. + +@item transpose +@samp{'}, @samp{.'} + +@item unary plus, minus, increment, decrement, and ``not'' +@samp{+}, @samp{-}, @samp{++}, @samp{--}, @samp{!}, @samp{~}. + +@item exponentiation +@samp{^}, @samp{**}, @samp{.^}, @samp{.**}. +@end table diff --git a/doc/interpreter/fn-idx.texi b/doc/interpreter/fn-idx.texi deleted file mode 100644 --- a/doc/interpreter/fn-idx.texi +++ /dev/null @@ -1,8 +0,0 @@ -@c Copyright (C) 1996, 1997 John W. Eaton -@c This is part of the Octave manual. -@c For copying conditions, see the file gpl.texi. - -@node Function Index, Operator Index, Variable Index, Top -@unnumbered Function Index - -@printindex fn diff --git a/doc/interpreter/fn-idx.txi b/doc/interpreter/fn-idx.txi new file mode 100644 --- /dev/null +++ b/doc/interpreter/fn-idx.txi @@ -0,0 +1,8 @@ +@c Copyright (C) 1996, 1997 John W. Eaton +@c This is part of the Octave manual. +@c For copying conditions, see the file gpl.texi. + +@node Function Index, Operator Index, Variable Index, Top +@unnumbered Function Index + +@printindex fn diff --git a/doc/interpreter/func.texi b/doc/interpreter/func.texi deleted file mode 100644 --- a/doc/interpreter/func.texi +++ /dev/null @@ -1,1081 +0,0 @@ -@c Copyright (C) 1996, 1997 John W. Eaton -@c This is part of the Octave manual. -@c For copying conditions, see the file gpl.texi. - -@node Functions and Scripts, Error Handling, Statements, Top -@chapter Functions and Script Files -@cindex defining functions -@cindex user-defined functions -@cindex functions, user-defined -@cindex script files - -Complicated Octave programs can often be simplified by defining -functions. Functions can be defined directly on the command line during -interactive Octave sessions, or in external files, and can be called just -like built-in functions. - -@menu -* Defining Functions:: -* Multiple Return Values:: -* Variable-length Argument Lists:: -* Variable-length Return Lists:: -* Returning From a Function:: -* Function Files:: -* Script Files:: -* Dynamically Linked Functions:: -* Organization of Functions:: -@end menu - -@node Defining Functions, Multiple Return Values, Functions and Scripts, Functions and Scripts -@section Defining Functions -@cindex @code{function} statement -@cindex @code{endfunction} statement - -In its simplest form, the definition of a function named @var{name} -looks like this: - -@example -@group -function @var{name} - @var{body} -endfunction -@end group -@end example - -@noindent -A valid function name is like a valid variable name: a sequence of -letters, digits and underscores, not starting with a digit. Functions -share the same pool of names as variables. - -The function @var{body} consists of Octave statements. It is the -most important part of the definition, because it says what the function -should actually @emph{do}. - -For example, here is a function that, when executed, will ring the bell -on your terminal (assuming that it is possible to do so): - -@example -@group -function wakeup - printf ("\a"); -endfunction -@end group -@end example - -The @code{printf} statement (@pxref{Input and Output}) simply tells -Octave to print the string @code{"\a"}. The special character @samp{\a} -stands for the alert character (ASCII 7). @xref{Strings}. - -Once this function is defined, you can ask Octave to evaluate it by -typing the name of the function. - -Normally, you will want to pass some information to the functions you -define. The syntax for passing parameters to a function in Octave is - -@example -@group -function @var{name} (@var{arg-list}) - @var{body} -endfunction -@end group -@end example - -@noindent -where @var{arg-list} is a comma-separated list of the function's -arguments. When the function is called, the argument names are used to -hold the argument values given in the call. The list of arguments may -be empty, in which case this form is equivalent to the one shown above. - -To print a message along with ringing the bell, you might modify the -@code{beep} to look like this: - -@example -@group -function wakeup (message) - printf ("\a%s\n", message); -endfunction -@end group -@end example - -Calling this function using a statement like this - -@example -wakeup ("Rise and shine!"); -@end example - -@noindent -will cause Octave to ring your terminal's bell and print the message -@samp{Rise and shine!}, followed by a newline character (the @samp{\n} -in the first argument to the @code{printf} statement). - -In most cases, you will also want to get some information back from the -functions you define. Here is the syntax for writing a function that -returns a single value: - -@example -@group -function @var{ret-var} = @var{name} (@var{arg-list}) - @var{body} -endfunction -@end group -@end example - -@noindent -The symbol @var{ret-var} is the name of the variable that will hold the -value to be returned by the function. This variable must be defined -before the end of the function body in order for the function to return -a value. - -Variables used in the body of a function are local to the -function. Variables named in @var{arg-list} and @var{ret-var} are also -local to the function. @xref{Global Variables}, for information about -how to access global variables inside a function. - -For example, here is a function that computes the average of the -elements of a vector: - -@example -@group -function retval = avg (v) - retval = sum (v) / length (v); -endfunction -@end group -@end example - -If we had written @code{avg} like this instead, - -@example -@group -function retval = avg (v) - if (is_vector (v)) - retval = sum (v) / length (v); - endif -endfunction -@end group -@end example - -@noindent -and then called the function with a matrix instead of a vector as the -argument, Octave would have printed an error message like this: - -@example -@group -error: `retval' undefined near line 1 column 10 -error: evaluating index expression near line 7, column 1 -@end group -@end example - -@noindent -because the body of the @code{if} statement was never executed, and -@code{retval} was never defined. To prevent obscure errors like this, -it is a good idea to always make sure that the return variables will -always have values, and to produce meaningful error messages when -problems are encountered. For example, @code{avg} could have been -written like this: - -@example -@group -function retval = avg (v) - retval = 0; - if (is_vector (v)) - retval = sum (v) / length (v); - else - error ("avg: expecting vector argument"); - endif -endfunction -@end group -@end example - -There is still one additional problem with this function. What if it is -called without an argument? Without additional error checking, Octave -will probably print an error message that won't really help you track -down the source of the error. To allow you to catch errors like this, -Octave provides each function with an automatic variable called -@code{nargin}. Each time a function is called, @code{nargin} is -automatically initialized to the number of arguments that have actually -been passed to the function. For example, we might rewrite the -@code{avg} function like this: - -@example -@group -function retval = avg (v) - retval = 0; - if (nargin != 1) - usage ("avg (vector)"); - endif - if (is_vector (v)) - retval = sum (v) / length (v); - else - error ("avg: expecting vector argument"); - endif -endfunction -@end group -@end example - -Although Octave does not automatically report an error if you call a -function with more arguments than expected, doing so probably indicates -that something is wrong. Octave also does not automatically report an -error if a function is called with too few arguments, but any attempt to -use a variable that has not been given a value will result in an error. -To avoid such problems and to provide useful messages, we check for both -possibilities and issue our own error message. - -@defvr {Automatic Variable} nargin -When a function is called, this local variable is automatically -initialized to the number of arguments passed to the function. At the -top level, @code{nargin} holds the number of command line arguments that -were passed to Octave. -@end defvr - -@defvr {Built-in Variable} silent_functions -If the value of @code{silent_functions} is nonzero, internal output -from a function is suppressed. Otherwise, the results of expressions -within a function body that are not terminated with a semicolon will -have their values printed. The default value is 0. - -For example, if the function - -@example -function f () - 2 + 2 -endfunction -@end example - -@noindent -is executed, Octave will either print @samp{ans = 4} or nothing -depending on the value of @code{silent_functions}. -@end defvr - -@defvr {Built-in Variable} warn_missing_semicolon -If the value of this variable is nonzero, Octave will warn when -statements in function definitions don't end in semicolons. The default -value is 0. -@end defvr - -@node Multiple Return Values, Variable-length Argument Lists, Defining Functions, Functions and Scripts -@section Multiple Return Values - -Unlike many other computer languages, Octave allows you to define -functions that return more than one value. The syntax for defining -functions that return multiple values is - -@example -function [@var{ret-list}] = @var{name} (@var{arg-list}) - @var{body} -endfunction -@end example - -@noindent -where @var{name}, @var{arg-list}, and @var{body} have the same meaning -as before, and @var{ret-list} is a comma-separated list of variable -names that will hold the values returned from the function. The list of -return values must have at least one element. If @var{ret-list} has -only one element, this form of the @code{function} statement is -equivalent to the form described in the previous section. - -Here is an example of a function that returns two values, the maximum -element of a vector and the index of its first occurrence in the vector. - -@example -@group -function [max, idx] = vmax (v) - idx = 1; - max = v (idx); - for i = 2:length (v) - if (v (i) > max) - max = v (i); - idx = i; - endif - endfor -endfunction -@end group -@end example - -In this particular case, the two values could have been returned as -elements of a single array, but that is not always possible or -convenient. The values to be returned may not have compatible -dimensions, and it is often desirable to give the individual return -values distinct names. - -In addition to setting @code{nargin} each time a function is called, -Octave also automatically initializes @code{nargout} to the number of -values that are expected to be returned. This allows you to write -functions that behave differently depending on the number of values that -the user of the function has requested. The implicit assignment to the -built-in variable @code{ans} does not figure in the count of output -arguments, so the value of @code{nargout} may be zero. - -The @code{svd} and @code{lu} functions are examples of built-in -functions that behave differently depending on the value of -@code{nargout}. - -It is possible to write functions that only set some return values. For -example, calling the function - -@example -function [x, y, z] = f () - x = 1; - z = 2; -endfunction -@end example - -@noindent -as - -@example -[a, b, c] = f () -@end example - -@noindent -produces: - -@example -a = 1 - -b = [](0x0) - -c = 2 -@end example - -@noindent -provided that the built-in variable @code{define_all_return_values} is -nonzero and the value of @code{default_return_value} is @samp{[]}. -@xref{Summary of Built-in Variables}. - -@defvr {Automatic Variable} nargout -When a function is called, this local variable is automatically -initialized to the number of arguments expected to be returned. For -example, - -@example -f () -@end example - -@noindent -will result in @code{nargout} being set to 0 inside the function -@code{f} and - -@example -[s, t] = f () -@end example - -@noindent -will result in @code{nargout} being set to 2 inside the function -@code{f}. - -At the top level, @code{nargout} is undefined. -@end defvr - -@defvr {Built-in Variable} default_return_value -The value given to otherwise uninitialized return values if -@code{define_all_return_values} is nonzero. The default value is -@code{[]}. -@end defvr - -@defvr {Built-in Variable} define_all_return_values -If the value of @code{define_all_return_values} is nonzero, Octave -will substitute the value specified by @code{default_return_value} for -any return values that remain undefined when a function returns. The -default value is 0. -@end defvr - -@deftypefn {Function File} {} nargchk (@var{nargin_min}, @var{nargin_max}, @var{n}) -If @var{n} is in the range @var{nargin_min} through @var{nargin_max} -inclusive, return the empty matrix. Otherwise, return a message -indicating whether @var{n} is too large or too small. - -This is useful for checking to see that the number of arguments supplied -to a function is within an acceptable range. -@end deftypefn - -@node Variable-length Argument Lists, Variable-length Return Lists, Multiple Return Values, Functions and Scripts -@section Variable-length Argument Lists -@cindex Variable-length argument lists -@cindex @code{...} - -Octave has a real mechanism for handling functions that take an -unspecified number of arguments, so it is not necessary to place an -upper bound on the number of optional arguments that a function can -accept. - -@c XXX FIXME XXX -- should we add a note about why this feature is not -@c compatible with Matlab 5? - -Here is an example of a function that uses the new syntax to print a -header followed by an unspecified number of values: - -@example -function foo (heading, ...) - disp (heading); - va_start (); - ## Pre-decrement to skip `heading' arg. - while (--nargin) - disp (va_arg ()); - endwhile -endfunction -@end example - -The ellipsis that marks the variable argument list may only appear once -and must be the last element in the list of arguments. - -@deftypefn {Built-in Function} {} va_start () -Position an internal pointer to the first unnamed argument and allows -you to cycle through the arguments more than once. It is not necessary -to call @code{va_start} if you do not plan to cycle through the -arguments more than once. This function may only be called inside -functions that have been declared to accept a variable number of input -arguments. -@end deftypefn - -@deftypefn {Built-in Function} {} va_arg () -Return the value of the next available argument and move the internal -pointer to the next argument. It is an error to call @code{va_arg()} -when there are no more arguments available. -@end deftypefn - -Sometimes it is useful to be able to pass all unnamed arguments to -another function. The keyword @var{all_va_args} makes this very easy to -do. For example, - -@example -@group -function f (...) - while (nargin--) - disp (va_arg ()) - endwhile -endfunction - -function g (...) - f ("begin", all_va_args, "end") -endfunction - -g (1, 2, 3) - - @print{} begin - @print{} 1 - @print{} 2 - @print{} 3 - @print{} end -@end group -@end example - -@defvr {Keyword} all_va_args -This keyword stands for the entire list of optional argument, so it is -possible to use it more than once within the same function without -having to call @code{va_start}. It can only be used within functions -that take a variable number of arguments. It is an error to use it in -other contexts. -@end defvr - -@node Variable-length Return Lists, Returning From a Function, Variable-length Argument Lists, Functions and Scripts -@section Variable-length Return Lists -@cindex Variable-length return lists -@cindex @code{...} - -Octave also has a real mechanism for handling functions that return an -unspecified number of values, so it is no longer necessary to place an -upper bound on the number of outputs that a function can produce. - -Here is an example of a function that uses a variable-length return list -to produce @var{n} values: - -@example -@group -function [...] = f (n, x) - for i = 1:n - vr_val (i * x); - endfor -endfunction - -[dos, quatro] = f (2, 2) - @result{} dos = 2 - @result{} quatro = 4 -@end group -@end example - -As with variable argument lists, the ellipsis that marks the variable -return list may only appear once and must be the last element in the -list of returned values. - -@deftypefn {Built-in Function} {} vr_val (@var{val}) -Each time this function is called, it places the value of its argument -at the end of the list of values to return from the current function. -Once @code{vr_val} has been called, there is no way to go back to the -beginning of the list and rewrite any of the return values. This -function may only be called within functions that have been declared to -return an unspecified number of output arguments (by using the special -ellipsis notation described above). -@end deftypefn - -@node Returning From a Function, Function Files, Variable-length Return Lists, Functions and Scripts -@section Returning From a Function - -The body of a user-defined function can contain a @code{return} statement. -This statement returns control to the rest of the Octave program. It -looks like this: - -@example -return -@end example - -Unlike the @code{return} statement in C, Octave's @code{return} -statement cannot be used to return a value from a function. Instead, -you must assign values to the list of return variables that are part of -the @code{function} statement. The @code{return} statement simply makes -it easier to exit a function from a deeply nested loop or conditional -statement. - -Here is an example of a function that checks to see if any elements of a -vector are nonzero. - -@example -@group -function retval = any_nonzero (v) - retval = 0; - for i = 1:length (v) - if (v (i) != 0) - retval = 1; - return; - endif - endfor - printf ("no nonzero elements found\n"); -endfunction -@end group -@end example - -Note that this function could not have been written using the -@code{break} statement to exit the loop once a nonzero value is found -without adding extra logic to avoid printing the message if the vector -does contain a nonzero element. - -@defvr {Keyword} return -When Octave encounters the keyword @code{return} inside a function or -script, it returns control to be caller immediately. At the top level, -the return statement is ignored. A @code{return} statement is assumed -at the end of every function definition. -@end defvr - -@defvr {Built-in Variable} return_last_computed_value -If the value of @code{return_last_computed_value} is true, and a -function is defined without explicitly specifying a return value, the -function will return the value of the last expression. Otherwise, no -value will be returned. The default value is 0. - -For example, the function - -@example -function f () - 2 + 2; -endfunction -@end example - -@noindent -will either return nothing, if the value of -@code{return_last_computed_value} is 0, or 4, if the value of -@code{return_last_computed_value} is nonzero. -@end defvr - -@node Function Files, Script Files, Returning From a Function, Functions and Scripts -@section Function Files -@cindex function file - -Except for simple one-shot programs, it is not practical to have to -define all the functions you need each time you need them. Instead, you -will normally want to save them in a file so that you can easily edit -them, and save them for use at a later time. - -Octave does not require you to load function definitions from files -before using them. You simply need to put the function definitions in a -place where Octave can find them. - -When Octave encounters an identifier that is undefined, it first looks -for variables or functions that are already compiled and currently -listed in its symbol table. If it fails to find a definition there, it -searches the list of directories specified by the built-in variable -@code{LOADPATH} for files ending in @file{.m} that have the same base -name as the undefined identifier.@footnote{The @samp{.m} suffix was -chosen for compatibility with @sc{Matlab}.} Once Octave finds a file -with a name that matches, the contents of the file are read. If it -defines a @emph{single} function, it is compiled and executed. -@xref{Script Files}, for more information about how you can define more -than one function in a single file. - -When Octave defines a function from a function file, it saves the full -name of the file it read and the time stamp on the file. After -that, it checks the time stamp on the file every time it needs the -function. If the time stamp indicates that the file has changed since -the last time it was read, Octave reads it again. - -Checking the time stamp allows you to edit the definition of a function -while Octave is running, and automatically use the new function -definition without having to restart your Octave session. Checking the -time stamp every time a function is used is rather inefficient, but it -has to be done to ensure that the correct function definition is used. - -To avoid degrading performance unnecessarily by checking the time stamps -on functions that are not likely to change, Octave assumes that function -files in the directory tree -@file{@var{octave-home}/share/octave/@var{version}/m} -will not change, so it doesn't have to check their time stamps every time the -functions defined in those files are used. This is normally a very good -assumption and provides a significant improvement in performance for the -function files that are distributed with Octave. - -If you know that your own function files will not change while you are -running Octave, you can improve performance by setting the variable -@code{ignore_function_time_stamp} to @code{"all"}, so that Octave will -ignore the time stamps for all function files. Setting it to -@code{"system"} gives the default behavior. If you set it to anything -else, Octave will check the time stamps on all function files. - -@c XXX FIXME XXX -- note about time stamps on files in NFS environments? - -@defvr {Built-in Variable} DEFAULT_LOADPATH -A colon separated list of directories in which to search for function -files by default. The value of this variable is also automatically -substituted for leading, trailing, or doubled colons that appear in the -built-in variable @code{LOADPATH}. -@end defvr - -@defvr {Built-in Variable} LOADPATH -A colon separated list of directories in which to search for function -files. @xref{Functions and Scripts}. The value of @code{LOADPATH} -overrides the environment variable @code{OCTAVE_PATH}. @xref{Installation}. - -@code{LOADPATH} is now handled in the same way as @TeX{} handles -@code{TEXINPUTS}. Leading, trailing, or doubled colons that appear in -@code{LOADPATH} are replaced by the value of @code{DEFAULT_LOADPATH}. -The default value of @code{LOADPATH} is @code{":"}, which tells Octave -to search in the directories specified by @code{DEFAULT_LOADPATH}. - -In addition, if any path element ends in @samp{//}, that directory and -all subdirectories it contains are searched recursively for function -files. This can result in a slight delay as Octave caches the lists of -files found in the @code{LOADPATH} the first time Octave searches for a -function. After that, searching is usually much faster because Octave -normally only needs to search its internal cache for files. - -To improve performance of recursive directory searching, it is best for -each directory that is to be searched recursively to contain -@emph{either} additional subdirectories @emph{or} function files, but -not a mixture of both. - -@xref{Organization of Functions} for a description of the function file -directories that are distributed with Octave. -@end defvr - -@defvr {Built-in Variable} ignore_function_time_stamp -This variable can be used to prevent Octave from making the system call -@code{stat} each time it looks up functions defined in function files. -If @code{ignore_function_time_stamp} to @code{"system"}, Octave will not -automatically recompile function files in subdirectories of -@file{@var{octave-home}/lib/@var{version}} if they have changed since -they were last compiled, but will recompile other function files in the -@code{LOADPATH} if they change. If set to @code{"all"}, Octave will not -recompile any function files unless their definitions are removed with -@code{clear}. For any other value of @code{ignore_function_time_stamp}, -Octave will always check to see if functions defined in function files -need to recompiled. The default value of @code{ignore_function_time_stamp} is -@code{"system"}. -@end defvr - -@defvr {Built-in Variable} warn_function_name_clash -If the value of @code{warn_function_name_clash} is nonzero, a warning is -issued when Octave finds that the name of a function defined in a -function file differs from the name of the file. (If the names -disagree, the name declared inside the file is ignored.) If the value -is 0, the warning is omitted. The default value is 1. -@end defvr - -@node Script Files, Dynamically Linked Functions, Function Files, Functions and Scripts -@section Script Files - -A script file is a file containing (almost) any sequence of Octave -commands. It is read and evaluated just as if you had typed each -command at the Octave prompt, and provides a convenient way to perform a -sequence of commands that do not logically belong inside a function. - -Unlike a function file, a script file must @emph{not} begin with the -keyword @code{function}. If it does, Octave will assume that it is a -function file, and that it defines a single function that should be -evaluated as soon as it is defined. - -A script file also differs from a function file in that the variables -named in a script file are not local variables, but are in the same -scope as the other variables that are visible on the command line. - -Even though a script file may not begin with the @code{function} -keyword, it is possible to define more than one function in a single -script file and load (but not execute) all of them at once. To do -this, the first token in the file (ignoring comments and other white -space) must be something other than @code{function}. If you have no -other statements to evaluate, you can use a statement that has no -effect, like this: - -@example -@group -# Prevent Octave from thinking that this -# is a function file: - -1; - -# Define function one: - -function one () - ... -@end group -@end example - -To have Octave read and compile these functions into an internal form, -you need to make sure that the file is in Octave's @code{LOADPATH}, then -simply type the base name of the file that contains the commands. -(Octave uses the same rules to search for script files as it does to -search for function files.) - -If the first token in a file (ignoring comments) is @code{function}, -Octave will compile the function and try to execute it, printing a -message warning about any non-whitespace characters that appear after -the function definition. - -Note that Octave does not try to look up the definition of any identifier -until it needs to evaluate it. This means that Octave will compile the -following statements if they appear in a script file, or are typed at -the command line, - -@example -@group -# not a function file: -1; -function foo () - do_something (); -endfunction -function do_something () - do_something_else (); -endfunction -@end group -@end example - -@noindent -even though the function @code{do_something} is not defined before it is -referenced in the function @code{foo}. This is not an error because -Octave does not need to resolve all symbols that are referenced by a -function until the function is actually evaluated. - -Since Octave doesn't look for definitions until they are needed, the -following code will always print @samp{bar = 3} whether it is typed -directly on the command line, read from a script file, or is part of a -function body, even if there is a function or script file called -@file{bar.m} in Octave's @code{LOADPATH}. - -@example -@group -eval ("bar = 3"); -bar -@end group -@end example - -Code like this appearing within a function body could fool Octave if -definitions were resolved as the function was being compiled. It would -be virtually impossible to make Octave clever enough to evaluate this -code in a consistent fashion. The parser would have to be able to -perform the call to @code{eval} at compile time, and that would be -impossible unless all the references in the string to be evaluated could -also be resolved, and requiring that would be too restrictive (the -string might come from user input, or depend on things that are not -known until the function is evaluated). - -Although Octave normally executes commands from script files that have -the name @file{@var{file}.m}, you can use the function @code{source} to -execute commands from any file. - -@deftypefn {Built-in Function} {} source (@var{file}) -Parse and execute the contents of @var{file}. This is equivalent to -executing commands from a script file, but without requiring the file to -be named @file{@var{file}.m}. -@end deftypefn - -@node Dynamically Linked Functions, Organization of Functions, Script Files, Functions and Scripts -@section Dynamically Linked Functions -@cindex dynamic linking - -On some systems, Octave can dynamically load and execute functions -written in C++. Octave can only directly call functions written in C++, -but you can also load functions written in other languages -by calling them from a simple wrapper function written in C++. - -Here is an example of how to write a C++ function that Octave can load, -with commentary. The source for this function is included in the source -distributions of Octave, in the file @file{examples/oregonator.cc}. It -defines the same set of differential equations that are used in the -example problem of @ref{Ordinary Differential Equations}. By running -that example and this one, we can compare the execution times to see -what sort of increase in speed you can expect by using dynamically -linked functions. - -The function defined in @file{oregonator.cc} contains just 8 statements, -and is not much different than the code defined in the corresponding -M-file (also distributed with Octave in the file -@file{examples/oregonator.m}). - -Here is the complete text of @file{oregonator.cc}: - -just - -@example -@group -#include - -DEFUN_DLD (oregonator, args, , - "The `oregonator'.") -@{ - ColumnVector dx (3); - - ColumnVector x = args(0).vector_value (); - - dx(0) = 77.27 * (x(1) - x(0)*x(1) + x(0) - - 8.375e-06*pow (x(0), 2)); - - dx(1) = (x(2) - x(0)*x(1) - x(1)) / 77.27; - - dx(2) = 0.161*(x(0) - x(2)); - - return octave_value (dx); -@} -@end group -@end example - -The first line of the file, - -@example -#include -@end example - -@noindent -includes declarations for all of Octave's internal functions that you -will need. If you need other functions from the standard C++ or C -libraries, you can include the necessary headers here. - -The next two lines -@example -@group -DEFUN_DLD (oregonator, args, , - "The `oregonator'.") -@end group -@end example - -@noindent -declares the function. The macro @code{DEFUN_DLD} and the macros that -it depends on are defined in the files @file{defun-dld.h}, -@file{defun.h}, and @file{defun-int.h} (these files are included in the -header file @file{octave/oct.h}). - -Note that the third parameter to @code{DEFUN_DLD} (@code{nargout}) is -not used, so it is omitted from the list of arguments to in order to -avoid the warning from gcc about an unused function parameter. - -@noindent -simply declares an object to store the right hand sides of the -differential equation, and - -The statement - -@example -ColumnVector x = args(0).vector_value (); -@end example - -@noindent -extracts a column vector from the input arguments. The variable -@code{args} is passed to functions defined with @code{DEFUN_DLD} as an -@code{octave_value_list} object, which includes methods for getting the -length of the list and extracting individual elements. - -In this example, we don't check for errors, but that is not difficult. -All of the Octave's built-in functions do some form of checking on their -arguments, so you can check the source code for those functions for -examples of various strategies for verifying that the correct number and -types of arguments have been supplied. - -The next statements - -@example -@group -ColumnVector dx (3); - -dx(0) = 77.27 * (x(1) - x(0)*x(1) + x(0) - - 8.375e-06*pow (x(0), 2)); - -dx(1) = (x(2) - x(0)*x(1) - x(1)) / 77.27; - -dx(2) = 0.161*(x(0) - x(2)); -@end group -@end example - -@noindent -define the right hand side of the differential equation. Finally, we -can return @code{dx}: - -@example -return octave_value (dx); -@end example - -@noindent -The actual return type is @code{octave_value_list}, but it is only -necessary to convert the return type to an @code{octave_value} because -there is a default constructor that can automatically create an object -of that type from an @code{octave_value} object, so we can just use that -instead. - -To use this file, your version of Octave must support dynamic linking. -To find out if it does, type the command -@kbd{octave_config_info ("dld")} at the Octave prompt. Support for -dynamic linking is included if this command returns 1. - -To compile the example file, type the command @samp{mkoctfile -oregonator.cc} at the shell prompt. The script @code{mkoctfile} should -have been installed along with Octave. Running it will create a file -called @file{oregonator.oct} that can be loaded by Octave. To test the -@file{oregonator.oct} file, start Octave and type the command - -@example -oregonator ([1, 2, 3], 0) -@end example - -@noindent -at the Octave prompt. Octave should respond by printing - -@example -@group -ans = - - 77.269353 - -0.012942 - -0.322000 -@end group -@end example - -You can now use the @file{oregonator.oct} file just as you would the -@code{oregonator.m} file to solve the set of differential equations. - -On a 133 MHz Pentium running Linux, Octave can solve the problem shown -in @ref{Ordinary Differential Equations} in about 1.4 second using the -dynamically linked function, compared to about 19 seconds using the -M-file. Similar decreases in execution time can be expected for other -functions, particularly those that rely on functions like @code{lsode} -that require user-supplied functions. - -Just as for M-files, Octave will automatically reload dynamically linked -functions when the files that define them are more recent than the last -time that the function was loaded. Two variables are available to -control how Octave behaves when dynamically linked functions are cleared -or reloaded. - -@defvr {Built-in Variable} auto_unload_dot_oct_files -If the value of @code{auto_unload_dot_oct_files} is nonzero, Octave will -automatically unload any @file{.oct} files when there are no longer any -functions in the symbol table that reference them. -@end defvr - -@defvr {Built-in Variable} warn_reload_forces_clear -If several functions have been loaded from the same file, Octave must -clear all the functions before any one of them can be reloaded. If -@code{warn_reload_forces_clear}, Octave will warn you when this happens, -and print a list of the additional functions that it is forced to clear. -@end defvr - -Additional examples for writing dynamically linked functions are -available in the files in the @file{src} directory of the Octave -distribution. Currently, this includes the files - -@example -@group -balance.cc fft2.cc inv.cc qzval.cc -chol.cc filter.cc log.cc schur.cc -colloc.cc find.cc lsode.cc sort.cc -dassl.cc fsolve.cc lu.cc svd.cc -det.cc givens.cc minmax.cc syl.cc -eig.cc hess.cc pinv.cc -expm.cc ifft.cc qr.cc -fft.cc ifft2.cc quad.cc -@end group -@end example - -@noindent -These files use the macro @code{DEFUN_DLD_BUILTIN} instead of -@code{DEFUN_DLD}. The difference between these two macros is just that -@code{DEFUN_DLD_BUILTIN} can define a built-in function that is not -dynamically loaded if the operating system does not support dynamic -linking. To define your own dynamically linked functions you should use -@code{DEFUN_DLD}. - -There is currently no detailed description of all the functions that you -can call in a built-in function. For the time being, you will have to -read the source code for Octave. - -@node Organization of Functions, , Dynamically Linked Functions, Functions and Scripts -@section Organization of Functions Distributed with Octave - -Many of Octave's standard functions are distributed as function files. -They are loosely organized by topic, in subdirectories of -@file{@var{octave-home}/lib/octave/@var{version}/m}, to make it easier -to find them. - -The following is a list of all the function file subdirectories, and the -types of functions you will find there. - -@table @file -@item audio -Functions for playing and recording sounds. - -@item control -Functions for design and simulation of automatic control systems. - -@item elfun -Elementary functions. - -@item general -Miscellaneous matrix manipulations, like @code{flipud}, @code{rot90}, -and @code{triu}, as well as other basic functions, like -@code{is_matrix}, @code{nargchk}, etc. - -@item image -Image processing tools. These functions require the X Window System. - -@item io -Input-ouput functions. - -@item linear-algebra -Functions for linear algebra. - -@item miscellaneous -Functions that don't really belong anywhere else. - -@item plot -A set of functions that implement the @sc{Matlab}-like plotting functions. - -@item polynomial -Functions for manipulating polynomials. - -@item set -Functions for creating and manipulating sets of unique values. - -@item signal -Functions for signal processing applications. - -@item specfun -Special functions. - -@item special-matrix -Functions that create special matrix forms. - -@item startup -Octave's system-wide startup file. - -@item statistics -Statistical functions. - -@item strings -Miscellaneous string-handling functions. - -@item time -Functions related to time keeping. -@end table diff --git a/doc/interpreter/func.txi b/doc/interpreter/func.txi new file mode 100644 --- /dev/null +++ b/doc/interpreter/func.txi @@ -0,0 +1,1081 @@ +@c Copyright (C) 1996, 1997 John W. Eaton +@c This is part of the Octave manual. +@c For copying conditions, see the file gpl.texi. + +@node Functions and Scripts, Error Handling, Statements, Top +@chapter Functions and Script Files +@cindex defining functions +@cindex user-defined functions +@cindex functions, user-defined +@cindex script files + +Complicated Octave programs can often be simplified by defining +functions. Functions can be defined directly on the command line during +interactive Octave sessions, or in external files, and can be called just +like built-in functions. + +@menu +* Defining Functions:: +* Multiple Return Values:: +* Variable-length Argument Lists:: +* Variable-length Return Lists:: +* Returning From a Function:: +* Function Files:: +* Script Files:: +* Dynamically Linked Functions:: +* Organization of Functions:: +@end menu + +@node Defining Functions, Multiple Return Values, Functions and Scripts, Functions and Scripts +@section Defining Functions +@cindex @code{function} statement +@cindex @code{endfunction} statement + +In its simplest form, the definition of a function named @var{name} +looks like this: + +@example +@group +function @var{name} + @var{body} +endfunction +@end group +@end example + +@noindent +A valid function name is like a valid variable name: a sequence of +letters, digits and underscores, not starting with a digit. Functions +share the same pool of names as variables. + +The function @var{body} consists of Octave statements. It is the +most important part of the definition, because it says what the function +should actually @emph{do}. + +For example, here is a function that, when executed, will ring the bell +on your terminal (assuming that it is possible to do so): + +@example +@group +function wakeup + printf ("\a"); +endfunction +@end group +@end example + +The @code{printf} statement (@pxref{Input and Output}) simply tells +Octave to print the string @code{"\a"}. The special character @samp{\a} +stands for the alert character (ASCII 7). @xref{Strings}. + +Once this function is defined, you can ask Octave to evaluate it by +typing the name of the function. + +Normally, you will want to pass some information to the functions you +define. The syntax for passing parameters to a function in Octave is + +@example +@group +function @var{name} (@var{arg-list}) + @var{body} +endfunction +@end group +@end example + +@noindent +where @var{arg-list} is a comma-separated list of the function's +arguments. When the function is called, the argument names are used to +hold the argument values given in the call. The list of arguments may +be empty, in which case this form is equivalent to the one shown above. + +To print a message along with ringing the bell, you might modify the +@code{beep} to look like this: + +@example +@group +function wakeup (message) + printf ("\a%s\n", message); +endfunction +@end group +@end example + +Calling this function using a statement like this + +@example +wakeup ("Rise and shine!"); +@end example + +@noindent +will cause Octave to ring your terminal's bell and print the message +@samp{Rise and shine!}, followed by a newline character (the @samp{\n} +in the first argument to the @code{printf} statement). + +In most cases, you will also want to get some information back from the +functions you define. Here is the syntax for writing a function that +returns a single value: + +@example +@group +function @var{ret-var} = @var{name} (@var{arg-list}) + @var{body} +endfunction +@end group +@end example + +@noindent +The symbol @var{ret-var} is the name of the variable that will hold the +value to be returned by the function. This variable must be defined +before the end of the function body in order for the function to return +a value. + +Variables used in the body of a function are local to the +function. Variables named in @var{arg-list} and @var{ret-var} are also +local to the function. @xref{Global Variables}, for information about +how to access global variables inside a function. + +For example, here is a function that computes the average of the +elements of a vector: + +@example +@group +function retval = avg (v) + retval = sum (v) / length (v); +endfunction +@end group +@end example + +If we had written @code{avg} like this instead, + +@example +@group +function retval = avg (v) + if (is_vector (v)) + retval = sum (v) / length (v); + endif +endfunction +@end group +@end example + +@noindent +and then called the function with a matrix instead of a vector as the +argument, Octave would have printed an error message like this: + +@example +@group +error: `retval' undefined near line 1 column 10 +error: evaluating index expression near line 7, column 1 +@end group +@end example + +@noindent +because the body of the @code{if} statement was never executed, and +@code{retval} was never defined. To prevent obscure errors like this, +it is a good idea to always make sure that the return variables will +always have values, and to produce meaningful error messages when +problems are encountered. For example, @code{avg} could have been +written like this: + +@example +@group +function retval = avg (v) + retval = 0; + if (is_vector (v)) + retval = sum (v) / length (v); + else + error ("avg: expecting vector argument"); + endif +endfunction +@end group +@end example + +There is still one additional problem with this function. What if it is +called without an argument? Without additional error checking, Octave +will probably print an error message that won't really help you track +down the source of the error. To allow you to catch errors like this, +Octave provides each function with an automatic variable called +@code{nargin}. Each time a function is called, @code{nargin} is +automatically initialized to the number of arguments that have actually +been passed to the function. For example, we might rewrite the +@code{avg} function like this: + +@example +@group +function retval = avg (v) + retval = 0; + if (nargin != 1) + usage ("avg (vector)"); + endif + if (is_vector (v)) + retval = sum (v) / length (v); + else + error ("avg: expecting vector argument"); + endif +endfunction +@end group +@end example + +Although Octave does not automatically report an error if you call a +function with more arguments than expected, doing so probably indicates +that something is wrong. Octave also does not automatically report an +error if a function is called with too few arguments, but any attempt to +use a variable that has not been given a value will result in an error. +To avoid such problems and to provide useful messages, we check for both +possibilities and issue our own error message. + +@defvr {Automatic Variable} nargin +When a function is called, this local variable is automatically +initialized to the number of arguments passed to the function. At the +top level, @code{nargin} holds the number of command line arguments that +were passed to Octave. +@end defvr + +@defvr {Built-in Variable} silent_functions +If the value of @code{silent_functions} is nonzero, internal output +from a function is suppressed. Otherwise, the results of expressions +within a function body that are not terminated with a semicolon will +have their values printed. The default value is 0. + +For example, if the function + +@example +function f () + 2 + 2 +endfunction +@end example + +@noindent +is executed, Octave will either print @samp{ans = 4} or nothing +depending on the value of @code{silent_functions}. +@end defvr + +@defvr {Built-in Variable} warn_missing_semicolon +If the value of this variable is nonzero, Octave will warn when +statements in function definitions don't end in semicolons. The default +value is 0. +@end defvr + +@node Multiple Return Values, Variable-length Argument Lists, Defining Functions, Functions and Scripts +@section Multiple Return Values + +Unlike many other computer languages, Octave allows you to define +functions that return more than one value. The syntax for defining +functions that return multiple values is + +@example +function [@var{ret-list}] = @var{name} (@var{arg-list}) + @var{body} +endfunction +@end example + +@noindent +where @var{name}, @var{arg-list}, and @var{body} have the same meaning +as before, and @var{ret-list} is a comma-separated list of variable +names that will hold the values returned from the function. The list of +return values must have at least one element. If @var{ret-list} has +only one element, this form of the @code{function} statement is +equivalent to the form described in the previous section. + +Here is an example of a function that returns two values, the maximum +element of a vector and the index of its first occurrence in the vector. + +@example +@group +function [max, idx] = vmax (v) + idx = 1; + max = v (idx); + for i = 2:length (v) + if (v (i) > max) + max = v (i); + idx = i; + endif + endfor +endfunction +@end group +@end example + +In this particular case, the two values could have been returned as +elements of a single array, but that is not always possible or +convenient. The values to be returned may not have compatible +dimensions, and it is often desirable to give the individual return +values distinct names. + +In addition to setting @code{nargin} each time a function is called, +Octave also automatically initializes @code{nargout} to the number of +values that are expected to be returned. This allows you to write +functions that behave differently depending on the number of values that +the user of the function has requested. The implicit assignment to the +built-in variable @code{ans} does not figure in the count of output +arguments, so the value of @code{nargout} may be zero. + +The @code{svd} and @code{lu} functions are examples of built-in +functions that behave differently depending on the value of +@code{nargout}. + +It is possible to write functions that only set some return values. For +example, calling the function + +@example +function [x, y, z] = f () + x = 1; + z = 2; +endfunction +@end example + +@noindent +as + +@example +[a, b, c] = f () +@end example + +@noindent +produces: + +@example +a = 1 + +b = [](0x0) + +c = 2 +@end example + +@noindent +provided that the built-in variable @code{define_all_return_values} is +nonzero and the value of @code{default_return_value} is @samp{[]}. +@xref{Summary of Built-in Variables}. + +@defvr {Automatic Variable} nargout +When a function is called, this local variable is automatically +initialized to the number of arguments expected to be returned. For +example, + +@example +f () +@end example + +@noindent +will result in @code{nargout} being set to 0 inside the function +@code{f} and + +@example +[s, t] = f () +@end example + +@noindent +will result in @code{nargout} being set to 2 inside the function +@code{f}. + +At the top level, @code{nargout} is undefined. +@end defvr + +@defvr {Built-in Variable} default_return_value +The value given to otherwise uninitialized return values if +@code{define_all_return_values} is nonzero. The default value is +@code{[]}. +@end defvr + +@defvr {Built-in Variable} define_all_return_values +If the value of @code{define_all_return_values} is nonzero, Octave +will substitute the value specified by @code{default_return_value} for +any return values that remain undefined when a function returns. The +default value is 0. +@end defvr + +@deftypefn {Function File} {} nargchk (@var{nargin_min}, @var{nargin_max}, @var{n}) +If @var{n} is in the range @var{nargin_min} through @var{nargin_max} +inclusive, return the empty matrix. Otherwise, return a message +indicating whether @var{n} is too large or too small. + +This is useful for checking to see that the number of arguments supplied +to a function is within an acceptable range. +@end deftypefn + +@node Variable-length Argument Lists, Variable-length Return Lists, Multiple Return Values, Functions and Scripts +@section Variable-length Argument Lists +@cindex Variable-length argument lists +@cindex @code{...} + +Octave has a real mechanism for handling functions that take an +unspecified number of arguments, so it is not necessary to place an +upper bound on the number of optional arguments that a function can +accept. + +@c XXX FIXME XXX -- should we add a note about why this feature is not +@c compatible with Matlab 5? + +Here is an example of a function that uses the new syntax to print a +header followed by an unspecified number of values: + +@example +function foo (heading, ...) + disp (heading); + va_start (); + ## Pre-decrement to skip `heading' arg. + while (--nargin) + disp (va_arg ()); + endwhile +endfunction +@end example + +The ellipsis that marks the variable argument list may only appear once +and must be the last element in the list of arguments. + +@deftypefn {Built-in Function} {} va_start () +Position an internal pointer to the first unnamed argument and allows +you to cycle through the arguments more than once. It is not necessary +to call @code{va_start} if you do not plan to cycle through the +arguments more than once. This function may only be called inside +functions that have been declared to accept a variable number of input +arguments. +@end deftypefn + +@deftypefn {Built-in Function} {} va_arg () +Return the value of the next available argument and move the internal +pointer to the next argument. It is an error to call @code{va_arg()} +when there are no more arguments available. +@end deftypefn + +Sometimes it is useful to be able to pass all unnamed arguments to +another function. The keyword @var{all_va_args} makes this very easy to +do. For example, + +@example +@group +function f (...) + while (nargin--) + disp (va_arg ()) + endwhile +endfunction + +function g (...) + f ("begin", all_va_args, "end") +endfunction + +g (1, 2, 3) + + @print{} begin + @print{} 1 + @print{} 2 + @print{} 3 + @print{} end +@end group +@end example + +@defvr {Keyword} all_va_args +This keyword stands for the entire list of optional argument, so it is +possible to use it more than once within the same function without +having to call @code{va_start}. It can only be used within functions +that take a variable number of arguments. It is an error to use it in +other contexts. +@end defvr + +@node Variable-length Return Lists, Returning From a Function, Variable-length Argument Lists, Functions and Scripts +@section Variable-length Return Lists +@cindex Variable-length return lists +@cindex @code{...} + +Octave also has a real mechanism for handling functions that return an +unspecified number of values, so it is no longer necessary to place an +upper bound on the number of outputs that a function can produce. + +Here is an example of a function that uses a variable-length return list +to produce @var{n} values: + +@example +@group +function [...] = f (n, x) + for i = 1:n + vr_val (i * x); + endfor +endfunction + +[dos, quatro] = f (2, 2) + @result{} dos = 2 + @result{} quatro = 4 +@end group +@end example + +As with variable argument lists, the ellipsis that marks the variable +return list may only appear once and must be the last element in the +list of returned values. + +@deftypefn {Built-in Function} {} vr_val (@var{val}) +Each time this function is called, it places the value of its argument +at the end of the list of values to return from the current function. +Once @code{vr_val} has been called, there is no way to go back to the +beginning of the list and rewrite any of the return values. This +function may only be called within functions that have been declared to +return an unspecified number of output arguments (by using the special +ellipsis notation described above). +@end deftypefn + +@node Returning From a Function, Function Files, Variable-length Return Lists, Functions and Scripts +@section Returning From a Function + +The body of a user-defined function can contain a @code{return} statement. +This statement returns control to the rest of the Octave program. It +looks like this: + +@example +return +@end example + +Unlike the @code{return} statement in C, Octave's @code{return} +statement cannot be used to return a value from a function. Instead, +you must assign values to the list of return variables that are part of +the @code{function} statement. The @code{return} statement simply makes +it easier to exit a function from a deeply nested loop or conditional +statement. + +Here is an example of a function that checks to see if any elements of a +vector are nonzero. + +@example +@group +function retval = any_nonzero (v) + retval = 0; + for i = 1:length (v) + if (v (i) != 0) + retval = 1; + return; + endif + endfor + printf ("no nonzero elements found\n"); +endfunction +@end group +@end example + +Note that this function could not have been written using the +@code{break} statement to exit the loop once a nonzero value is found +without adding extra logic to avoid printing the message if the vector +does contain a nonzero element. + +@defvr {Keyword} return +When Octave encounters the keyword @code{return} inside a function or +script, it returns control to be caller immediately. At the top level, +the return statement is ignored. A @code{return} statement is assumed +at the end of every function definition. +@end defvr + +@defvr {Built-in Variable} return_last_computed_value +If the value of @code{return_last_computed_value} is true, and a +function is defined without explicitly specifying a return value, the +function will return the value of the last expression. Otherwise, no +value will be returned. The default value is 0. + +For example, the function + +@example +function f () + 2 + 2; +endfunction +@end example + +@noindent +will either return nothing, if the value of +@code{return_last_computed_value} is 0, or 4, if the value of +@code{return_last_computed_value} is nonzero. +@end defvr + +@node Function Files, Script Files, Returning From a Function, Functions and Scripts +@section Function Files +@cindex function file + +Except for simple one-shot programs, it is not practical to have to +define all the functions you need each time you need them. Instead, you +will normally want to save them in a file so that you can easily edit +them, and save them for use at a later time. + +Octave does not require you to load function definitions from files +before using them. You simply need to put the function definitions in a +place where Octave can find them. + +When Octave encounters an identifier that is undefined, it first looks +for variables or functions that are already compiled and currently +listed in its symbol table. If it fails to find a definition there, it +searches the list of directories specified by the built-in variable +@code{LOADPATH} for files ending in @file{.m} that have the same base +name as the undefined identifier.@footnote{The @samp{.m} suffix was +chosen for compatibility with @sc{Matlab}.} Once Octave finds a file +with a name that matches, the contents of the file are read. If it +defines a @emph{single} function, it is compiled and executed. +@xref{Script Files}, for more information about how you can define more +than one function in a single file. + +When Octave defines a function from a function file, it saves the full +name of the file it read and the time stamp on the file. After +that, it checks the time stamp on the file every time it needs the +function. If the time stamp indicates that the file has changed since +the last time it was read, Octave reads it again. + +Checking the time stamp allows you to edit the definition of a function +while Octave is running, and automatically use the new function +definition without having to restart your Octave session. Checking the +time stamp every time a function is used is rather inefficient, but it +has to be done to ensure that the correct function definition is used. + +To avoid degrading performance unnecessarily by checking the time stamps +on functions that are not likely to change, Octave assumes that function +files in the directory tree +@file{@var{octave-home}/share/octave/@var{version}/m} +will not change, so it doesn't have to check their time stamps every time the +functions defined in those files are used. This is normally a very good +assumption and provides a significant improvement in performance for the +function files that are distributed with Octave. + +If you know that your own function files will not change while you are +running Octave, you can improve performance by setting the variable +@code{ignore_function_time_stamp} to @code{"all"}, so that Octave will +ignore the time stamps for all function files. Setting it to +@code{"system"} gives the default behavior. If you set it to anything +else, Octave will check the time stamps on all function files. + +@c XXX FIXME XXX -- note about time stamps on files in NFS environments? + +@defvr {Built-in Variable} DEFAULT_LOADPATH +A colon separated list of directories in which to search for function +files by default. The value of this variable is also automatically +substituted for leading, trailing, or doubled colons that appear in the +built-in variable @code{LOADPATH}. +@end defvr + +@defvr {Built-in Variable} LOADPATH +A colon separated list of directories in which to search for function +files. @xref{Functions and Scripts}. The value of @code{LOADPATH} +overrides the environment variable @code{OCTAVE_PATH}. @xref{Installation}. + +@code{LOADPATH} is now handled in the same way as @TeX{} handles +@code{TEXINPUTS}. Leading, trailing, or doubled colons that appear in +@code{LOADPATH} are replaced by the value of @code{DEFAULT_LOADPATH}. +The default value of @code{LOADPATH} is @code{":"}, which tells Octave +to search in the directories specified by @code{DEFAULT_LOADPATH}. + +In addition, if any path element ends in @samp{//}, that directory and +all subdirectories it contains are searched recursively for function +files. This can result in a slight delay as Octave caches the lists of +files found in the @code{LOADPATH} the first time Octave searches for a +function. After that, searching is usually much faster because Octave +normally only needs to search its internal cache for files. + +To improve performance of recursive directory searching, it is best for +each directory that is to be searched recursively to contain +@emph{either} additional subdirectories @emph{or} function files, but +not a mixture of both. + +@xref{Organization of Functions} for a description of the function file +directories that are distributed with Octave. +@end defvr + +@defvr {Built-in Variable} ignore_function_time_stamp +This variable can be used to prevent Octave from making the system call +@code{stat} each time it looks up functions defined in function files. +If @code{ignore_function_time_stamp} to @code{"system"}, Octave will not +automatically recompile function files in subdirectories of +@file{@var{octave-home}/lib/@var{version}} if they have changed since +they were last compiled, but will recompile other function files in the +@code{LOADPATH} if they change. If set to @code{"all"}, Octave will not +recompile any function files unless their definitions are removed with +@code{clear}. For any other value of @code{ignore_function_time_stamp}, +Octave will always check to see if functions defined in function files +need to recompiled. The default value of @code{ignore_function_time_stamp} is +@code{"system"}. +@end defvr + +@defvr {Built-in Variable} warn_function_name_clash +If the value of @code{warn_function_name_clash} is nonzero, a warning is +issued when Octave finds that the name of a function defined in a +function file differs from the name of the file. (If the names +disagree, the name declared inside the file is ignored.) If the value +is 0, the warning is omitted. The default value is 1. +@end defvr + +@node Script Files, Dynamically Linked Functions, Function Files, Functions and Scripts +@section Script Files + +A script file is a file containing (almost) any sequence of Octave +commands. It is read and evaluated just as if you had typed each +command at the Octave prompt, and provides a convenient way to perform a +sequence of commands that do not logically belong inside a function. + +Unlike a function file, a script file must @emph{not} begin with the +keyword @code{function}. If it does, Octave will assume that it is a +function file, and that it defines a single function that should be +evaluated as soon as it is defined. + +A script file also differs from a function file in that the variables +named in a script file are not local variables, but are in the same +scope as the other variables that are visible on the command line. + +Even though a script file may not begin with the @code{function} +keyword, it is possible to define more than one function in a single +script file and load (but not execute) all of them at once. To do +this, the first token in the file (ignoring comments and other white +space) must be something other than @code{function}. If you have no +other statements to evaluate, you can use a statement that has no +effect, like this: + +@example +@group +# Prevent Octave from thinking that this +# is a function file: + +1; + +# Define function one: + +function one () + ... +@end group +@end example + +To have Octave read and compile these functions into an internal form, +you need to make sure that the file is in Octave's @code{LOADPATH}, then +simply type the base name of the file that contains the commands. +(Octave uses the same rules to search for script files as it does to +search for function files.) + +If the first token in a file (ignoring comments) is @code{function}, +Octave will compile the function and try to execute it, printing a +message warning about any non-whitespace characters that appear after +the function definition. + +Note that Octave does not try to look up the definition of any identifier +until it needs to evaluate it. This means that Octave will compile the +following statements if they appear in a script file, or are typed at +the command line, + +@example +@group +# not a function file: +1; +function foo () + do_something (); +endfunction +function do_something () + do_something_else (); +endfunction +@end group +@end example + +@noindent +even though the function @code{do_something} is not defined before it is +referenced in the function @code{foo}. This is not an error because +Octave does not need to resolve all symbols that are referenced by a +function until the function is actually evaluated. + +Since Octave doesn't look for definitions until they are needed, the +following code will always print @samp{bar = 3} whether it is typed +directly on the command line, read from a script file, or is part of a +function body, even if there is a function or script file called +@file{bar.m} in Octave's @code{LOADPATH}. + +@example +@group +eval ("bar = 3"); +bar +@end group +@end example + +Code like this appearing within a function body could fool Octave if +definitions were resolved as the function was being compiled. It would +be virtually impossible to make Octave clever enough to evaluate this +code in a consistent fashion. The parser would have to be able to +perform the call to @code{eval} at compile time, and that would be +impossible unless all the references in the string to be evaluated could +also be resolved, and requiring that would be too restrictive (the +string might come from user input, or depend on things that are not +known until the function is evaluated). + +Although Octave normally executes commands from script files that have +the name @file{@var{file}.m}, you can use the function @code{source} to +execute commands from any file. + +@deftypefn {Built-in Function} {} source (@var{file}) +Parse and execute the contents of @var{file}. This is equivalent to +executing commands from a script file, but without requiring the file to +be named @file{@var{file}.m}. +@end deftypefn + +@node Dynamically Linked Functions, Organization of Functions, Script Files, Functions and Scripts +@section Dynamically Linked Functions +@cindex dynamic linking + +On some systems, Octave can dynamically load and execute functions +written in C++. Octave can only directly call functions written in C++, +but you can also load functions written in other languages +by calling them from a simple wrapper function written in C++. + +Here is an example of how to write a C++ function that Octave can load, +with commentary. The source for this function is included in the source +distributions of Octave, in the file @file{examples/oregonator.cc}. It +defines the same set of differential equations that are used in the +example problem of @ref{Ordinary Differential Equations}. By running +that example and this one, we can compare the execution times to see +what sort of increase in speed you can expect by using dynamically +linked functions. + +The function defined in @file{oregonator.cc} contains just 8 statements, +and is not much different than the code defined in the corresponding +M-file (also distributed with Octave in the file +@file{examples/oregonator.m}). + +Here is the complete text of @file{oregonator.cc}: + +just + +@example +@group +#include + +DEFUN_DLD (oregonator, args, , + "The `oregonator'.") +@{ + ColumnVector dx (3); + + ColumnVector x = args(0).vector_value (); + + dx(0) = 77.27 * (x(1) - x(0)*x(1) + x(0) + - 8.375e-06*pow (x(0), 2)); + + dx(1) = (x(2) - x(0)*x(1) - x(1)) / 77.27; + + dx(2) = 0.161*(x(0) - x(2)); + + return octave_value (dx); +@} +@end group +@end example + +The first line of the file, + +@example +#include +@end example + +@noindent +includes declarations for all of Octave's internal functions that you +will need. If you need other functions from the standard C++ or C +libraries, you can include the necessary headers here. + +The next two lines +@example +@group +DEFUN_DLD (oregonator, args, , + "The `oregonator'.") +@end group +@end example + +@noindent +declares the function. The macro @code{DEFUN_DLD} and the macros that +it depends on are defined in the files @file{defun-dld.h}, +@file{defun.h}, and @file{defun-int.h} (these files are included in the +header file @file{octave/oct.h}). + +Note that the third parameter to @code{DEFUN_DLD} (@code{nargout}) is +not used, so it is omitted from the list of arguments to in order to +avoid the warning from gcc about an unused function parameter. + +@noindent +simply declares an object to store the right hand sides of the +differential equation, and + +The statement + +@example +ColumnVector x = args(0).vector_value (); +@end example + +@noindent +extracts a column vector from the input arguments. The variable +@code{args} is passed to functions defined with @code{DEFUN_DLD} as an +@code{octave_value_list} object, which includes methods for getting the +length of the list and extracting individual elements. + +In this example, we don't check for errors, but that is not difficult. +All of the Octave's built-in functions do some form of checking on their +arguments, so you can check the source code for those functions for +examples of various strategies for verifying that the correct number and +types of arguments have been supplied. + +The next statements + +@example +@group +ColumnVector dx (3); + +dx(0) = 77.27 * (x(1) - x(0)*x(1) + x(0) + - 8.375e-06*pow (x(0), 2)); + +dx(1) = (x(2) - x(0)*x(1) - x(1)) / 77.27; + +dx(2) = 0.161*(x(0) - x(2)); +@end group +@end example + +@noindent +define the right hand side of the differential equation. Finally, we +can return @code{dx}: + +@example +return octave_value (dx); +@end example + +@noindent +The actual return type is @code{octave_value_list}, but it is only +necessary to convert the return type to an @code{octave_value} because +there is a default constructor that can automatically create an object +of that type from an @code{octave_value} object, so we can just use that +instead. + +To use this file, your version of Octave must support dynamic linking. +To find out if it does, type the command +@kbd{octave_config_info ("dld")} at the Octave prompt. Support for +dynamic linking is included if this command returns 1. + +To compile the example file, type the command @samp{mkoctfile +oregonator.cc} at the shell prompt. The script @code{mkoctfile} should +have been installed along with Octave. Running it will create a file +called @file{oregonator.oct} that can be loaded by Octave. To test the +@file{oregonator.oct} file, start Octave and type the command + +@example +oregonator ([1, 2, 3], 0) +@end example + +@noindent +at the Octave prompt. Octave should respond by printing + +@example +@group +ans = + + 77.269353 + -0.012942 + -0.322000 +@end group +@end example + +You can now use the @file{oregonator.oct} file just as you would the +@code{oregonator.m} file to solve the set of differential equations. + +On a 133 MHz Pentium running Linux, Octave can solve the problem shown +in @ref{Ordinary Differential Equations} in about 1.4 second using the +dynamically linked function, compared to about 19 seconds using the +M-file. Similar decreases in execution time can be expected for other +functions, particularly those that rely on functions like @code{lsode} +that require user-supplied functions. + +Just as for M-files, Octave will automatically reload dynamically linked +functions when the files that define them are more recent than the last +time that the function was loaded. Two variables are available to +control how Octave behaves when dynamically linked functions are cleared +or reloaded. + +@defvr {Built-in Variable} auto_unload_dot_oct_files +If the value of @code{auto_unload_dot_oct_files} is nonzero, Octave will +automatically unload any @file{.oct} files when there are no longer any +functions in the symbol table that reference them. +@end defvr + +@defvr {Built-in Variable} warn_reload_forces_clear +If several functions have been loaded from the same file, Octave must +clear all the functions before any one of them can be reloaded. If +@code{warn_reload_forces_clear}, Octave will warn you when this happens, +and print a list of the additional functions that it is forced to clear. +@end defvr + +Additional examples for writing dynamically linked functions are +available in the files in the @file{src} directory of the Octave +distribution. Currently, this includes the files + +@example +@group +balance.cc fft2.cc inv.cc qzval.cc +chol.cc filter.cc log.cc schur.cc +colloc.cc find.cc lsode.cc sort.cc +dassl.cc fsolve.cc lu.cc svd.cc +det.cc givens.cc minmax.cc syl.cc +eig.cc hess.cc pinv.cc +expm.cc ifft.cc qr.cc +fft.cc ifft2.cc quad.cc +@end group +@end example + +@noindent +These files use the macro @code{DEFUN_DLD_BUILTIN} instead of +@code{DEFUN_DLD}. The difference between these two macros is just that +@code{DEFUN_DLD_BUILTIN} can define a built-in function that is not +dynamically loaded if the operating system does not support dynamic +linking. To define your own dynamically linked functions you should use +@code{DEFUN_DLD}. + +There is currently no detailed description of all the functions that you +can call in a built-in function. For the time being, you will have to +read the source code for Octave. + +@node Organization of Functions, , Dynamically Linked Functions, Functions and Scripts +@section Organization of Functions Distributed with Octave + +Many of Octave's standard functions are distributed as function files. +They are loosely organized by topic, in subdirectories of +@file{@var{octave-home}/lib/octave/@var{version}/m}, to make it easier +to find them. + +The following is a list of all the function file subdirectories, and the +types of functions you will find there. + +@table @file +@item audio +Functions for playing and recording sounds. + +@item control +Functions for design and simulation of automatic control systems. + +@item elfun +Elementary functions. + +@item general +Miscellaneous matrix manipulations, like @code{flipud}, @code{rot90}, +and @code{triu}, as well as other basic functions, like +@code{is_matrix}, @code{nargchk}, etc. + +@item image +Image processing tools. These functions require the X Window System. + +@item io +Input-ouput functions. + +@item linear-algebra +Functions for linear algebra. + +@item miscellaneous +Functions that don't really belong anywhere else. + +@item plot +A set of functions that implement the @sc{Matlab}-like plotting functions. + +@item polynomial +Functions for manipulating polynomials. + +@item set +Functions for creating and manipulating sets of unique values. + +@item signal +Functions for signal processing applications. + +@item specfun +Special functions. + +@item special-matrix +Functions that create special matrix forms. + +@item startup +Octave's system-wide startup file. + +@item statistics +Statistical functions. + +@item strings +Miscellaneous string-handling functions. + +@item time +Functions related to time keeping. +@end table diff --git a/doc/interpreter/gpl.texi b/doc/interpreter/gpl.texi deleted file mode 100644 --- a/doc/interpreter/gpl.texi +++ /dev/null @@ -1,399 +0,0 @@ -@c Copyright (C) 1996, 1997 John W. Eaton -@c This is part of the Octave manual. -@c For copying conditions, see the file gpl.texi. - -@cindex warranty -@cindex copyright -@node Copying, Concept Index, Grammar, Top -@appendix GNU GENERAL PUBLIC LICENSE -@center Version 2, June 1991 - -@display -Copyright @copyright{} 1989, 1991 Free Software Foundation, Inc. -59 Temple Place - Suite 330, Boston, MA 02111-1307, USA - -Everyone is permitted to copy and distribute verbatim copies -of this license document, but changing it is not allowed. -@end display - -@appendixsec Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software---to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Library General Public License instead.) You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. - - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and -modification follow. - -@iftex -@appendixsec TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION -@end iftex -@ifinfo -@center TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION -@end ifinfo - -@enumerate 0 -@item -This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The ``Program'', below, -refers to any such program or work, and a ``work based on the Program'' -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term ``modification''.) Each licensee is addressed as ``you''. - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - -@item -You may copy and distribute verbatim copies of the Program's -source code as you receive it, in any medium, provided that you -conspicuously and appropriately publish on each copy an appropriate -copyright notice and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. - -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. - -@item -You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - -@enumerate a -@item -You must cause the modified files to carry prominent notices -stating that you changed the files and the date of any change. - -@item -You must cause any work that you distribute or publish, that in -whole or in part contains or is derived from the Program or any -part thereof, to be licensed as a whole at no charge to all third -parties under the terms of this License. - -@item -If the modified program normally reads commands interactively -when run, you must cause it, when started running for such -interactive use in the most ordinary way, to print or display an -announcement including an appropriate copyright notice and a -notice that there is no warranty (or else, saying that you provide -a warranty) and that users may redistribute the program under -these conditions, and telling the user how to view a copy of this -License. (Exception: if the Program itself is interactive but -does not normally print such an announcement, your work based on -the Program is not required to print an announcement.) -@end enumerate - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - -@item -You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - -@enumerate a -@item -Accompany it with the complete corresponding machine-readable -source code, which must be distributed under the terms of Sections -1 and 2 above on a medium customarily used for software interchange; or, - -@item -Accompany it with a written offer, valid for at least three -years, to give any third party, for a charge no more than your -cost of physically performing source distribution, a complete -machine-readable copy of the corresponding source code, to be -distributed under the terms of Sections 1 and 2 above on a medium -customarily used for software interchange; or, - -@item -Accompany it with the information you received as to the offer -to distribute corresponding source code. (This alternative is -allowed only for noncommercial distribution and only if you -received the program in object code or executable form with such -an offer, in accord with Subsection b above.) -@end enumerate - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - -@item -You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. - -@item -You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - -@item -Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to -this License. - -@item -If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - -@item -If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - -@item -The Free Software Foundation may publish revised and/or new versions -of the General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and ``any -later version'', you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - -@item -If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. - -@iftex -@heading NO WARRANTY -@end iftex -@ifinfo -@center NO WARRANTY -@end ifinfo - -@item -BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. - -@item -IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. -@end enumerate - -@iftex -@heading END OF TERMS AND CONDITIONS -@end iftex -@ifinfo -@center END OF TERMS AND CONDITIONS -@end ifinfo - -@page -@appendixsec Appendix: How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least -the ``copyright'' line and a pointer to where the full notice is found. - -@smallexample -@var{one line to give the program's name and a brief idea of what it does.} -Copyright (C) 19@var{yy} @var{name of author} - -This program is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA -02111-1307, USA. -@end smallexample - -Also add information on how to contact you by electronic and paper mail. - -If the program is interactive, make it output a short notice like this -when it starts in an interactive mode: - -@smallexample -Gnomovision version 69, Copyright (C) 19@var{yy} @var{name of author} -Gnomovision comes with ABSOLUTELY NO WARRANTY; for details -type `show w'. This is free software, and you are welcome -to redistribute it under certain conditions; type `show c' -for details. -@end smallexample - -The hypothetical commands @samp{show w} and @samp{show c} should show -the appropriate parts of the General Public License. Of course, the -commands you use may be called something other than @samp{show w} and -@samp{show c}; they could even be mouse-clicks or menu items---whatever -suits your program. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a ``copyright disclaimer'' for the program, if -necessary. Here is a sample; alter the names: - -@example -Yoyodyne, Inc., hereby disclaims all copyright interest in the program -`Gnomovision' (which makes passes at compilers) written by James Hacker. - -@var{signature of Ty Coon}, 1 April 1989 -Ty Coon, President of Vice -@end example - -This General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may -consider it more useful to permit linking proprietary applications with the -library. If this is what you want to do, use the GNU Library General -Public License instead of this License. - diff --git a/doc/interpreter/gpl.txi b/doc/interpreter/gpl.txi new file mode 100644 --- /dev/null +++ b/doc/interpreter/gpl.txi @@ -0,0 +1,399 @@ +@c Copyright (C) 1996, 1997 John W. Eaton +@c This is part of the Octave manual. +@c For copying conditions, see the file gpl.texi. + +@cindex warranty +@cindex copyright +@node Copying, Concept Index, Grammar, Top +@appendix GNU GENERAL PUBLIC LICENSE +@center Version 2, June 1991 + +@display +Copyright @copyright{} 1989, 1991 Free Software Foundation, Inc. +59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + +Everyone is permitted to copy and distribute verbatim copies +of this license document, but changing it is not allowed. +@end display + +@appendixsec Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software---to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Library General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + +@iftex +@appendixsec TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION +@end iftex +@ifinfo +@center TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION +@end ifinfo + +@enumerate 0 +@item +This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The ``Program'', below, +refers to any such program or work, and a ``work based on the Program'' +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term ``modification''.) Each licensee is addressed as ``you''. + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + +@item +You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + +@item +You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + +@enumerate a +@item +You must cause the modified files to carry prominent notices +stating that you changed the files and the date of any change. + +@item +You must cause any work that you distribute or publish, that in +whole or in part contains or is derived from the Program or any +part thereof, to be licensed as a whole at no charge to all third +parties under the terms of this License. + +@item +If the modified program normally reads commands interactively +when run, you must cause it, when started running for such +interactive use in the most ordinary way, to print or display an +announcement including an appropriate copyright notice and a +notice that there is no warranty (or else, saying that you provide +a warranty) and that users may redistribute the program under +these conditions, and telling the user how to view a copy of this +License. (Exception: if the Program itself is interactive but +does not normally print such an announcement, your work based on +the Program is not required to print an announcement.) +@end enumerate + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + +@item +You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + +@enumerate a +@item +Accompany it with the complete corresponding machine-readable +source code, which must be distributed under the terms of Sections +1 and 2 above on a medium customarily used for software interchange; or, + +@item +Accompany it with a written offer, valid for at least three +years, to give any third party, for a charge no more than your +cost of physically performing source distribution, a complete +machine-readable copy of the corresponding source code, to be +distributed under the terms of Sections 1 and 2 above on a medium +customarily used for software interchange; or, + +@item +Accompany it with the information you received as to the offer +to distribute corresponding source code. (This alternative is +allowed only for noncommercial distribution and only if you +received the program in object code or executable form with such +an offer, in accord with Subsection b above.) +@end enumerate + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + +@item +You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + +@item +You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + +@item +Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + +@item +If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + +@item +If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + +@item +The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and ``any +later version'', you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + +@item +If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + +@iftex +@heading NO WARRANTY +@end iftex +@ifinfo +@center NO WARRANTY +@end ifinfo + +@item +BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + +@item +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. +@end enumerate + +@iftex +@heading END OF TERMS AND CONDITIONS +@end iftex +@ifinfo +@center END OF TERMS AND CONDITIONS +@end ifinfo + +@page +@appendixsec Appendix: How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the ``copyright'' line and a pointer to where the full notice is found. + +@smallexample +@var{one line to give the program's name and a brief idea of what it does.} +Copyright (C) 19@var{yy} @var{name of author} + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA +02111-1307, USA. +@end smallexample + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + +@smallexample +Gnomovision version 69, Copyright (C) 19@var{yy} @var{name of author} +Gnomovision comes with ABSOLUTELY NO WARRANTY; for details +type `show w'. This is free software, and you are welcome +to redistribute it under certain conditions; type `show c' +for details. +@end smallexample + +The hypothetical commands @samp{show w} and @samp{show c} should show +the appropriate parts of the General Public License. Of course, the +commands you use may be called something other than @samp{show w} and +@samp{show c}; they could even be mouse-clicks or menu items---whatever +suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a ``copyright disclaimer'' for the program, if +necessary. Here is a sample; alter the names: + +@example +Yoyodyne, Inc., hereby disclaims all copyright interest in the program +`Gnomovision' (which makes passes at compilers) written by James Hacker. + +@var{signature of Ty Coon}, 1 April 1989 +Ty Coon, President of Vice +@end example + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Library General +Public License instead of this License. + diff --git a/doc/interpreter/grammar.texi b/doc/interpreter/grammar.texi deleted file mode 100644 --- a/doc/interpreter/grammar.texi +++ /dev/null @@ -1,58 +0,0 @@ -@c Copyright (C) 1996, 1997 John W. Eaton -@c This is part of the Octave manual. -@c For copying conditions, see the file gpl.texi. - -@node Grammar, Copying, Emacs, Top -@chapter Grammar -@cindex grammar rules -@cindex language definition - -Someday I hope to expand this to include a semi-formal description of -Octave's language. - -@menu -* Keywords:: -@end menu - -@node Keywords, , Grammar, Grammar -@section Keywords -@cindex keywords - -The following identifiers are keywords, and may not be used as variable -or function names: - -@example -@group -all_va_args endwhile -break for -case function -catch global -continue gplot -else gsplot -elseif if -end otherwise -end_try_catch return -end_unwind_protect switch -endfor try -endfunction unwind_protect -endif unwind_protect_cleanup -endswitch while -@end group -@end example - -The following command-like functions are also speical. They may be used -as simple variable names, but not as formal parameters for functions, or -as the names of structure variables. Failed assignments leave them -undefined (you can recover the orginal definition as a function using -clear). - -@example -@group -casesen echo load show -cd edit_history ls type -chdir format more which -clear help run_history who -diary history save whos -dir hold set -@end group -@end example diff --git a/doc/interpreter/grammar.txi b/doc/interpreter/grammar.txi new file mode 100644 --- /dev/null +++ b/doc/interpreter/grammar.txi @@ -0,0 +1,58 @@ +@c Copyright (C) 1996, 1997 John W. Eaton +@c This is part of the Octave manual. +@c For copying conditions, see the file gpl.texi. + +@node Grammar, Copying, Emacs, Top +@chapter Grammar +@cindex grammar rules +@cindex language definition + +Someday I hope to expand this to include a semi-formal description of +Octave's language. + +@menu +* Keywords:: +@end menu + +@node Keywords, , Grammar, Grammar +@section Keywords +@cindex keywords + +The following identifiers are keywords, and may not be used as variable +or function names: + +@example +@group +all_va_args endwhile +break for +case function +catch global +continue gplot +else gsplot +elseif if +end otherwise +end_try_catch return +end_unwind_protect switch +endfor try +endfunction unwind_protect +endif unwind_protect_cleanup +endswitch while +@end group +@end example + +The following command-like functions are also speical. They may be used +as simple variable names, but not as formal parameters for functions, or +as the names of structure variables. Failed assignments leave them +undefined (you can recover the orginal definition as a function using +clear). + +@example +@group +casesen echo load show +cd edit_history ls type +chdir format more which +clear help run_history who +diary history save whos +dir hold set +@end group +@end example diff --git a/doc/interpreter/image.texi b/doc/interpreter/image.texi deleted file mode 100644 --- a/doc/interpreter/image.texi +++ /dev/null @@ -1,138 +0,0 @@ -@c Copyright (C) 1996, 1997 John W. Eaton -@c This is part of the Octave manual. -@c For copying conditions, see the file gpl.texi. - -@node Image Processing, Audio Processing, Signal Processing, Top -@chapter Image Processing - -Octave can display images with the X Window System using the -@code{xloadimage} program. You do not need to be running X in order to -manipulate images, however, so some of these functions may be useful -even if you are not able to view the results. - -Loading images only works with Octave's image format (a file with a -matrix containing the image data, and a matrix containing the -colormap). Contributions of robust, well-written functions to read -other image formats are welcome. If you can provide them, or would like -to improve Octave's image processing capabilities in other ways, please -contact @email{bug-octave@@bevo.che.wisc.edu}. - -@deftypefn {Function File} {} colormap (@var{map}) -@deftypefnx {Function File} {} colormap ("default") -Set the current colormap. - -@code{colormap (@var{map})} sets the current colormap to @var{map}. The -color map should be an @var{n} row by 3 column matrix. The columns -contain red, green, and blue intensities respectively. All entries -should be between 0 and 1 inclusive. The new colormap is returned. - -@code{colormap ("default")} restores the default colormap (a gray scale -colormap with 64 entries). The default colormap is returned. - -With no arguments, @code{colormap} returns the current color map. -@end deftypefn - -@deftypefn {Function File} {} gray (@var{n}) -Return a gray colormap with @var{n} entries corresponding to values from -0 to @var{n}-1. The argument @var{n} should be a scalar. If it is -omitted, 64 is assumed. -@end deftypefn - -@deftypefn {Function File} {[@var{img}, @var{map}] =} gray2ind (@var{}) -Convert a gray scale intensity image to an Octave indexed image. -@end deftypefn - -@deftypefn {Function File} {} image (@var{x}, @var{zoom}) -Display a matrix as a color image. The elements of @var{x} are indices -into the current colormap and should have values between 1 and the -length of the colormap. If @var{zoom} is omitted, a value of 4 is -assumed. -@end deftypefn - -@deftypefn {Function File} {} imagesc (@var{x}, @var{zoom}) -Display a scaled version of the matrix @var{x} as a color image. The -matrix is scaled so that its entries are indices into the current -colormap. The scaled matrix is returned. If @var{zoom} is omitted, a -value of 4 is assumed. -@end deftypefn - -@deftypefn {Function File} {} imshow (@var{x}, @var{map}) -@deftypefnx {Function File} {} imshow (@var{x}, @var{n}) -@deftypefnx {Function File} {} imshow (@var{i}, @var{n}) -@deftypefnx {Function File} {} imshow (@var{r}, @var{g}, @var{b}) -Display images. - -@code{imshow (@var{x})} displays an indexed image using the current -colormap. - -@code{imshow (@var{x}, @var{map})} displays an indexed image using the -specified colormap. - -@code{imshow (@var{i}, @var{n})} displays a gray scale intensity image. - -@code{imshow (@var{r}, @var{g}, @var{b})} displays an RGB image. -@end deftypefn - -@deftypefn {Function File} {} ind2gray (@var{x}, @var{map}) -Convert an Octave indexed image to a gray scale intensity image. -If @var{map} is omitted, the current colormap is used to determine the -intensities. -@end deftypefn - -@deftypefn {Function File} {[@var{r}, @var{g}, @var{b}] =} ind2rgb (@var{x}, @var{map}) -Convert an indexed image to red, green, and blue color components. -If @var{map} is omitted, the current colormap is used for the conversion. -@end deftypefn - -@deftypefn {Function File} {[@var{x}, @var{map}] =} loadimage (@var{file}) -Load an image file and it's associated color map from the specified -@var{file}. The image must be stored in Octave's image format. -@end deftypefn - -@deftypefn {Function File} {} rgb2ntsc (@var{rgb}) -Image format conversion. -@end deftypefn - -@deftypefn {Function File} {} ntsc2rgb (@var{yiq}) -Image format conversion. -@end deftypefn - -@deftypefn {Function File} {} ocean (@var{n}) -Create color colormap. The argument @var{n} should be a scalar. If it -is omitted, 64 is assumed. -@end deftypefn - -@deftypefn {Function File} {[@var{x}, @var{map}] =} rgb2ind (@var{r}, @var{g}, @var{b}) -Convert and RGB image to an Octave indexed image. -@end deftypefn - -@deftypefn {Function File} {} saveimage (@var{file}, @var{x}, @var{fmt}, @var{map}) -Save the matrix @var{x} to @var{file} in image format @var{fmt}. Valid -values for @var{fmt} are - -@table @code -@item "img" -Octave's image format. The current colormap is also saved in the file. - -@item "ppm" -Portable pixmap format. - -@item "ps" -PostScript format. Note that images saved in PostScript format can not -be read back into Octave with loadimage. -@end table - -If the fourth argument is supplied, the specified colormap will also be -saved along with the image. - -Note: if the colormap contains only two entries and these entries are -black and white, the bitmap ppm and PostScript formats are used. If the -image is a gray scale image (the entries within each row of the colormap -are equal) the gray scale ppm and PostScript image formats are used, -otherwise the full color formats are used. -@end deftypefn - -@defvr {Built-in Variable} IMAGEPATH -A colon separated list of directories in which to search for image -files. -@end defvr diff --git a/doc/interpreter/image.txi b/doc/interpreter/image.txi new file mode 100644 --- /dev/null +++ b/doc/interpreter/image.txi @@ -0,0 +1,138 @@ +@c Copyright (C) 1996, 1997 John W. Eaton +@c This is part of the Octave manual. +@c For copying conditions, see the file gpl.texi. + +@node Image Processing, Audio Processing, Signal Processing, Top +@chapter Image Processing + +Octave can display images with the X Window System using the +@code{xloadimage} program. You do not need to be running X in order to +manipulate images, however, so some of these functions may be useful +even if you are not able to view the results. + +Loading images only works with Octave's image format (a file with a +matrix containing the image data, and a matrix containing the +colormap). Contributions of robust, well-written functions to read +other image formats are welcome. If you can provide them, or would like +to improve Octave's image processing capabilities in other ways, please +contact @email{bug-octave@@bevo.che.wisc.edu}. + +@deftypefn {Function File} {} colormap (@var{map}) +@deftypefnx {Function File} {} colormap ("default") +Set the current colormap. + +@code{colormap (@var{map})} sets the current colormap to @var{map}. The +color map should be an @var{n} row by 3 column matrix. The columns +contain red, green, and blue intensities respectively. All entries +should be between 0 and 1 inclusive. The new colormap is returned. + +@code{colormap ("default")} restores the default colormap (a gray scale +colormap with 64 entries). The default colormap is returned. + +With no arguments, @code{colormap} returns the current color map. +@end deftypefn + +@deftypefn {Function File} {} gray (@var{n}) +Return a gray colormap with @var{n} entries corresponding to values from +0 to @var{n}-1. The argument @var{n} should be a scalar. If it is +omitted, 64 is assumed. +@end deftypefn + +@deftypefn {Function File} {[@var{img}, @var{map}] =} gray2ind (@var{}) +Convert a gray scale intensity image to an Octave indexed image. +@end deftypefn + +@deftypefn {Function File} {} image (@var{x}, @var{zoom}) +Display a matrix as a color image. The elements of @var{x} are indices +into the current colormap and should have values between 1 and the +length of the colormap. If @var{zoom} is omitted, a value of 4 is +assumed. +@end deftypefn + +@deftypefn {Function File} {} imagesc (@var{x}, @var{zoom}) +Display a scaled version of the matrix @var{x} as a color image. The +matrix is scaled so that its entries are indices into the current +colormap. The scaled matrix is returned. If @var{zoom} is omitted, a +value of 4 is assumed. +@end deftypefn + +@deftypefn {Function File} {} imshow (@var{x}, @var{map}) +@deftypefnx {Function File} {} imshow (@var{x}, @var{n}) +@deftypefnx {Function File} {} imshow (@var{i}, @var{n}) +@deftypefnx {Function File} {} imshow (@var{r}, @var{g}, @var{b}) +Display images. + +@code{imshow (@var{x})} displays an indexed image using the current +colormap. + +@code{imshow (@var{x}, @var{map})} displays an indexed image using the +specified colormap. + +@code{imshow (@var{i}, @var{n})} displays a gray scale intensity image. + +@code{imshow (@var{r}, @var{g}, @var{b})} displays an RGB image. +@end deftypefn + +@deftypefn {Function File} {} ind2gray (@var{x}, @var{map}) +Convert an Octave indexed image to a gray scale intensity image. +If @var{map} is omitted, the current colormap is used to determine the +intensities. +@end deftypefn + +@deftypefn {Function File} {[@var{r}, @var{g}, @var{b}] =} ind2rgb (@var{x}, @var{map}) +Convert an indexed image to red, green, and blue color components. +If @var{map} is omitted, the current colormap is used for the conversion. +@end deftypefn + +@deftypefn {Function File} {[@var{x}, @var{map}] =} loadimage (@var{file}) +Load an image file and it's associated color map from the specified +@var{file}. The image must be stored in Octave's image format. +@end deftypefn + +@deftypefn {Function File} {} rgb2ntsc (@var{rgb}) +Image format conversion. +@end deftypefn + +@deftypefn {Function File} {} ntsc2rgb (@var{yiq}) +Image format conversion. +@end deftypefn + +@deftypefn {Function File} {} ocean (@var{n}) +Create color colormap. The argument @var{n} should be a scalar. If it +is omitted, 64 is assumed. +@end deftypefn + +@deftypefn {Function File} {[@var{x}, @var{map}] =} rgb2ind (@var{r}, @var{g}, @var{b}) +Convert and RGB image to an Octave indexed image. +@end deftypefn + +@deftypefn {Function File} {} saveimage (@var{file}, @var{x}, @var{fmt}, @var{map}) +Save the matrix @var{x} to @var{file} in image format @var{fmt}. Valid +values for @var{fmt} are + +@table @code +@item "img" +Octave's image format. The current colormap is also saved in the file. + +@item "ppm" +Portable pixmap format. + +@item "ps" +PostScript format. Note that images saved in PostScript format can not +be read back into Octave with loadimage. +@end table + +If the fourth argument is supplied, the specified colormap will also be +saved along with the image. + +Note: if the colormap contains only two entries and these entries are +black and white, the bitmap ppm and PostScript formats are used. If the +image is a gray scale image (the entries within each row of the colormap +are equal) the gray scale ppm and PostScript image formats are used, +otherwise the full color formats are used. +@end deftypefn + +@defvr {Built-in Variable} IMAGEPATH +A colon separated list of directories in which to search for image +files. +@end defvr diff --git a/doc/interpreter/install.texi b/doc/interpreter/install.texi deleted file mode 100644 --- a/doc/interpreter/install.texi +++ /dev/null @@ -1,566 +0,0 @@ -@c Copyright (C) 1996, 1997 John W. Eaton -@c This is part of the Octave manual. -@c For copying conditions, see the file gpl.texi. - -@c The text of this file will eventually appear in the file INSTALL -@c in the Octave distribution, as well as in the Octave manual. - -@ifclear INSTALLONLY -@node Installation, Emacs, Trouble, Top -@appendix Installing Octave -@end ifclear - -@ifset INSTALLONLY -@include conf.texi - -This file documents the installation of Octave. - -Octave is free software; you can redistribute it and/or modify it -under the terms of the GNU General Public License as published by the -Free Software Foundation. - -@node Installation, , Installation -@chapter Installing Octave -@end ifset - -@cindex installing Octave - -Here is the procedure for installing Octave from scratch on a Unix -system. For instructions on how to install the binary distributions of -Octave, see @ref{Binary Distributions}. - -@itemize @bullet -@item -Run the shell script @file{configure}. This will determine the features -your system has (or doesn't have) and create a file named -@file{Makefile} from each of the files named @file{Makefile.in}. - -Here is a summary of the configure options that are most frequently used -when building Octave: - -@table @code -@item --prefix=@var{prefix} -Install Octave in subdirectories below @var{prefix}. The default value -of @var{prefix} is @file{/usr/local}. - -@item --srcdir=@var{dir} -Look for Octave sources in the directory @var{dir}. - -@item --with-f2c -Use @code{f2c} even if a Fortran compiler is available. - -@item --with-g77 -Use @code{g77} to compile Fortran code. - -@item --enable-shared -Create shared libraries. If you are planning to use -@code{--enable-lite-kernelel} or the dynamic loading features, you will -probably want to use this option. It will make your @file{.oct} files -much smaller and on some systems it may be necessary to build shared -libraries in order to use dynamically linked functions. - -You may also want to build a shared version of @code{libstdc++}, if your -system doesn't already have one. Note that a patch is needed to build -shared versions of version 2.7.2 of @code{libstdc++} on the HP-PA -architecture. You can find the patch at -@url{ftp://ftp.cygnus.com/pub/g++/libg++-2.7.2-hppa-gcc-fix}. - -@item --enable-dl -Use @code{dlopen} and friends to make Octave capable of dynamically -linking externally compiled functions. This only works on systems that -actually have these functions. If you plan on using this feature, you -should probably also use @code{--enable-shared} to reduce the size of -your @file{.oct} files. - -@item --enable-shl -Use @code{shl_load} and friends to make Octave capable of dynamically -linking externally compiled functions. This only works on systems that -actually have these functions (only HP-UX systems). If you plan on -using this feature, you should probably also use @code{--enable-shared} -to reduce the size of your @file{.oct} files. - -@item --enable-lite-kernel -Compile smaller kernel. This currently requires the dynamic linking -functions @code{dlopen} or @code{shl_load} and friends so that Octave -can load functions at run time that are not loaded at compile time. - -@item --help -Print a summary of the options recognized by the configure script. -@end table - -See the file @file{INSTALL} for more information about the command line -options used by configure. That file also contains instructions for -compiling in a directory other than where the source is located. - -@item -Run make. - -You will need a recent version of GNU Make. Modifying Octave's -makefiles to work with other make programs is probably not worth -your time. We recommend you get and compile GNU Make instead. - -For plotting, you will need to have gnuplot installed on your system. -Gnuplot is a command-driven interactive function plotting program. -Gnuplot is copyrighted, but freely distributable. The `gnu' in gnuplot -is a coincidence---it is not related to the GNU project or the FSF in -any but the most peripheral sense. - -To compile Octave, you will need a recent version of GNU Make. You -will also need @code{g++} 2.7.2 or later. Version 2.8.0 or @code{egcs} -1.0.x should work. Later versions may work, but C++ is still evolving, -so don't be too surprised if you run into some trouble. - -It is no longer necessary to have @code{libg++}, but you do need to have -the GNU implementation of @code{libstdc++}. If you are using @code{g++} -2.7.2, @code{libstdc++} is distributed along with @code{libg++}, but for -later versions, @code{libstdc++} is distributed separately. For -@code{egcs}, @code{libstdc++} is included with the compiler -distribution. - -If you plan to modify the parser you will also need GNU @code{bison} and -@code{flex}. If you modify the documentation, you will need GNU -Texinfo, along with the patch for the @code{makeinfo} program that is -distributed with Octave. - -GNU Make, @code{gcc}, and @code{libstdc++}, @code{gnuplot}, -@code{bison}, @code{flex}, and Texinfo are all available from many -anonymous ftp archives. The primary site is @url{ftp.gnu.org}, but it -is often very busy. A list of sites that mirror the software on -@url{ftp.gnu.org} is available by anonymous ftp from -@url{ftp://ftp.gnu.org/pub/gnu/GNUinfo/FTP}. - -If you don't have a Fortran compiler, or if your Fortran compiler -doesn't work like the traditional Unix f77, you will need to have the -Fortran to C translator @code{f2c}. You can get @code{f2c} from any -number of anonymous ftp archives. The most recent version of @code{f2c} -is always available from @url{netlib.att.com}. - -On an otherwise idle Pentium 133 running Linux, it will take somewhere -between 1-1/2 to 3 hours to compile everything, depending on whether you -are building shared libraries. You will need about 100 megabytes of disk -storage to work with (considerably less if you don't compile with debugging -symbols). To do that, use the command - -@example -make CFLAGS=-O CXXFLAGS=-O LDFLAGS= -@end example - -@noindent -instead of just @samp{make}. - -@item -If you encounter errors while compiling Octave, first check the list of -known problems below to see if there is a workaround or solution for -your problem. If not, -@ifclear INSTALLONLY -see @ref{Trouble}, -@end ifclear -@ifset INSTALLONLY -see the file BUGS -@end ifset -for information about how to report bugs. - -@item -Once you have successfully compiled Octave, run @samp{make install}. - -This will install a copy of octave, its libraries, and its documentation -in the destination directory. As distributed, Octave is installed in -the following directories. In the table below, @var{prefix} defaults to -@file{/usr/local}, @var{version} stands for the current version number -of the interpreter, and @var{arch} is the type of computer on which -Octave is installed (for example, @samp{i586-unknown-gnu}). - -@table @file -@item @var{prefix}/bin -Octave and other binaries that people will want to run directly. - -@item @var{prefix}/lib -Libraries like libcruft.a and liboctave.a. - -@item @var{prefix}/share -Architecture-independent data files. - -@item @var{prefix}/include/octave -Include files distributed with Octave. - -@item @var{prefix}/man/man1 -Unix-style man pages describing Octave. - -@item @var{prefix}/info -Info files describing Octave. - -@item @var{prefix}/share/octave/@var{version}/m -Function files distributed with Octave. This includes the Octave -version, so that multiple versions of Octave may be installed at the -same time. - -@item @var{prefix}/lib/octave/@var{version}/exec/@var{arch} -Executables to be run by Octave rather than the user. - -@item @var{prefix}/lib/octave/@var{version}/oct/@var{arch} -Object files that will be dynamically loaded. - -@item @var{prefix}/share/octave/@var{version}/imagelib -Image files that are distributed with Octave. -@end table -@end itemize - -@menu -* Installation Problems:: -* Binary Distributions:: -@end menu - -@node Installation Problems, Binary Distributions, Installation, Installation -@appendixsec Installation Problems - -This section contains a list of problems (and some apparent problems -that don't really mean anything is wrong) that may show up during -installation of Octave. - -@itemize @bullet -@item -On some SCO systems, @code{info} fails to compile if -@code{HAVE_TERMIOS_H} is defined int @file{config.h}. Simply removing -the definition from @file{info/config.h} should allow it to compile. - -@item -If @code{configure} finds @code{dlopen}, @code{dlsym}, @code{dlclose}, -and @code{dlerror}, but not the header file @file{dlfcn.h}, you need to -find the source for the header file and install it in the directory -@file{usr/include}. This is reportedly a problem with Slackware 3.1. -For Linux/GNU systems, the source for @file{dlfcn.h} is in the -@code{ldso} package. - -@item -Building @file{.oct} files doesn't work. - -You should probably have a shared version of @code{libstdc++}. A patch -is needed to build shared versions of version 2.7.2 of @code{libstdc++} -on the HP-PA architecture. You can find the patch at -@url{ftp://ftp.cygnus.com/pub/g++/libg++-2.7.2-hppa-gcc-fix}. - -@item -On FreeBSD systems Octave may hang while initializing some internal -constants. The fix appears to be to use - -@example -options GPL_MATH_EMULATE -@end example - -@noindent -rather than - -@example -options MATH_EMULATE -@end example - -@noindent -in the kernel configuration files (typically found in the directory -@file{/sys/i386/conf}. After making this change, you'll need to rebuild -the kernel, install it, and reboot. - -@item -If you encounter errors like - -@smallexample -@group -passing `void (*)()' as argument 2 of - `octave_set_signal_handler(int, void (*)(int))' -@end group -@end smallexample - -@noindent -or - -@smallexample -warning: ANSI C++ prohibits conversion from `(int)' to `(...)' -@end smallexample - -@noindent -while compiling @file{sighandlers.cc}, you may need to edit some files -in the @code{gcc} include subdirectory to add proper prototypes for functions -there. For example, Ultrix 4.2 needs proper declarations for the -@code{signal} function and the @code{SIG_IGN} macro in the file -@file{signal.h}. - -On some systems the @code{SIG_IGN} macro is defined to be something like -this: - -@example -#define SIG_IGN (void (*)())1 -@end example - -@noindent -when it should really be something like: - -@example -#define SIG_IGN (void (*)(int))1 -@end example - -@noindent -to match the prototype declaration for the @code{signal} function. This -change should also be made for the @code{SIG_DFL} and @code{SIG_ERR} -symbols. It may be necessary to change the definitions in -@file{sys/signal.h} as well. - -The @code{gcc} @code{fixincludes} and @code{fixproto} scripts should -probably fix these problems when @code{gcc} installs its modified set of -header files, but I don't think that's been done yet. - -@strong{You should not change the files in @file{/usr/include}}. You -can find the @code{gcc} include directory tree by running the command - -@example -gcc -print-libgcc-file-name -@end example - -@noindent -The directory of @code{gcc} include files normally begins in the same directory -that contains the file @file{libgcc.a}. - -@item -Some of the Fortran subroutines may fail to compile with older versions -of the Sun Fortran compiler. If you get errors like - -@smallexample -zgemm.f: - zgemm: -warning: unexpected parent of complex expression subtree -zgemm.f, line 245: warning: unexpected parent of complex - expression subtree -warning: unexpected parent of complex expression subtree -zgemm.f, line 304: warning: unexpected parent of complex - expression subtree -warning: unexpected parent of complex expression subtree -zgemm.f, line 327: warning: unexpected parent of complex - expression subtree -pcc_binval: missing IR_CONV in complex op -make[2]: *** [zgemm.o] Error 1 -@end smallexample - -@noindent -when compiling the Fortran subroutines in the @file{libcruft} -subdirectory, you should either upgrade your compiler or try compiling -with optimization turned off. - -@item -On NeXT systems, if you get errors like this: - -@example -/usr/tmp/cc007458.s:unknown:Undefined local symbol LBB7656 -/usr/tmp/cc007458.s:unknown:Undefined local symbol LBE7656 -@end example - -@noindent -when compiling @file{Array.cc} and @file{Matrix.cc}, try recompiling -these files without @code{-g}. - -@item -Some people have reported that calls to shell_cmd and the pager do not -work on SunOS systems. This is apparently due to having -@code{G_HAVE_SYS_WAIT} defined to be 0 instead of 1 when compiling -@code{libg++}. - -@item -On NeXT systems, linking to @file{libsys_s.a} may fail to resolve the -following functions - -@example -_tcgetattr -_tcsetattr -_tcflow -@end example - -@noindent -which are part of @file{libposix.a}. Unfortunately, linking Octave with -@code{-posix} results in the following undefined symbols. - -@example -.destructors_used -.constructors_used -_objc_msgSend -_NXGetDefaultValue -_NXRegisterDefaults -.objc_class_name_NXStringTable -.objc_class_name_NXBundle -@end example - -One kluge around this problem is to extract @file{termios.o} from -@file{libposix.a}, put it in Octave's @file{src} directory, and add it -to the list of files to link together in the makefile. Suggestions for -better ways to solve this problem are welcome! - -@item -If Octave crashes immediately with a floating point exception, it is -likely that it is failing to initialize the IEEE floating point values -for infinity and NaN. - -If your system actually does support IEEE arithmetic, you should be able -to fix this problem by modifying the function @code{octave_ieee_init} in -the file @file{lo-ieee.cc} to correctly initialize Octave's internal -infinity and NaN variables. - -If your system does not support IEEE arithmetic but Octave's configure -script incorrectly determined that it does, you can work around the -problem by editing the file @file{config.h} to not define -@code{HAVE_ISINF}, @code{HAVE_FINITE}, and @code{HAVE_ISNAN}. - -In any case, please report this as a bug since it might be possible to -modify Octave's configuration script to automatically determine the -proper thing to do. - -@item -After installing the binary distribution of Octave in an alternate -directory, the Emacs command @code{run-octave} doesn't work. Emacs -hangs in @code{accept-process-output} in @code{inferior-octave-startup}. - -This seems to be a problem with executing a shell script using the -comint package. You can avoid the problem by changing the way Octave is -installed to eliminate the need for the shell script. You can either -compile and install Octave using the source distribution, reinstall the -binary distribution in the default directory, or copy the commands in -the octave shell script wrapper to your shell startup files (and the -shell startup files for anyone else who is using Octave) and then -rename the file @file{octave.bin} to be @file{octave}. -@end itemize - -@node Binary Distributions, , Installation Problems, Installation -@appendixsec Binary Distributions - -Although Octave is not very difficult to build from its sources, it is a -relatively large program that does require a significant amount of time -and disk space to compile and install. Because of this, many people -want to be able to obtain binary distributions so they can start using -Octave immediately, without having to bother with the details of -compiling it first. This is understandable, so I try to maintain a -current collection of binary distributions at -@url{ftp://ftp.che.wisc.edu/pub/octave/BINARIES}. - -Please understand, however, that there is only a limited amount of time -available to devote to making binaries, so binaries may not be -immediately available for some platforms. (Please contact -@email{bug-octave@@bevo.che.wisc.edu} if you are interested in helping -make a binary distribution available for your system.) - -@menu -* Installing Octave from a Binary Distribution:: -* Creating a Binary Distribution:: -@end menu - -@node Installing Octave from a Binary Distribution, Creating a Binary Distribution, Binary Distributions, Binary Distributions -@appendixsubsec Installing Octave from a Binary Distribution - -To install Octave from a binary distribution, execute the command - -@example -sh ./install-octave -@end example - -@noindent -in the top level directory of the distribution. - -Binary distributions are normally compiled assuming that Octave will be -installed in the following subdirectories of @file{/usr/local}. - -@table @file -@item bin -Octave and other binaries that people will want to run directly. - -@item lib -Shared libraries that Octave needs in order to run. These files are -not included if you are installing a statically linked version of -Octave. - -@item man/man1 -Unix-style man pages describing Octave. - -@item info -Info files describing Octave. - -@item share/octave/@var{version}/m -Function files distributed with Octave. This includes the Octave -version, so that multiple versions of Octave may be installed at the -same time. - -@item libexec/octave/@var{version}/exec/@var{arch} -Executables to be run by Octave rather than the user. - -@item libexec/octave/@var{version}/oct/@var{arch} -Object files that will be dynamically loaded. - -@item share/octave/@var{version}/imagelib -Image files that are distributed with Octave. -@end table - -@noindent -where @var{version} stands for the current version number of the -interpreter, and @var{arch} is the type of computer on which Octave -is installed (for example, @samp{@value{TARGETHOSTTYPE}}). - -If these directories don't exist, the script @code{install-octave} will -create them for you. The installation script also creates the following -subdirectories of @file{/usr/local} that are intended for locally -installed functions: - -@table @file -@item share/octave/site/m -Locally installed M-files. - -@item libexec/octave/site/exec/@var{arch} -Locally installed binaries intended to be run by Octave rather than by -the user. - -@item libexec/octave/site/octave/@var{arch} -Local object files that will be dynamically linked. -@end table - -If it is not possible for you to install Octave in @file{/usr/local}, or -if you would prefer to install it in a different directory, you can -specify the name of the top level directory as an argument to the -@file{install-octave} script. For example: - -@example -sh ./install-octave /some/other/directory -@end example - -@noindent -will install Octave in subdirectories of the directory -@file{/some/other/directory}. - -@node Creating a Binary Distribution, , Installing Octave from a Binary Distribution, Binary Distributions -@appendixsubsec Creating a Binary Distribution - -Here is how to build a binary distribution for others to use. If you -want to make a binary distribution for your system available along with -the Octave sources and binaries on @url{ftp.che.wisc.edu}, please follow -this procedure. For directions explaining how to make the binary -available on the ftp site, please contact -@email{bug-octave@@bevo.che.wisc.edu}. - -@itemize @bullet -@item -Unpack the source distribution: - -@example -gunzip -c octave-@value{VERSION}.tar.gz | tar xf - -@end example - -@item -Change your current directory to the top-level directory of the source -distribution: - -@example -cd octave-@value{VERSION} -@end example - -@item -Make the binary distribution: - -@example -make binary-dist -@end example - -This will create a compressed tar file ready for distribution. -It will have a name like -@file{octave-@value{VERSION}-@value{TARGETHOSTTYPE}.tar.gz} -@end itemize diff --git a/doc/interpreter/install.txi b/doc/interpreter/install.txi new file mode 100644 --- /dev/null +++ b/doc/interpreter/install.txi @@ -0,0 +1,566 @@ +@c Copyright (C) 1996, 1997 John W. Eaton +@c This is part of the Octave manual. +@c For copying conditions, see the file gpl.texi. + +@c The text of this file will eventually appear in the file INSTALL +@c in the Octave distribution, as well as in the Octave manual. + +@ifclear INSTALLONLY +@node Installation, Emacs, Trouble, Top +@appendix Installing Octave +@end ifclear + +@ifset INSTALLONLY +@include conf.texi + +This file documents the installation of Octave. + +Octave is free software; you can redistribute it and/or modify it +under the terms of the GNU General Public License as published by the +Free Software Foundation. + +@node Installation, , Installation +@chapter Installing Octave +@end ifset + +@cindex installing Octave + +Here is the procedure for installing Octave from scratch on a Unix +system. For instructions on how to install the binary distributions of +Octave, see @ref{Binary Distributions}. + +@itemize @bullet +@item +Run the shell script @file{configure}. This will determine the features +your system has (or doesn't have) and create a file named +@file{Makefile} from each of the files named @file{Makefile.in}. + +Here is a summary of the configure options that are most frequently used +when building Octave: + +@table @code +@item --prefix=@var{prefix} +Install Octave in subdirectories below @var{prefix}. The default value +of @var{prefix} is @file{/usr/local}. + +@item --srcdir=@var{dir} +Look for Octave sources in the directory @var{dir}. + +@item --with-f2c +Use @code{f2c} even if a Fortran compiler is available. + +@item --with-g77 +Use @code{g77} to compile Fortran code. + +@item --enable-shared +Create shared libraries. If you are planning to use +@code{--enable-lite-kernelel} or the dynamic loading features, you will +probably want to use this option. It will make your @file{.oct} files +much smaller and on some systems it may be necessary to build shared +libraries in order to use dynamically linked functions. + +You may also want to build a shared version of @code{libstdc++}, if your +system doesn't already have one. Note that a patch is needed to build +shared versions of version 2.7.2 of @code{libstdc++} on the HP-PA +architecture. You can find the patch at +@url{ftp://ftp.cygnus.com/pub/g++/libg++-2.7.2-hppa-gcc-fix}. + +@item --enable-dl +Use @code{dlopen} and friends to make Octave capable of dynamically +linking externally compiled functions. This only works on systems that +actually have these functions. If you plan on using this feature, you +should probably also use @code{--enable-shared} to reduce the size of +your @file{.oct} files. + +@item --enable-shl +Use @code{shl_load} and friends to make Octave capable of dynamically +linking externally compiled functions. This only works on systems that +actually have these functions (only HP-UX systems). If you plan on +using this feature, you should probably also use @code{--enable-shared} +to reduce the size of your @file{.oct} files. + +@item --enable-lite-kernel +Compile smaller kernel. This currently requires the dynamic linking +functions @code{dlopen} or @code{shl_load} and friends so that Octave +can load functions at run time that are not loaded at compile time. + +@item --help +Print a summary of the options recognized by the configure script. +@end table + +See the file @file{INSTALL} for more information about the command line +options used by configure. That file also contains instructions for +compiling in a directory other than where the source is located. + +@item +Run make. + +You will need a recent version of GNU Make. Modifying Octave's +makefiles to work with other make programs is probably not worth +your time. We recommend you get and compile GNU Make instead. + +For plotting, you will need to have gnuplot installed on your system. +Gnuplot is a command-driven interactive function plotting program. +Gnuplot is copyrighted, but freely distributable. The `gnu' in gnuplot +is a coincidence---it is not related to the GNU project or the FSF in +any but the most peripheral sense. + +To compile Octave, you will need a recent version of GNU Make. You +will also need @code{g++} 2.7.2 or later. Version 2.8.0 or @code{egcs} +1.0.x should work. Later versions may work, but C++ is still evolving, +so don't be too surprised if you run into some trouble. + +It is no longer necessary to have @code{libg++}, but you do need to have +the GNU implementation of @code{libstdc++}. If you are using @code{g++} +2.7.2, @code{libstdc++} is distributed along with @code{libg++}, but for +later versions, @code{libstdc++} is distributed separately. For +@code{egcs}, @code{libstdc++} is included with the compiler +distribution. + +If you plan to modify the parser you will also need GNU @code{bison} and +@code{flex}. If you modify the documentation, you will need GNU +Texinfo, along with the patch for the @code{makeinfo} program that is +distributed with Octave. + +GNU Make, @code{gcc}, and @code{libstdc++}, @code{gnuplot}, +@code{bison}, @code{flex}, and Texinfo are all available from many +anonymous ftp archives. The primary site is @url{ftp.gnu.org}, but it +is often very busy. A list of sites that mirror the software on +@url{ftp.gnu.org} is available by anonymous ftp from +@url{ftp://ftp.gnu.org/pub/gnu/GNUinfo/FTP}. + +If you don't have a Fortran compiler, or if your Fortran compiler +doesn't work like the traditional Unix f77, you will need to have the +Fortran to C translator @code{f2c}. You can get @code{f2c} from any +number of anonymous ftp archives. The most recent version of @code{f2c} +is always available from @url{netlib.att.com}. + +On an otherwise idle Pentium 133 running Linux, it will take somewhere +between 1-1/2 to 3 hours to compile everything, depending on whether you +are building shared libraries. You will need about 100 megabytes of disk +storage to work with (considerably less if you don't compile with debugging +symbols). To do that, use the command + +@example +make CFLAGS=-O CXXFLAGS=-O LDFLAGS= +@end example + +@noindent +instead of just @samp{make}. + +@item +If you encounter errors while compiling Octave, first check the list of +known problems below to see if there is a workaround or solution for +your problem. If not, +@ifclear INSTALLONLY +see @ref{Trouble}, +@end ifclear +@ifset INSTALLONLY +see the file BUGS +@end ifset +for information about how to report bugs. + +@item +Once you have successfully compiled Octave, run @samp{make install}. + +This will install a copy of octave, its libraries, and its documentation +in the destination directory. As distributed, Octave is installed in +the following directories. In the table below, @var{prefix} defaults to +@file{/usr/local}, @var{version} stands for the current version number +of the interpreter, and @var{arch} is the type of computer on which +Octave is installed (for example, @samp{i586-unknown-gnu}). + +@table @file +@item @var{prefix}/bin +Octave and other binaries that people will want to run directly. + +@item @var{prefix}/lib +Libraries like libcruft.a and liboctave.a. + +@item @var{prefix}/share +Architecture-independent data files. + +@item @var{prefix}/include/octave +Include files distributed with Octave. + +@item @var{prefix}/man/man1 +Unix-style man pages describing Octave. + +@item @var{prefix}/info +Info files describing Octave. + +@item @var{prefix}/share/octave/@var{version}/m +Function files distributed with Octave. This includes the Octave +version, so that multiple versions of Octave may be installed at the +same time. + +@item @var{prefix}/lib/octave/@var{version}/exec/@var{arch} +Executables to be run by Octave rather than the user. + +@item @var{prefix}/lib/octave/@var{version}/oct/@var{arch} +Object files that will be dynamically loaded. + +@item @var{prefix}/share/octave/@var{version}/imagelib +Image files that are distributed with Octave. +@end table +@end itemize + +@menu +* Installation Problems:: +* Binary Distributions:: +@end menu + +@node Installation Problems, Binary Distributions, Installation, Installation +@appendixsec Installation Problems + +This section contains a list of problems (and some apparent problems +that don't really mean anything is wrong) that may show up during +installation of Octave. + +@itemize @bullet +@item +On some SCO systems, @code{info} fails to compile if +@code{HAVE_TERMIOS_H} is defined int @file{config.h}. Simply removing +the definition from @file{info/config.h} should allow it to compile. + +@item +If @code{configure} finds @code{dlopen}, @code{dlsym}, @code{dlclose}, +and @code{dlerror}, but not the header file @file{dlfcn.h}, you need to +find the source for the header file and install it in the directory +@file{usr/include}. This is reportedly a problem with Slackware 3.1. +For Linux/GNU systems, the source for @file{dlfcn.h} is in the +@code{ldso} package. + +@item +Building @file{.oct} files doesn't work. + +You should probably have a shared version of @code{libstdc++}. A patch +is needed to build shared versions of version 2.7.2 of @code{libstdc++} +on the HP-PA architecture. You can find the patch at +@url{ftp://ftp.cygnus.com/pub/g++/libg++-2.7.2-hppa-gcc-fix}. + +@item +On FreeBSD systems Octave may hang while initializing some internal +constants. The fix appears to be to use + +@example +options GPL_MATH_EMULATE +@end example + +@noindent +rather than + +@example +options MATH_EMULATE +@end example + +@noindent +in the kernel configuration files (typically found in the directory +@file{/sys/i386/conf}. After making this change, you'll need to rebuild +the kernel, install it, and reboot. + +@item +If you encounter errors like + +@smallexample +@group +passing `void (*)()' as argument 2 of + `octave_set_signal_handler(int, void (*)(int))' +@end group +@end smallexample + +@noindent +or + +@smallexample +warning: ANSI C++ prohibits conversion from `(int)' to `(...)' +@end smallexample + +@noindent +while compiling @file{sighandlers.cc}, you may need to edit some files +in the @code{gcc} include subdirectory to add proper prototypes for functions +there. For example, Ultrix 4.2 needs proper declarations for the +@code{signal} function and the @code{SIG_IGN} macro in the file +@file{signal.h}. + +On some systems the @code{SIG_IGN} macro is defined to be something like +this: + +@example +#define SIG_IGN (void (*)())1 +@end example + +@noindent +when it should really be something like: + +@example +#define SIG_IGN (void (*)(int))1 +@end example + +@noindent +to match the prototype declaration for the @code{signal} function. This +change should also be made for the @code{SIG_DFL} and @code{SIG_ERR} +symbols. It may be necessary to change the definitions in +@file{sys/signal.h} as well. + +The @code{gcc} @code{fixincludes} and @code{fixproto} scripts should +probably fix these problems when @code{gcc} installs its modified set of +header files, but I don't think that's been done yet. + +@strong{You should not change the files in @file{/usr/include}}. You +can find the @code{gcc} include directory tree by running the command + +@example +gcc -print-libgcc-file-name +@end example + +@noindent +The directory of @code{gcc} include files normally begins in the same directory +that contains the file @file{libgcc.a}. + +@item +Some of the Fortran subroutines may fail to compile with older versions +of the Sun Fortran compiler. If you get errors like + +@smallexample +zgemm.f: + zgemm: +warning: unexpected parent of complex expression subtree +zgemm.f, line 245: warning: unexpected parent of complex + expression subtree +warning: unexpected parent of complex expression subtree +zgemm.f, line 304: warning: unexpected parent of complex + expression subtree +warning: unexpected parent of complex expression subtree +zgemm.f, line 327: warning: unexpected parent of complex + expression subtree +pcc_binval: missing IR_CONV in complex op +make[2]: *** [zgemm.o] Error 1 +@end smallexample + +@noindent +when compiling the Fortran subroutines in the @file{libcruft} +subdirectory, you should either upgrade your compiler or try compiling +with optimization turned off. + +@item +On NeXT systems, if you get errors like this: + +@example +/usr/tmp/cc007458.s:unknown:Undefined local symbol LBB7656 +/usr/tmp/cc007458.s:unknown:Undefined local symbol LBE7656 +@end example + +@noindent +when compiling @file{Array.cc} and @file{Matrix.cc}, try recompiling +these files without @code{-g}. + +@item +Some people have reported that calls to shell_cmd and the pager do not +work on SunOS systems. This is apparently due to having +@code{G_HAVE_SYS_WAIT} defined to be 0 instead of 1 when compiling +@code{libg++}. + +@item +On NeXT systems, linking to @file{libsys_s.a} may fail to resolve the +following functions + +@example +_tcgetattr +_tcsetattr +_tcflow +@end example + +@noindent +which are part of @file{libposix.a}. Unfortunately, linking Octave with +@code{-posix} results in the following undefined symbols. + +@example +.destructors_used +.constructors_used +_objc_msgSend +_NXGetDefaultValue +_NXRegisterDefaults +.objc_class_name_NXStringTable +.objc_class_name_NXBundle +@end example + +One kluge around this problem is to extract @file{termios.o} from +@file{libposix.a}, put it in Octave's @file{src} directory, and add it +to the list of files to link together in the makefile. Suggestions for +better ways to solve this problem are welcome! + +@item +If Octave crashes immediately with a floating point exception, it is +likely that it is failing to initialize the IEEE floating point values +for infinity and NaN. + +If your system actually does support IEEE arithmetic, you should be able +to fix this problem by modifying the function @code{octave_ieee_init} in +the file @file{lo-ieee.cc} to correctly initialize Octave's internal +infinity and NaN variables. + +If your system does not support IEEE arithmetic but Octave's configure +script incorrectly determined that it does, you can work around the +problem by editing the file @file{config.h} to not define +@code{HAVE_ISINF}, @code{HAVE_FINITE}, and @code{HAVE_ISNAN}. + +In any case, please report this as a bug since it might be possible to +modify Octave's configuration script to automatically determine the +proper thing to do. + +@item +After installing the binary distribution of Octave in an alternate +directory, the Emacs command @code{run-octave} doesn't work. Emacs +hangs in @code{accept-process-output} in @code{inferior-octave-startup}. + +This seems to be a problem with executing a shell script using the +comint package. You can avoid the problem by changing the way Octave is +installed to eliminate the need for the shell script. You can either +compile and install Octave using the source distribution, reinstall the +binary distribution in the default directory, or copy the commands in +the octave shell script wrapper to your shell startup files (and the +shell startup files for anyone else who is using Octave) and then +rename the file @file{octave.bin} to be @file{octave}. +@end itemize + +@node Binary Distributions, , Installation Problems, Installation +@appendixsec Binary Distributions + +Although Octave is not very difficult to build from its sources, it is a +relatively large program that does require a significant amount of time +and disk space to compile and install. Because of this, many people +want to be able to obtain binary distributions so they can start using +Octave immediately, without having to bother with the details of +compiling it first. This is understandable, so I try to maintain a +current collection of binary distributions at +@url{ftp://ftp.che.wisc.edu/pub/octave/BINARIES}. + +Please understand, however, that there is only a limited amount of time +available to devote to making binaries, so binaries may not be +immediately available for some platforms. (Please contact +@email{bug-octave@@bevo.che.wisc.edu} if you are interested in helping +make a binary distribution available for your system.) + +@menu +* Installing Octave from a Binary Distribution:: +* Creating a Binary Distribution:: +@end menu + +@node Installing Octave from a Binary Distribution, Creating a Binary Distribution, Binary Distributions, Binary Distributions +@appendixsubsec Installing Octave from a Binary Distribution + +To install Octave from a binary distribution, execute the command + +@example +sh ./install-octave +@end example + +@noindent +in the top level directory of the distribution. + +Binary distributions are normally compiled assuming that Octave will be +installed in the following subdirectories of @file{/usr/local}. + +@table @file +@item bin +Octave and other binaries that people will want to run directly. + +@item lib +Shared libraries that Octave needs in order to run. These files are +not included if you are installing a statically linked version of +Octave. + +@item man/man1 +Unix-style man pages describing Octave. + +@item info +Info files describing Octave. + +@item share/octave/@var{version}/m +Function files distributed with Octave. This includes the Octave +version, so that multiple versions of Octave may be installed at the +same time. + +@item libexec/octave/@var{version}/exec/@var{arch} +Executables to be run by Octave rather than the user. + +@item libexec/octave/@var{version}/oct/@var{arch} +Object files that will be dynamically loaded. + +@item share/octave/@var{version}/imagelib +Image files that are distributed with Octave. +@end table + +@noindent +where @var{version} stands for the current version number of the +interpreter, and @var{arch} is the type of computer on which Octave +is installed (for example, @samp{@value{TARGETHOSTTYPE}}). + +If these directories don't exist, the script @code{install-octave} will +create them for you. The installation script also creates the following +subdirectories of @file{/usr/local} that are intended for locally +installed functions: + +@table @file +@item share/octave/site/m +Locally installed M-files. + +@item libexec/octave/site/exec/@var{arch} +Locally installed binaries intended to be run by Octave rather than by +the user. + +@item libexec/octave/site/octave/@var{arch} +Local object files that will be dynamically linked. +@end table + +If it is not possible for you to install Octave in @file{/usr/local}, or +if you would prefer to install it in a different directory, you can +specify the name of the top level directory as an argument to the +@file{install-octave} script. For example: + +@example +sh ./install-octave /some/other/directory +@end example + +@noindent +will install Octave in subdirectories of the directory +@file{/some/other/directory}. + +@node Creating a Binary Distribution, , Installing Octave from a Binary Distribution, Binary Distributions +@appendixsubsec Creating a Binary Distribution + +Here is how to build a binary distribution for others to use. If you +want to make a binary distribution for your system available along with +the Octave sources and binaries on @url{ftp.che.wisc.edu}, please follow +this procedure. For directions explaining how to make the binary +available on the ftp site, please contact +@email{bug-octave@@bevo.che.wisc.edu}. + +@itemize @bullet +@item +Unpack the source distribution: + +@example +gunzip -c octave-@value{VERSION}.tar.gz | tar xf - +@end example + +@item +Change your current directory to the top-level directory of the source +distribution: + +@example +cd octave-@value{VERSION} +@end example + +@item +Make the binary distribution: + +@example +make binary-dist +@end example + +This will create a compressed tar file ready for distribution. +It will have a name like +@file{octave-@value{VERSION}-@value{TARGETHOSTTYPE}.tar.gz} +@end itemize diff --git a/doc/interpreter/intro.texi b/doc/interpreter/intro.texi deleted file mode 100644 --- a/doc/interpreter/intro.texi +++ /dev/null @@ -1,599 +0,0 @@ -@c Copyright (C) 1996, 1997 John W. Eaton -@c This is part of the Octave manual. -@c For copying conditions, see the file gpl.texi. - -@node Introduction, Getting Started, Preface, Top -@chapter A Brief Introduction to Octave -@cindex introduction - -This manual documents how to run, install and port GNU Octave, and how -to report bugs. - -GNU Octave is a high-level language, primarily intended for numerical -computations. It provides a convenient command line interface for -solving linear and nonlinear problems numerically, and for performing -other numerical experiments. It may also be used as a batch-oriented -language. - -GNU Octave is also freely redistributable software. You may -redistribute it and/or modify it under the terms of the GNU General -Public License as published by the Free Software Foundation. The GPL is -included in this manual in @ref{Copying}. - -This document corresponds to Octave version @value{VERSION}. - -@c XXX FIXME XXX -- add explanation about how and why Octave was written. -@c -@c XXX FIXME XXX -- add a sentence or two explaining that we could -@c always use more funding. - -@menu -* Running Octave:: -* Simple Examples:: -* Conventions:: -@end menu - -@node Running Octave, Simple Examples, Introduction, Introduction -@section Running Octave - -On most systems, the way to invoke Octave is with the shell command -@samp{octave}. Octave displays an initial message and then a prompt -indicating it is ready to accept input. You can begin typing Octave -commands immediately afterward. - -If you get into trouble, you can usually interrupt Octave by typing -@kbd{Control-C} (usually written @kbd{C-c} for short). @kbd{C-c} gets -its name from the fact that you type it by holding down @key{CTRL} and -then pressing @key{c}. Doing this will normally return you to Octave's -prompt. - -@cindex exiting octave -@cindex quitting octave -To exit Octave, type @kbd{quit}, or @kbd{exit} at the Octave prompt. - -On systems that support job control, you can suspend Octave by sending -it a @code{SIGTSTP} signal, usually by typing @kbd{C-z}. - -@node Simple Examples, Conventions, Running Octave, Introduction -@section Simple Examples - -The following chapters describe all of Octave's features in detail, but -before doing that, it might be helpful to give a sampling of some of its -capabilities. - -If you are new to Octave, I recommend that you try these examples to -begin learning Octave by using it. Lines marked with @samp{octave:13>} -are lines you type, ending each with a carriage return. Octave will -respond with an answer, or by displaying a graph. - -@unnumberedsubsec Creating a Matrix - -To create a new matrix and store it in a variable so that it you can -refer to it later, type the command - -@example -octave:1> a = [ 1, 1, 2; 3, 5, 8; 13, 21, 34 ] -@end example - -@noindent -Octave will respond by printing the matrix in neatly aligned columns. -Ending a command with a semicolon tells Octave to not print the result -of a command. For example - -@example -octave:2> b = rand (3, 2); -@end example - -@noindent -will create a 3 row, 2 column matrix with each element set to a random -value between zero and one. - -To display the value of any variable, simply type the name of the -variable. For example, to display the value stored in the matrix -@code{b}, type the command - -@example -octave:3> b -@end example - -@unnumberedsubsec Matrix Arithmetic - -Octave has a convenient operator notation for performing matrix -arithmetic. For example, to multiply the matrix @code{a} by a scalar -value, type the command - -@example -octave:4> 2 * a -@end example - -To multiply the two matrices @code{a} and @code{b}, type the command - -@example -octave:5> a * b -@end example - -To form the matrix product -@iftex -@tex -$@code{a}^T@code{a}$, -@end tex -@end iftex -@ifinfo -@code{transpose (a) * a}, -@end ifinfo -type the command - -@example -octave:6> a' * a -@end example - -@unnumberedsubsec Solving Linear Equations - -To solve the set of linear equations @code{a@var{x} = b}, -use the left division operator, @samp{\}: - -@example -octave:7> a \ b -@end example - -@noindent -This is conceptually equivalent to -@iftex -@tex -$@code{a}^{-1}@code{b}$, -@end tex -@end iftex -@ifinfo -@code{inv (a) * b}, -@end ifinfo -but avoids computing the inverse of a matrix directly. - -If the coefficient matrix is singular, Octave will print a warning -message and compute a minimum norm solution. - -@unnumberedsubsec Integrating Differential Equations - -Octave has built-in functions for solving nonlinear differential -equations of the form -@iftex -@tex -$$ - {dx \over dt} = f(x,t), \qquad x(t=t_0) = x_0 -$$ -@end tex -@end iftex -@ifinfo - -@example -@group -dx --- = f (x, t) -dt -@end group -@end example - -@noindent -with the initial condition - -@example -x(t = t0) = x0 -@end example -@end ifinfo - -@noindent -For Octave to integrate equations of this form, you must first provide a -definition of the function -@iftex -@tex -$f (x, t)$. -@end tex -@end iftex -@ifinfo -@code{f(x,t)}. -@end ifinfo -This is straightforward, and may be accomplished by entering the -function body directly on the command line. For example, the following -commands define the right hand side function for an interesting pair of -nonlinear differential equations. Note that while you are entering a -function, Octave responds with a different prompt, to indicate that it -is waiting for you to complete your input. - -@example -@group -octave:8> function xdot = f (x, t) -> -> r = 0.25; -> k = 1.4; -> a = 1.5; -> b = 0.16; -> c = 0.9; -> d = 0.8; -> -> xdot(1) = r*x(1)*(1 - x(1)/k) - a*x(1)*x(2)/(1 + b*x(1)); -> xdot(2) = c*a*x(1)*x(2)/(1 + b*x(1)) - d*x(2); -> -> endfunction -@end group -@end example - -@noindent -Given the initial condition - -@example -x0 = [1; 2]; -@end example - -@noindent -and the set of output times as a column vector (note that the first -output time corresponds to the initial condition given above) - -@example -t = linspace (0, 50, 200)'; -@end example - -@noindent -it is easy to integrate the set of differential equations: - -@example -x = lsode ("f", x0, t); -@end example - -@noindent -The function @code{lsode} uses the Livermore Solver for Ordinary -Differential Equations, described in A. C. Hindmarsh, @cite{ODEPACK, a -Systematized Collection of ODE Solvers}, in: Scientific Computing, R. S. -Stepleman et al. (Eds.), North-Holland, Amsterdam, 1983, pages 55--64. - -@unnumberedsubsec Producing Graphical Output - -To display the solution of the previous example graphically, use the -command - -@example -plot (t, x) -@end example - -If you are using the X Window System, Octave will automatically create -a separate window to display the plot. If you are using a terminal that -supports some other graphics commands, you will need to tell Octave what -kind of terminal you have. Type the command - -@example -gset term -@end example - -@noindent -to see a list of the supported terminal types. Octave uses -@code{gnuplot} to display graphics, and can display graphics on any -terminal that is supported by @code{gnuplot}. - -To capture the output of the plot command in a file rather than sending -the output directly to your terminal, you can use a set of commands like -this - -@example -@group -gset term postscript -gset output "foo.ps" -replot -@end group -@end example - -@noindent -This will work for other types of output devices as well. Octave's -@code{gset} command is really just piped to the @code{gnuplot} -subprocess, so that once you have a plot on the screen that you like, -you should be able to do something like this to create an output file -suitable for your graphics printer. - -Or, you can eliminate the intermediate file by using commands like this - -@example -@group -gset term postscript -gset output "|lpr -Pname_of_your_graphics_printer" -replot -@end group -@end example - -@unnumberedsubsec Editing What You Have Typed - -At the Octave prompt, you can recall, edit, and reissue previous -commands using Emacs- or vi-style editing commands. The default -keybindings use Emacs-style commands. For example, to recall the -previous command, type @kbd{Control-p} (usually written @kbd{C-p} for -short). @kbd{C-p} gets its name from the fact that you type it by -holding down @key{CTRL} and then pressing @key{p}. Doing this will -normally bring back the previous line of input. @kbd{C-n} will bring up -the next line of input, @kbd{C-b} will move the cursor backward on the -line, @kbd{C-f} will move the cursor forward on the line, etc. - -A complete description of the command line editing capability is given -in this manual in @ref{Command Line Editing}. - -@unnumberedsubsec Getting Help - -Octave has an extensive help facility. The same documentation that is -available in printed form is also available from the Octave prompt, -because both forms of the documentation are created from the same input -file. - -In order to get good help you first need to know the name of the command -that you want to use. This name of the function may not always be -obvious, but a good place to start is to just type @code{help}. -This will show you all the operators, reserved words, functions, -built-in variables, and function files. You can then get more -help on anything that is listed by simply including the name as an -argument to help. For example, - -@example -help plot -@end example - -@noindent -will display the help text for the @code{plot} function. - -Octave sends output that is too long to fit on one screen through a -pager like @code{less} or @code{more}. Type a @key{RET} to advance one -line, a @key{SPC} to advance one page, and @key{q} to exit the pager. - -The part of Octave's help facility that allows you to read the complete -text of the printed manual from within Octave normally uses a separate -program called Info. When you invoke Info you will be put into a menu -driven program that contains the entire Octave manual. Help for using -Info is provided in this manual in @ref{Getting Help}. - -@node Conventions, , Simple Examples, Introduction -@section Conventions - -This section explains the notational conventions that are used in this -manual. You may want to skip this section and refer back to it later. - -@menu -* Fonts:: -* Evaluation Notation:: -* Printing Notation:: -* Error Messages:: -* Format of Descriptions:: -@end menu - -@node Fonts, Evaluation Notation, Conventions, Conventions -@subsection Fonts -@cindex fonts - -Examples of Octave code appear in this font or form: @code{svd (a)}. -Names that represent arguments or metasyntactic variables appear -in this font or form: @var{first-number}. Commands that you type at the -shell prompt sometimes appear in this font or form: -@samp{octave --no-init-file}. Commands that you type at the Octave -prompt sometimes appear in this font or form: @kbd{foo --bar --baz}. -Specific keys on your keyboard appear in this font or form: @key{ANY}. -@cindex any key - -@node Evaluation Notation, Printing Notation, Fonts, Conventions -@subsection Evaluation Notation -@cindex evaluation notation -@cindex documentation notation - -In the examples in this manual, results from expressions that you -evaluate are indicated with @samp{@result{}}. For example, - -@example -@group -sqrt (2) - @result{} 1.4142 -@end group -@end example - -@noindent -You can read this as ``@code{sqrt (2)} evaluates to 1.4142''. - -In some cases, matrix values that are returned by expressions are -displayed like this - -@example -@group -[1, 2; 3, 4] == [1, 3; 2, 4] - @result{} [ 1, 0; 0, 1 ] -@end group -@end example - -@noindent -and in other cases, they are displayed like this - -@example -@group -eye (3) - @result{} 1 0 0 - 0 1 0 - 0 0 1 -@end group -@end example - -@noindent -in order to clearly show the structure of the result. - -Sometimes to help describe one expression, another expression is -shown that produces identical results. The exact equivalence of -expressions is indicated with @samp{@equiv{}}. For example, - -@example -@group -rot90 ([1, 2; 3, 4], -1) -@equiv{} -rot90 ([1, 2; 3, 4], 3) -@equiv{} -rot90 ([1, 2; 3, 4], 7) -@end group -@end example - -@node Printing Notation, Error Messages, Evaluation Notation, Conventions -@subsection Printing Notation -@cindex printing notation - -Many of the examples in this manual print text when they are -evaluated. Examples in this manual indicate printed text with -@samp{@print{}}. The value that is returned by evaluating the -expression (here @code{1}) is displayed with @samp{@result{}} and -follows on a separate line. - -@example -@group -printf ("foo %s\n", "bar") - @print{} foo bar - @result{} 1 -@end group -@end example - -@node Error Messages, Format of Descriptions, Printing Notation, Conventions -@subsection Error Messages -@cindex error message notation - -Some examples signal errors. This normally displays an error message -on your terminal. Error messages are shown on a line starting with -@code{error:}. - -@example -@group -struct_elements ([1, 2; 3, 4]) -error: struct_elements: wrong type argument `matrix' -@end group -@end example - -@node Format of Descriptions, , Error Messages, Conventions -@subsection Format of Descriptions -@cindex description format - -Functions, commands, and variables are described in this manual in a -uniform format. The first line of a description contains the name of -the item followed by its arguments, if any. -@ifinfo -The category---function, variable, or whatever---appears at the -beginning of the line. -@end ifinfo -@iftex -The category---function, variable, or whatever---is printed next to the -right margin. -@end iftex -The description follows on succeeding lines, sometimes with examples. - -@menu -* A Sample Function Description:: -* A Sample Command Description:: -* A Sample Variable Description:: -@end menu - -@node A Sample Function Description, A Sample Command Description, Format of Descriptions, Format of Descriptions -@subsubsection A Sample Function Description -@cindex function descriptions - -In a function description, the name of the function being described -appears first. It is followed on the same line by a list of parameters. -The names used for the parameters are also used in the body of the -description. - -Here is a description of an imaginary function @code{foo}: - -@deftypefn {Function} {} foo (@var{x}, @var{y}, @dots{}) -The function @code{foo} subtracts @var{x} from @var{y}, then adds the -remaining arguments to the result. If @var{y} is not supplied, then the -number 19 is used by default. - -@example -@group -foo (1, [3, 5], 3, 9) - @result{} [ 14, 16 ] -foo (5) - @result{} 14 -@end group -@end example - -More generally, - -@example -@group -foo (@var{w}, @var{x}, @var{y}, @dots{}) -@equiv{} -@var{x} - @var{w} + @var{y} + @dots{} -@end group -@end example -@end deftypefn - -Any parameter whose name contains the name of a type (e.g., -@var{integer}, @var{integer1} or @var{matrix}) is expected to be of that -type. Parameters named @var{object} may be of any type. Parameters -with other sorts of names (e.g., @var{new_file}) are discussed -specifically in the description of the function. In some sections, -features common to parameters of several functions are described at the -beginning. - -Functions in Octave may be defined in several different ways. The -catagory name for functions may include another name that indicates the -way that the function is defined. These additional tags include - -@table @asis -@item Built-in Function -@cindex built-in function -The function described is written in a language like C++, C, or Fortran, -and is part of the compiled Octave binary. - -@item Loadable Function -@cindex loadable function -The function described is written in a language like C++, C, or Fortran. -On systems that support dynamic linking of user-supplied functions, it -may be automatically linked while Octave is running, but only if it is -needed. @xref{Dynamically Linked Functions}. - -@item Function File -@cindex function file -The function described is defined using Octave commands stored in a text -file. @xref{Function Files}. - -@item Mapping Function -@cindex mapping function -The function described works element-by-element for matrix and vector -arguments. -@end table - -@node A Sample Command Description, A Sample Variable Description, A Sample Function Description, Format of Descriptions -@subsubsection A Sample Command Description -@cindex command descriptions - -Command descriptions have a format similar to function descriptions, -except that the word `Function' is replaced by `Command. Commands are -functions that may called without surrounding their arguments in -parentheses. For example, here is the description for Octave's -@code{cd} command: - -@deffn {Command} cd dir -@deffnx {Command} chdir dir -Change the current working directory to @var{dir}. For example, -@kbd{cd ~/octave} changes the current working directory to -@file{~/octave}. If the directory does not exist, an error message is -printed and the working directory is not changed. -@end deffn - -@node A Sample Variable Description, , A Sample Command Description, Format of Descriptions -@subsubsection A Sample Variable Description -@cindex variable descriptions - -A @dfn{variable} is a name that can hold a value. Although any variable -can be set by the user, @dfn{built-in variables} typically exist -specifically so that users can change them to alter the way Octave -behaves (built-in variables are also sometimes called @dfn{user -options}). Ordinary variables and built-in variables are described -using a format like that for functions except that there are no -arguments. - -Here is a description of the imaginary variable -@code{do_what_i_mean_not_what_i_say}. - -@defvr {Built-in Variable} do_what_i_mean_not_what_i_say -If the value of this variable is nonzero, Octave will do what you -actually wanted, even if you have typed a completely different and -meaningless list of commands. -@end defvr - -Other variable descriptions have the same format, but `Built-in -Variable' is replaced by `Variable', for ordinary variables, or -`Constant' for symbolic constants whose values cannot be changed. diff --git a/doc/interpreter/intro.txi b/doc/interpreter/intro.txi new file mode 100644 --- /dev/null +++ b/doc/interpreter/intro.txi @@ -0,0 +1,599 @@ +@c Copyright (C) 1996, 1997 John W. Eaton +@c This is part of the Octave manual. +@c For copying conditions, see the file gpl.texi. + +@node Introduction, Getting Started, Preface, Top +@chapter A Brief Introduction to Octave +@cindex introduction + +This manual documents how to run, install and port GNU Octave, and how +to report bugs. + +GNU Octave is a high-level language, primarily intended for numerical +computations. It provides a convenient command line interface for +solving linear and nonlinear problems numerically, and for performing +other numerical experiments. It may also be used as a batch-oriented +language. + +GNU Octave is also freely redistributable software. You may +redistribute it and/or modify it under the terms of the GNU General +Public License as published by the Free Software Foundation. The GPL is +included in this manual in @ref{Copying}. + +This document corresponds to Octave version @value{VERSION}. + +@c XXX FIXME XXX -- add explanation about how and why Octave was written. +@c +@c XXX FIXME XXX -- add a sentence or two explaining that we could +@c always use more funding. + +@menu +* Running Octave:: +* Simple Examples:: +* Conventions:: +@end menu + +@node Running Octave, Simple Examples, Introduction, Introduction +@section Running Octave + +On most systems, the way to invoke Octave is with the shell command +@samp{octave}. Octave displays an initial message and then a prompt +indicating it is ready to accept input. You can begin typing Octave +commands immediately afterward. + +If you get into trouble, you can usually interrupt Octave by typing +@kbd{Control-C} (usually written @kbd{C-c} for short). @kbd{C-c} gets +its name from the fact that you type it by holding down @key{CTRL} and +then pressing @key{c}. Doing this will normally return you to Octave's +prompt. + +@cindex exiting octave +@cindex quitting octave +To exit Octave, type @kbd{quit}, or @kbd{exit} at the Octave prompt. + +On systems that support job control, you can suspend Octave by sending +it a @code{SIGTSTP} signal, usually by typing @kbd{C-z}. + +@node Simple Examples, Conventions, Running Octave, Introduction +@section Simple Examples + +The following chapters describe all of Octave's features in detail, but +before doing that, it might be helpful to give a sampling of some of its +capabilities. + +If you are new to Octave, I recommend that you try these examples to +begin learning Octave by using it. Lines marked with @samp{octave:13>} +are lines you type, ending each with a carriage return. Octave will +respond with an answer, or by displaying a graph. + +@unnumberedsubsec Creating a Matrix + +To create a new matrix and store it in a variable so that it you can +refer to it later, type the command + +@example +octave:1> a = [ 1, 1, 2; 3, 5, 8; 13, 21, 34 ] +@end example + +@noindent +Octave will respond by printing the matrix in neatly aligned columns. +Ending a command with a semicolon tells Octave to not print the result +of a command. For example + +@example +octave:2> b = rand (3, 2); +@end example + +@noindent +will create a 3 row, 2 column matrix with each element set to a random +value between zero and one. + +To display the value of any variable, simply type the name of the +variable. For example, to display the value stored in the matrix +@code{b}, type the command + +@example +octave:3> b +@end example + +@unnumberedsubsec Matrix Arithmetic + +Octave has a convenient operator notation for performing matrix +arithmetic. For example, to multiply the matrix @code{a} by a scalar +value, type the command + +@example +octave:4> 2 * a +@end example + +To multiply the two matrices @code{a} and @code{b}, type the command + +@example +octave:5> a * b +@end example + +To form the matrix product +@iftex +@tex +$@code{a}^T@code{a}$, +@end tex +@end iftex +@ifinfo +@code{transpose (a) * a}, +@end ifinfo +type the command + +@example +octave:6> a' * a +@end example + +@unnumberedsubsec Solving Linear Equations + +To solve the set of linear equations @code{a@var{x} = b}, +use the left division operator, @samp{\}: + +@example +octave:7> a \ b +@end example + +@noindent +This is conceptually equivalent to +@iftex +@tex +$@code{a}^{-1}@code{b}$, +@end tex +@end iftex +@ifinfo +@code{inv (a) * b}, +@end ifinfo +but avoids computing the inverse of a matrix directly. + +If the coefficient matrix is singular, Octave will print a warning +message and compute a minimum norm solution. + +@unnumberedsubsec Integrating Differential Equations + +Octave has built-in functions for solving nonlinear differential +equations of the form +@iftex +@tex +$$ + {dx \over dt} = f(x,t), \qquad x(t=t_0) = x_0 +$$ +@end tex +@end iftex +@ifinfo + +@example +@group +dx +-- = f (x, t) +dt +@end group +@end example + +@noindent +with the initial condition + +@example +x(t = t0) = x0 +@end example +@end ifinfo + +@noindent +For Octave to integrate equations of this form, you must first provide a +definition of the function +@iftex +@tex +$f (x, t)$. +@end tex +@end iftex +@ifinfo +@code{f(x,t)}. +@end ifinfo +This is straightforward, and may be accomplished by entering the +function body directly on the command line. For example, the following +commands define the right hand side function for an interesting pair of +nonlinear differential equations. Note that while you are entering a +function, Octave responds with a different prompt, to indicate that it +is waiting for you to complete your input. + +@example +@group +octave:8> function xdot = f (x, t) +> +> r = 0.25; +> k = 1.4; +> a = 1.5; +> b = 0.16; +> c = 0.9; +> d = 0.8; +> +> xdot(1) = r*x(1)*(1 - x(1)/k) - a*x(1)*x(2)/(1 + b*x(1)); +> xdot(2) = c*a*x(1)*x(2)/(1 + b*x(1)) - d*x(2); +> +> endfunction +@end group +@end example + +@noindent +Given the initial condition + +@example +x0 = [1; 2]; +@end example + +@noindent +and the set of output times as a column vector (note that the first +output time corresponds to the initial condition given above) + +@example +t = linspace (0, 50, 200)'; +@end example + +@noindent +it is easy to integrate the set of differential equations: + +@example +x = lsode ("f", x0, t); +@end example + +@noindent +The function @code{lsode} uses the Livermore Solver for Ordinary +Differential Equations, described in A. C. Hindmarsh, @cite{ODEPACK, a +Systematized Collection of ODE Solvers}, in: Scientific Computing, R. S. +Stepleman et al. (Eds.), North-Holland, Amsterdam, 1983, pages 55--64. + +@unnumberedsubsec Producing Graphical Output + +To display the solution of the previous example graphically, use the +command + +@example +plot (t, x) +@end example + +If you are using the X Window System, Octave will automatically create +a separate window to display the plot. If you are using a terminal that +supports some other graphics commands, you will need to tell Octave what +kind of terminal you have. Type the command + +@example +gset term +@end example + +@noindent +to see a list of the supported terminal types. Octave uses +@code{gnuplot} to display graphics, and can display graphics on any +terminal that is supported by @code{gnuplot}. + +To capture the output of the plot command in a file rather than sending +the output directly to your terminal, you can use a set of commands like +this + +@example +@group +gset term postscript +gset output "foo.ps" +replot +@end group +@end example + +@noindent +This will work for other types of output devices as well. Octave's +@code{gset} command is really just piped to the @code{gnuplot} +subprocess, so that once you have a plot on the screen that you like, +you should be able to do something like this to create an output file +suitable for your graphics printer. + +Or, you can eliminate the intermediate file by using commands like this + +@example +@group +gset term postscript +gset output "|lpr -Pname_of_your_graphics_printer" +replot +@end group +@end example + +@unnumberedsubsec Editing What You Have Typed + +At the Octave prompt, you can recall, edit, and reissue previous +commands using Emacs- or vi-style editing commands. The default +keybindings use Emacs-style commands. For example, to recall the +previous command, type @kbd{Control-p} (usually written @kbd{C-p} for +short). @kbd{C-p} gets its name from the fact that you type it by +holding down @key{CTRL} and then pressing @key{p}. Doing this will +normally bring back the previous line of input. @kbd{C-n} will bring up +the next line of input, @kbd{C-b} will move the cursor backward on the +line, @kbd{C-f} will move the cursor forward on the line, etc. + +A complete description of the command line editing capability is given +in this manual in @ref{Command Line Editing}. + +@unnumberedsubsec Getting Help + +Octave has an extensive help facility. The same documentation that is +available in printed form is also available from the Octave prompt, +because both forms of the documentation are created from the same input +file. + +In order to get good help you first need to know the name of the command +that you want to use. This name of the function may not always be +obvious, but a good place to start is to just type @code{help}. +This will show you all the operators, reserved words, functions, +built-in variables, and function files. You can then get more +help on anything that is listed by simply including the name as an +argument to help. For example, + +@example +help plot +@end example + +@noindent +will display the help text for the @code{plot} function. + +Octave sends output that is too long to fit on one screen through a +pager like @code{less} or @code{more}. Type a @key{RET} to advance one +line, a @key{SPC} to advance one page, and @key{q} to exit the pager. + +The part of Octave's help facility that allows you to read the complete +text of the printed manual from within Octave normally uses a separate +program called Info. When you invoke Info you will be put into a menu +driven program that contains the entire Octave manual. Help for using +Info is provided in this manual in @ref{Getting Help}. + +@node Conventions, , Simple Examples, Introduction +@section Conventions + +This section explains the notational conventions that are used in this +manual. You may want to skip this section and refer back to it later. + +@menu +* Fonts:: +* Evaluation Notation:: +* Printing Notation:: +* Error Messages:: +* Format of Descriptions:: +@end menu + +@node Fonts, Evaluation Notation, Conventions, Conventions +@subsection Fonts +@cindex fonts + +Examples of Octave code appear in this font or form: @code{svd (a)}. +Names that represent arguments or metasyntactic variables appear +in this font or form: @var{first-number}. Commands that you type at the +shell prompt sometimes appear in this font or form: +@samp{octave --no-init-file}. Commands that you type at the Octave +prompt sometimes appear in this font or form: @kbd{foo --bar --baz}. +Specific keys on your keyboard appear in this font or form: @key{ANY}. +@cindex any key + +@node Evaluation Notation, Printing Notation, Fonts, Conventions +@subsection Evaluation Notation +@cindex evaluation notation +@cindex documentation notation + +In the examples in this manual, results from expressions that you +evaluate are indicated with @samp{@result{}}. For example, + +@example +@group +sqrt (2) + @result{} 1.4142 +@end group +@end example + +@noindent +You can read this as ``@code{sqrt (2)} evaluates to 1.4142''. + +In some cases, matrix values that are returned by expressions are +displayed like this + +@example +@group +[1, 2; 3, 4] == [1, 3; 2, 4] + @result{} [ 1, 0; 0, 1 ] +@end group +@end example + +@noindent +and in other cases, they are displayed like this + +@example +@group +eye (3) + @result{} 1 0 0 + 0 1 0 + 0 0 1 +@end group +@end example + +@noindent +in order to clearly show the structure of the result. + +Sometimes to help describe one expression, another expression is +shown that produces identical results. The exact equivalence of +expressions is indicated with @samp{@equiv{}}. For example, + +@example +@group +rot90 ([1, 2; 3, 4], -1) +@equiv{} +rot90 ([1, 2; 3, 4], 3) +@equiv{} +rot90 ([1, 2; 3, 4], 7) +@end group +@end example + +@node Printing Notation, Error Messages, Evaluation Notation, Conventions +@subsection Printing Notation +@cindex printing notation + +Many of the examples in this manual print text when they are +evaluated. Examples in this manual indicate printed text with +@samp{@print{}}. The value that is returned by evaluating the +expression (here @code{1}) is displayed with @samp{@result{}} and +follows on a separate line. + +@example +@group +printf ("foo %s\n", "bar") + @print{} foo bar + @result{} 1 +@end group +@end example + +@node Error Messages, Format of Descriptions, Printing Notation, Conventions +@subsection Error Messages +@cindex error message notation + +Some examples signal errors. This normally displays an error message +on your terminal. Error messages are shown on a line starting with +@code{error:}. + +@example +@group +struct_elements ([1, 2; 3, 4]) +error: struct_elements: wrong type argument `matrix' +@end group +@end example + +@node Format of Descriptions, , Error Messages, Conventions +@subsection Format of Descriptions +@cindex description format + +Functions, commands, and variables are described in this manual in a +uniform format. The first line of a description contains the name of +the item followed by its arguments, if any. +@ifinfo +The category---function, variable, or whatever---appears at the +beginning of the line. +@end ifinfo +@iftex +The category---function, variable, or whatever---is printed next to the +right margin. +@end iftex +The description follows on succeeding lines, sometimes with examples. + +@menu +* A Sample Function Description:: +* A Sample Command Description:: +* A Sample Variable Description:: +@end menu + +@node A Sample Function Description, A Sample Command Description, Format of Descriptions, Format of Descriptions +@subsubsection A Sample Function Description +@cindex function descriptions + +In a function description, the name of the function being described +appears first. It is followed on the same line by a list of parameters. +The names used for the parameters are also used in the body of the +description. + +Here is a description of an imaginary function @code{foo}: + +@deftypefn {Function} {} foo (@var{x}, @var{y}, @dots{}) +The function @code{foo} subtracts @var{x} from @var{y}, then adds the +remaining arguments to the result. If @var{y} is not supplied, then the +number 19 is used by default. + +@example +@group +foo (1, [3, 5], 3, 9) + @result{} [ 14, 16 ] +foo (5) + @result{} 14 +@end group +@end example + +More generally, + +@example +@group +foo (@var{w}, @var{x}, @var{y}, @dots{}) +@equiv{} +@var{x} - @var{w} + @var{y} + @dots{} +@end group +@end example +@end deftypefn + +Any parameter whose name contains the name of a type (e.g., +@var{integer}, @var{integer1} or @var{matrix}) is expected to be of that +type. Parameters named @var{object} may be of any type. Parameters +with other sorts of names (e.g., @var{new_file}) are discussed +specifically in the description of the function. In some sections, +features common to parameters of several functions are described at the +beginning. + +Functions in Octave may be defined in several different ways. The +catagory name for functions may include another name that indicates the +way that the function is defined. These additional tags include + +@table @asis +@item Built-in Function +@cindex built-in function +The function described is written in a language like C++, C, or Fortran, +and is part of the compiled Octave binary. + +@item Loadable Function +@cindex loadable function +The function described is written in a language like C++, C, or Fortran. +On systems that support dynamic linking of user-supplied functions, it +may be automatically linked while Octave is running, but only if it is +needed. @xref{Dynamically Linked Functions}. + +@item Function File +@cindex function file +The function described is defined using Octave commands stored in a text +file. @xref{Function Files}. + +@item Mapping Function +@cindex mapping function +The function described works element-by-element for matrix and vector +arguments. +@end table + +@node A Sample Command Description, A Sample Variable Description, A Sample Function Description, Format of Descriptions +@subsubsection A Sample Command Description +@cindex command descriptions + +Command descriptions have a format similar to function descriptions, +except that the word `Function' is replaced by `Command. Commands are +functions that may called without surrounding their arguments in +parentheses. For example, here is the description for Octave's +@code{cd} command: + +@deffn {Command} cd dir +@deffnx {Command} chdir dir +Change the current working directory to @var{dir}. For example, +@kbd{cd ~/octave} changes the current working directory to +@file{~/octave}. If the directory does not exist, an error message is +printed and the working directory is not changed. +@end deffn + +@node A Sample Variable Description, , A Sample Command Description, Format of Descriptions +@subsubsection A Sample Variable Description +@cindex variable descriptions + +A @dfn{variable} is a name that can hold a value. Although any variable +can be set by the user, @dfn{built-in variables} typically exist +specifically so that users can change them to alter the way Octave +behaves (built-in variables are also sometimes called @dfn{user +options}). Ordinary variables and built-in variables are described +using a format like that for functions except that there are no +arguments. + +Here is a description of the imaginary variable +@code{do_what_i_mean_not_what_i_say}. + +@defvr {Built-in Variable} do_what_i_mean_not_what_i_say +If the value of this variable is nonzero, Octave will do what you +actually wanted, even if you have typed a completely different and +meaningless list of commands. +@end defvr + +Other variable descriptions have the same format, but `Built-in +Variable' is replaced by `Variable', for ordinary variables, or +`Constant' for symbolic constants whose values cannot be changed. diff --git a/doc/interpreter/io.texi b/doc/interpreter/io.texi deleted file mode 100644 --- a/doc/interpreter/io.texi +++ /dev/null @@ -1,1541 +0,0 @@ -@c Copyright (C) 1996, 1997 John W. Eaton -@c This is part of the Octave manual. -@c For copying conditions, see the file gpl.texi. - -@node Input and Output, Plotting, Error Handling, Top -@chapter Input and Output - -There are two distinct classes of input and output functions. The first -set are modeled after the functions available in @sc{Matlab}. The -second set are modeled after the standard I/O library used by the C -programming language and offer more flexibility and control over the -output. - -When running interactively, Octave normally sends any output intended -for your terminal that is more than one screen long to a paging program, -such as @code{less} or @code{more}. This avoids the problem of having a -large volume of output stream by before you can read it. With -@code{less} (and some versions of @code{more}) you can also scan forward -and backward, and search for specific items. - -Normally, no output is displayed by the pager until just before Octave -is ready to print the top level prompt, or read from the standard input -(for example, by using the @code{fscanf} or @code{scanf} functions). -This means that there may be some delay before any output appears on -your screen if you have asked Octave to perform a significant amount of -work with a single command statement. The function @code{fflush} may be -used to force output to be sent to the pager (or any other stream) -immediately. - -You can select the program to run as the pager by setting the variable -@code{PAGER}, and you can turn paging off by setting the value of the -variable @code{page_screen_output} to 0. - -@deffn {Command} more -@deffnx {Command} more on -@deffnx {Command} more off -Turn output pagination on or off. Without an argument, @code{more} -toggles the current state. -@end deffn - -@defvr {Built-in Variable} PAGER -The default value is normally @code{"less"}, @code{"more"}, or -@code{"pg"}, depending on what programs are installed on your system. -@xref{Installation}. - -When running interactively, Octave sends any output intended for your -terminal that is more than one screen long to the program named by the -value of the variable @code{PAGER}. -@end defvr - -@defvr {Built-in Variable} page_screen_output -If the value of @code{page_screen_output} is nonzero, all output -intended for the screen that is longer than one page is sent through a -pager. This allows you to view one screenful at a time. Some pagers -(such as @code{less}---see @ref{Installation}) are also capable of moving -backward on the output. The default value is 1. -@end defvr - -@defvr {Built-in Variable} page_output_immediately -If the value of @code{page_output_immediately} is nonzero, Octave sends -output to the pager as soon as it is available. Otherwise, Octave -buffers its output and waits until just before the prompt is printed to -flush it to the pager. The default value is 0. - -@deftypefn {Built-in Function} {} fflush (@var{fid}) -Flush output to @var{fid}. This is useful for ensuring that all -pending output makes it to the screen before some other event occurs. -For example, it is always a good idea to flush the standard output -stream before calling @code{input}. -@end deftypefn - -@c XXX FIXME XXX -- maybe this would be a good place to describe the -@c following message: -@c -@c warning: connection to external pager (pid = 9334) lost -- -@c warning: pending computations and output may be lost -@c warning: broken pipe -@end defvr - -@menu -* Basic Input and Output:: -* C-Style I/O Functions:: -@end menu - -@node Basic Input and Output, C-Style I/O Functions, Input and Output, Input and Output -@section Basic Input and Output - -@menu -* Terminal Output:: -* Terminal Input:: -* Simple File I/O:: -@end menu - -@node Terminal Output, Terminal Input, Basic Input and Output, Basic Input and Output -@subsection Terminal Output - -Since Octave normally prints the value of an expression as soon as it -has been evaluated, the simplest of all I/O functions is a simple -expression. For example, the following expression will display the -value of pi - -@example -pi - @print{} pi = 3.1416 -@end example - -This works well as long as it is acceptable to have the name of the -variable (or @samp{ans}) printed along with the value. To print the -value of a variable without printing its name, use the function -@code{disp}. - -The @code{format} command offers some control over the way Octave prints -values with @code{disp} and through the normal echoing mechanism. - -@defvr {Built-in Variable} ans -This variable holds the most recently computed result that was not -explicitly assigned to a variable. For example, after the expression - -@example -3^2 + 4^2 -@end example - -@noindent -is evaluated, the value of @code{ans} is 25. -@end defvr - -@deftypefn {Built-in Function} {} disp (@var{x}) -Display the value of @var{x}. For example, - -@example -disp ("The value of pi is:"), disp (pi) - - @print{} the value of pi is: - @print{} 3.1416 -@end example - -@noindent -Note that the output from @code{disp} always ends with a newline. -@end deftypefn - -@deffn {Command} format options -Control the format of the output produced by @code{disp} and Octave's -normal echoing mechanism. Valid options are listed in the following -table. - -@table @code -@item short -Octave will try to print numbers with at -least 3 significant figures within a field that is a maximum of 8 -characters wide. - -If Octave is unable to format a matrix so that columns line up on the -decimal point and all the numbers fit within the maximum field width, -it switches to an @samp{e} format. - -@item long -Octave will try to print numbers with at least 15 significant figures -within a field that is a maximum of 24 characters wide. - -As will the @samp{short} format, Octave will switch to an @samp{e} -format if it is unable to format a matrix so that columns line up on the -decimal point and all the numbers fit within the maximum field width. - -@item long e -@itemx short e -The same as @samp{format long} or @samp{format short} but always display -output with an @samp{e} format. For example, with the @samp{short e} -format, pi is displayed as @code{3.14e+00}. - -@item long E -@itemx short E -The same as @samp{format long e} or @samp{format short e} but always -display output with an uppercase @samp{E} format. For example, with -the @samp{long E} format, pi is displayed as -@code{3.14159265358979E+00}. - -@item free -@itemx none -Print output in free format, without trying to line up columns of -matrices on the decimal point. This also causes complex numbers to be -formatted like this @samp{(0.604194, 0.607088)} instead of like this -@samp{0.60419 + 0.60709i}. - -@item bank -Print in a fixed format with two places to the right of the decimal -point. - -@item + -Print a @samp{+} symbol for nonzero matrix elements and a space for zero -matrix elements. This format can be very useful for examining the -structure of a large matrix. - -@item hex -Print the hexadecimal representation numbers as they are stored in -memory. For example, on a workstation which stores 8 byte real values -in IEEE format with the least significant byte first, the value of -@code{pi} when printed in @code{hex} format is @code{400921fb54442d18}. -This format only works for numeric values. - -@item bit -Print the bit representation of numbers as stored in memory. -For example, the value of @code{pi} is - -@example -@group -01000000000010010010000111111011 -01010100010001000010110100011000 -@end group -@end example - -(shown here in two 32 bit sections for typesetting purposes) when -printed in bit format on a workstation which stores 8 byte real values -in IEEE format with the least significant byte first. This format only -works for numeric types. -@end table - -By default, Octave will try to print numbers with at least 5 significant -figures within a field that is a maximum of 10 characters wide. - -If Octave is unable to format a matrix so that columns line up on the -decimal point and all the numbers fit within the maximum field width, -it switches to an @samp{e} format. - -If @code{format} is invoked without any options, the default format -state is restored. -@end deffn - -@defvr {Built-in Variable} print_answer_id_name -If the value of @code{print_answer_id_name} is nonzero, variable -names are printed along with the result. Otherwise, only the result -values are printed. The default value is 1. -@end defvr - -@node Terminal Input, Simple File I/O, Terminal Output, Basic Input and Output -@subsection Terminal Input - -Octave has three functions that make it easy to prompt users for -input. The @code{input} and @code{menu} functions are normally -used for managing an interactive dialog with a user, and the -@code{keyboard} function is normally used for doing simple debugging. - -@deftypefn {Built-in Function} {} input (@var{prompt}) -@deftypefnx {Built-in Function} {} input (@var{prompt}, "s") -Print a prompt and wait for user input. For example, - -@example -input ("Pick a number, any number! ") -@end example - -@noindent -prints the prompt - -@example -Pick a number, any number! -@end example - -@noindent -and waits for the user to enter a value. The string entered by the user -is evaluated as an expression, so it may be a literal constant, a -variable name, or any other valid expression. - -Currently, @code{input} only returns one value, regardless of the number -of values produced by the evaluation of the expression. - -If you are only interested in getting a literal string value, you can -call @code{input} with the character string @code{"s"} as the second -argument. This tells Octave to return the string entered by the user -directly, without evaluating it first. - -Because there may be output waiting to be displayed by the pager, it is -a good idea to always call @code{fflush (stdout)} before calling -@code{input}. This will ensure that all pending output is written to -the screen before your prompt. @xref{Input and Output}. -@end deftypefn - -@deftypefn {Function File} {} menu (@var{title}, @var{opt1}, @dots{}) -Print a title string followed by a series of options. Each option will -be printed along with a number. The return value is the number of the -option selected by the user. This function is useful for interactive -programs. There is no limit to the number of options that may be passed -in, but it may be confusing to present more than will fit easily on one -screen. -@end deftypefn - -@deftypefn {Built-in Function} {} keyboard (@var{prompt}) -This function is normally used for simple debugging. When the -@code{keyboard} function is executed, Octave prints a prompt and waits -for user input. The input strings are then evaluated and the results -are printed. This makes it possible to examine the values of variables -within a function, and to assign new values to variables. No value is -returned from the @code{keyboard} function, and it continues to prompt -for input until the user types @samp{quit}, or @samp{exit}. - -If @code{keyboard} is invoked without any arguments, a default prompt of -@samp{debug> } is used. -@end deftypefn - -For both @code{input} and @code{keyboard}, the normal command line -history and editing functions are available at the prompt. - -Octave also has a function that makes it possible to get a single -character from the keyboard without requiring the user to type a -carriage return. - -@c XXX FIXME XXX -- perhaps kbhit should also be able to print a prompt -@c string? - -@deftypefn {Built-in Function} {} kbhit () -Read a single keystroke from the keyboard. For example, - -@example -x = kbhit (); -@end example - -@noindent -will set @var{x} to the next character typed at the keyboard as soon as -it is typed. -@end deftypefn - -@node Simple File I/O, , Terminal Input, Basic Input and Output -@subsection Simple File I/O - -The @code{save} and @code{load} commands allow data to be written to and -read from disk files in various formats. The default format of files -written by the @code{save} command can be controlled using the built-in -variables @code{default_save_format} and @code{save_precision}. - -Note that Octave can not yet save or load structure variables or any -user-defined types. - -@deffn {Command} save options file v1 v2 @dots{} -Save the named variables @var{v1}, @var{v2}, @dots{} in the file -@var{file}. The special filename @samp{-} can be used to write the -output to your terminal. If no variable names are listed, Octave saves -all the variables in the current scope. Valid options for the -@code{save} command are listed in the following table. Options that -modify the output format override the format specified by the built-in -variable @code{default_save_format}. - -@table @code -@item -ascii -Save the data in Octave's text data format. - -@item -binary -Save the data in Octave's binary data format. - -@item -float-binary -Save the data in Octave's binary data format but only using single -precision. You should use this format only if you know that all the -values to be saved can be represented in single precision. - -@item -mat-binary -Save the data in @sc{Matlab}'s binary data format. - -@item -save-builtins -Force Octave to save the values of built-in variables too. By default, -Octave does not save built-in variables. -@end table - -The list of variables to save may include wildcard patterns containing -the following special characters: -@table @code -@item ? -Match any single character. - -@item * -Match zero or more characters. - -@item [ @var{list} ] -Match the list of characters specified by @var{list}. If the first -character is @code{!} or @code{^}, match all characters except those -specified by @var{list}. For example, the pattern @samp{[a-zA-Z]} will -match all lower and upper case alphabetic characters. -@end table - -Except when using the @sc{Matlab} binary data file format, saving global -variables also saves the global status of the variable, so that if it is -restored at a later time using @samp{load}, it will be restored as a -global variable. - -The command - -@example -save -binary data a b* -@end example - -@noindent -saves the variable @samp{a} and all variables beginning with @samp{b} to -the file @file{data} in Octave's binary format. -@end deffn - -There are two variables that modify the behavior of @code{save} and one -that controls whether variables are saved when Octave exits unexpectedly. - -@defvr {Built-in Variable} crash_dumps_octave_core -If this variable is set to a nonzero value, Octave tries to save all -current variables the the file "octave-core" if it crashes or receives a -hangup, terminate or similar signal. The default value is 1. -@end defvr - -@defvr {Built-in Variable} default_save_format -This variable specifies the default format for the @code{save} command. -It should have one of the following values: @code{"ascii"}, -@code{"binary"}, @code{float-binary}, or @code{"mat-binary"}. The -initial default save format is Octave's text format. -@end defvr - -@defvr {Built-in Variable} save_precision -This variable specifies the number of digits to keep when saving data in -text format. The default value is 17. -@end defvr - -@deffn {Command} load options file v1 v2 @dots{} -Load the named variables from the file @var{file}. As with @code{save}, -you may specify a list of variables and @code{load} will only extract -those variables with names that match. For example, to restore the -variables saved in the file @file{data}, use the command - -@example -load data -@end example - -Octave will refuse to overwrite existing variables unless you use the -option @samp{-force}. - -If a variable that is not marked as global is loaded from a file when a -global symbol with the same name already exists, it is loaded in the -global symbol table. Also, if a variable is marked as global in a file -and a local symbol exists, the local symbol is moved to the global -symbol table and given the value from the file. Since it seems that -both of these cases are likely to be the result of some sort of error, -they will generate warnings. - -The @code{load} command can read data stored in Octave's text and -binary formats, and @sc{Matlab}'s binary format. It will automatically -detect the type of file and do conversion from different floating point -formats (currently only IEEE big and little endian, though other formats -may added in the future). - -Valid options for @code{load} are listed in the following table. - -@table @code -@item -force -Force variables currently in memory to be overwritten by variables with -the same name found in the file. - -@item -ascii -Force Octave to assume the file is in Octave's text format. - -@item -binary -Force Octave to assume the file is in Octave's binary format. - -@item -mat-binary -Force Octave to assume the file is in @sc{Matlab}'s binary format. -@end table -@end deffn - -@node C-Style I/O Functions, , Basic Input and Output, Input and Output -@section C-Style I/O Functions - -Octave's C-style input and output functions provide most of the -functionality of the C programming language's standard I/O library. The -argument lists for some of the input functions are slightly different, -however, because Octave has no way of passing arguments by reference. - -In the following, @var{file} refers to a file name and @code{fid} refers -to an integer file number, as returned by @code{fopen}. - -There are three files that are always available. Although these files -can be accessed using their corresponding numeric file ids, you should -always use the symbolic names given in the table below, since it will -make your programs easier to understand. - -@defvr {Built-in Variable} stdin -The standard input stream (file id 0). When Octave is used -interactively, this is filtered through the command line editing -functions. -@end defvr - -@defvr {Built-in Variable} stdout -The standard output stream (file id 1). Data written to the -standard output is normally filtered through the pager. -@end defvr - -@defvr {Built-in Variable} stderr -The standard error stream (file id 2). Even if paging is turned on, -the standard error is not sent to the pager. It is useful for error -messages and prompts. -@end defvr - -@menu -* Opening and Closing Files:: -* Simple Output:: -* Line-Oriented Input:: -* Formatted Output:: -* Output Conversion for Matrices:: -* Output Conversion Syntax:: -* Table of Output Conversions:: -* Integer Conversions:: -* Floating-Point Conversions:: Other Output Conversions:: -* Other Output Conversions:: -* Formatted Input:: -* Input Conversion Syntax:: -* Table of Input Conversions:: -* Numeric Input Conversions:: -* String Input Conversions:: -* Binary I/O:: -* Temporary Files:: -* EOF and Errors:: -* File Positioning:: -@end menu - -@node Opening and Closing Files, Simple Output, C-Style I/O Functions, C-Style I/O Functions -@subsection Opening and Closing Files - -@deftypefn {Built-in Function} {[@var{fid}, @var{msg}] =} fopen (@var{name}, @var{mode}, @var{arch}) -@deftypefnx {Built-in Function} {@var{fid_list} =} fopen ("all") -@deftypefnx {Built-in Function} {@var{file} =} fopen (@var{fid}) -The first form of the @code{fopen} function opens the named file with -the specified mode (read-write, read-only, etc.) and architecture -interpretation (IEEE big endian, IEEE little endian, etc.), and returns -an integer value that may be used to refer to the file later. If an -error occurs, @var{fid} is set to @minus{}1 and @var{msg} contains the -corresponding system error message. The @var{mode} is a one or two -character string that specifies whether the file is to be opened for -reading, writing, or both. - -The second form of the @code{fopen} function returns a vector of file ids -corresponding to all the currently open files, excluding the -@code{stdin}, @code{stdout}, and @code{stderr} streams. - -The third form of the @code{fopen} function returns the name of a -currently open file given its file id. - -For example, - -@example -myfile = fopen ("splat.dat", "r", "ieee-le"); -@end example - -@noindent -opens the file @file{splat.dat} for reading. If necessary, binary -numeric values will be read assuming they are stored in IEEE format with -the least significant bit first, and then converted to the native -representation. - -Opening a file that is already open simply opens it again and returns a -separate file id. It is not an error to open a file several times, -though writing to the same file through several different file ids may -produce unexpected results. - -The possible values @samp{mode} may have are - -@table @asis -@item @samp{r} -Open a file for reading. - -@item @samp{w} -Open a file for writing. The previous contents are discared. - -@item @samp{a} -Open or create a file for writing at the end of the file. - -@item @samp{r+} -Open an existing file for reading and writing. - -@item @samp{w+} -Open a file for reading or writing. The previous contents are -discarded. - -@item @samp{a+} -Open or create a file for reading or writing at the end of the -file. -@end table - -The parameter @var{arch} is a string specifying the default data format -for the file. Valid values for @var{arch} are: - -@table @asis -@samp{native} -The format of the current machine (this is the default). - -@samp{ieee-le} -IEEE big endian format. - -@samp{ieee-be} -IEEE little endian format. - -@samp{vaxd} -VAX D floating format. - -@samp{vaxg} -VAX G floating format. - -@samp{cray} -Cray floating format. -@end table - -@noindent -however, conversions are currently only supported for @samp{native} -@samp{ieee-be}, and @samp{ieee-le} formats. -@end deftypefn - -@deftypefn {Built-in Function} {} fclose (@var{fid}) -Closes the specified file. If an error is encountered while trying to -close the file, an error message is printed and @code{fclose} returns -0. Otherwise, it returns 1. -@end deftypefn - -@node Simple Output, Line-Oriented Input, Opening and Closing Files, C-Style I/O Functions -@subsection Simple Output - -@deftypefn {Built-in Function} {} fputs (@var{fid}, @var{string}) -Write a string to a file with no formatting. -@end deftypefn - -@deftypefn {Built-in Function} {} puts (@var{string}) -Write a string to the standard output with no formatting. -@end deftypefn - -@node Line-Oriented Input, Formatted Output, Simple Output, C-Style I/O Functions -@subsection Line-Oriented Input - -@deftypefn {Built-in Function} {} fgetl (@var{fid}, @var{len}) -Read characters from a file, stopping after a newline, or EOF, -or @var{len} characters have been read. The characters read, excluding -the possible trailing newline, are returned as a string. - -If @var{len} is omitted, @code{fgetl} reads until the next newline -character. - -If there are no more characters to read, @code{fgetl} returns @minus{}1. -@end deftypefn - -@deftypefn {Built-in Function} {} fgets (@var{fid}, @var{len}) -Read characters from a file, stopping after a newline, or EOF, -or @var{len} characters have been read. The characters read, including -the possible trailing newline, are returned as a string. - -If @var{len} is omitted, @code{fgets} reads until the next newline -character. - -If there are no more characters to read, @code{fgets} returns @minus{}1. -@end deftypefn - -@node Formatted Output, Output Conversion for Matrices, Line-Oriented Input, C-Style I/O Functions -@subsection Formatted Output - -This section describes how to call @code{printf} and related functions. - -The following functions are available for formatted output. They are -modelled after the C language functions of the same name, but they -interpret the format template differently in order to improve the -performance of printing vector and matrix values. - -@deftypefn {Function File} {} printf (@var{template}, @dots{}) -The @code{printf} function prints the optional arguments under the -control of the template string @var{template} to the stream -@code{stdout}. -@end deftypefn - -@deftypefn {Built-in Function} {} fprintf (@var{fid}, @var{template}, @dots{}) -This function is just like @code{printf}, except that the output is -written to the stream @var{fid} instead of @code{stdout}. -@end deftypefn - -@deftypefn {Built-in Function} {} sprintf (@var{template}, @dots{}) -This is like @code{printf}, except that the output is returned as a -string. Unlike the C library function, which requires you to provide a -suitably sized string as an argument, Octave's @code{sprintf} function -returns the string, automatically sized to hold all of the items -converted. -@end deftypefn - -The @code{printf} function can be used to print any number of arguments. -The template string argument you supply in a call provides -information not only about the number of additional arguments, but also -about their types and what style should be used for printing them. - -Ordinary characters in the template string are simply written to the -output stream as-is, while @dfn{conversion specifications} introduced by -a @samp{%} character in the template cause subsequent arguments to be -formatted and written to the output stream. For example, -@cindex conversion specifications (@code{printf}) - -@smallexample -pct = 37; -filename = "foo.txt"; -printf ("Processing of `%s' is %d%% finished.\nPlease be patient.\n", - filename, pct); -@end smallexample - -@noindent -produces output like - -@smallexample -Processing of `foo.txt' is 37% finished. -Please be patient. -@end smallexample - -This example shows the use of the @samp{%d} conversion to specify that a -scalar argument should be printed in decimal notation, the @samp{%s} -conversion to specify printing of a string argument, and the @samp{%%} -conversion to print a literal @samp{%} character. - -There are also conversions for printing an integer argument as an -unsigned value in octal, decimal, or hexadecimal radix (@samp{%o}, -@samp{%u}, or @samp{%x}, respectively); or as a character value -(@samp{%c}). - -Floating-point numbers can be printed in normal, fixed-point notation -using the @samp{%f} conversion or in exponential notation using the -@samp{%e} conversion. The @samp{%g} conversion uses either @samp{%e} -or @samp{%f} format, depending on what is more appropriate for the -magnitude of the particular number. - -You can control formatting more precisely by writing @dfn{modifiers} -between the @samp{%} and the character that indicates which conversion -to apply. These slightly alter the ordinary behavior of the conversion. -For example, most conversion specifications permit you to specify a -minimum field width and a flag indicating whether you want the result -left- or right-justified within the field. - -The specific flags and modifiers that are permitted and their -interpretation vary depending on the particular conversion. They're all -described in more detail in the following sections. - -@node Output Conversion for Matrices, Output Conversion Syntax, Formatted Output, C-Style I/O Functions -@subsection Output Conversion for Matrices - -When given a matrix value, Octave's formatted output functions cycle -through the format template until all the values in the matrix have been -printed. For example, - -@example -@group -printf ("%4.2f %10.2e %8.4g\n", hilb (3)); - - @print{} 1.00 5.00e-01 0.3333 - @print{} 0.50 3.33e-01 0.25 - @print{} 0.33 2.50e-01 0.2 -@end group -@end example - -If more than one value is to be printed in a single call, the output -functions do not return to the beginning of the format template when -moving on from one value to the next. This can lead to confusing output -if the number of elements in the matrices are not exact multiples of the -number of conversions in the format template. For example, - -@example -@group -printf ("%4.2f %10.2e %8.4g\n", [1, 2], [3, 4]); - - @print{} 1.00 2.00e+00 3 - @print{} 4.00 -@end group -@end example - -If this is not what you want, use a series of calls instead of just one. - -@node Output Conversion Syntax, Table of Output Conversions, Output Conversion for Matrices, C-Style I/O Functions -@subsection Output Conversion Syntax - -This section provides details about the precise syntax of conversion -specifications that can appear in a @code{printf} template -string. - -Characters in the template string that are not part of a -conversion specification are printed as-is to the output stream. - -The conversion specifications in a @code{printf} template string have -the general form: - -@smallexample -% @var{flags} @var{width} @r{[} . @var{precision} @r{]} @var{type} @var{conversion} -@end smallexample - -For example, in the conversion specifier @samp{%-10.8ld}, the @samp{-} -is a flag, @samp{10} specifies the field width, the precision is -@samp{8}, the letter @samp{l} is a type modifier, and @samp{d} specifies -the conversion style. (This particular type specifier says to print a -numeric argument in decimal notation, with a minimum of 8 digits -left-justified in a field at least 10 characters wide.) - -In more detail, output conversion specifications consist of an -initial @samp{%} character followed in sequence by: - -@itemize @bullet -@item -Zero or more @dfn{flag characters} that modify the normal behavior of -the conversion specification. -@cindex flag character (@code{printf}) - -@item -An optional decimal integer specifying the @dfn{minimum field width}. -If the normal conversion produces fewer characters than this, the field -is padded with spaces to the specified width. This is a @emph{minimum} -value; if the normal conversion produces more characters than this, the -field is @emph{not} truncated. Normally, the output is right-justified -within the field. -@cindex minimum field width (@code{printf}) - -You can also specify a field width of @samp{*}. This means that the -next argument in the argument list (before the actual value to be -printed) is used as the field width. The value is rounded to the -nearest integer. If the value is negative, this means to set the -@samp{-} flag (see below) and to use the absolute value as the field -width. - -@item -An optional @dfn{precision} to specify the number of digits to be -written for the numeric conversions. If the precision is specified, it -consists of a period (@samp{.}) followed optionally by a decimal integer -(which defaults to zero if omitted). -@cindex precision (@code{printf}) - -You can also specify a precision of @samp{*}. This means that the next -argument in the argument list (before the actual value to be printed) is -used as the precision. The value must be an integer, and is ignored -if it is negative. - -@item -An optional @dfn{type modifier character}. This character is ignored by -Octave's @code{printf} function, but is recognized to provide -compatibility with the C language @code{printf}. - -@item -A character that specifies the conversion to be applied. -@end itemize - -The exact options that are permitted and how they are interpreted vary -between the different conversion specifiers. See the descriptions of the -individual conversions for information about the particular options that -they use. - -@node Table of Output Conversions, Integer Conversions, Output Conversion Syntax, C-Style I/O Functions -@subsection Table of Output Conversions -@cindex output conversions, for @code{printf} - -Here is a table summarizing what all the different conversions do: - -@table @asis -@item @samp{%d}, @samp{%i} -Print an integer as a signed decimal number. @xref{Integer -Conversions}, for details. @samp{%d} and @samp{%i} are synonymous for -output, but are different when used with @code{scanf} for input -(@pxref{Table of Input Conversions}). - -@item @samp{%o} -Print an integer as an unsigned octal number. @xref{Integer -Conversions}, for details. - -@item @samp{%u} -Print an integer as an unsigned decimal number. @xref{Integer -Conversions}, for details. - -@item @samp{%x}, @samp{%X} -Print an integer as an unsigned hexadecimal number. @samp{%x} uses -lower-case letters and @samp{%X} uses upper-case. @xref{Integer -Conversions}, for details. - -@item @samp{%f} -Print a floating-point number in normal (fixed-point) notation. -@xref{Floating-Point Conversions}, for details. - -@item @samp{%e}, @samp{%E} -Print a floating-point number in exponential notation. @samp{%e} uses -lower-case letters and @samp{%E} uses upper-case. @xref{Floating-Point -Conversions}, for details. - -@item @samp{%g}, @samp{%G} -Print a floating-point number in either normal (fixed-point) or -exponential notation, whichever is more appropriate for its magnitude. -@samp{%g} uses lower-case letters and @samp{%G} uses upper-case. -@xref{Floating-Point Conversions}, for details. - -@item @samp{%c} -Print a single character. @xref{Other Output Conversions}. - -@item @samp{%s} -Print a string. @xref{Other Output Conversions}. - -@item @samp{%%} -Print a literal @samp{%} character. @xref{Other Output Conversions}. -@end table - -If the syntax of a conversion specification is invalid, unpredictable -things will happen, so don't do this. If there aren't enough function -arguments provided to supply values for all the conversion -specifications in the template string, or if the arguments are not of -the correct types, the results are unpredictable. If you supply more -arguments than conversion specifications, the extra argument values are -simply ignored; this is sometimes useful. - -@node Integer Conversions, Floating-Point Conversions, Table of Output Conversions, C-Style I/O Functions -@subsection Integer Conversions - -This section describes the options for the @samp{%d}, @samp{%i}, -@samp{%o}, @samp{%u}, @samp{%x}, and @samp{%X} conversion -specifications. These conversions print integers in various formats. - -The @samp{%d} and @samp{%i} conversion specifications both print an -numeric argument as a signed decimal number; while @samp{%o}, -@samp{%u}, and @samp{%x} print the argument as an unsigned octal, -decimal, or hexadecimal number (respectively). The @samp{%X} conversion -specification is just like @samp{%x} except that it uses the characters -@samp{ABCDEF} as digits instead of @samp{abcdef}. - -The following flags are meaningful: - -@table @asis -@item @samp{-} -Left-justify the result in the field (instead of the normal -right-justification). - -@item @samp{+} -For the signed @samp{%d} and @samp{%i} conversions, print a -plus sign if the value is positive. - -@item @samp{ } -For the signed @samp{%d} and @samp{%i} conversions, if the result -doesn't start with a plus or minus sign, prefix it with a space -character instead. Since the @samp{+} flag ensures that the result -includes a sign, this flag is ignored if you supply both of them. - -@item @samp{#} -For the @samp{%o} conversion, this forces the leading digit to be -@samp{0}, as if by increasing the precision. For @samp{%x} or -@samp{%X}, this prefixes a leading @samp{0x} or @samp{0X} (respectively) -to the result. This doesn't do anything useful for the @samp{%d}, -@samp{%i}, or @samp{%u} conversions. - -@item @samp{0} -Pad the field with zeros instead of spaces. The zeros are placed after -any indication of sign or base. This flag is ignored if the @samp{-} -flag is also specified, or if a precision is specified. -@end table - -If a precision is supplied, it specifies the minimum number of digits to -appear; leading zeros are produced if necessary. If you don't specify a -precision, the number is printed with as many digits as it needs. If -you convert a value of zero with an explicit precision of zero, then no -characters at all are produced. - -@node Floating-Point Conversions, Other Output Conversions, Integer Conversions, C-Style I/O Functions -@subsection Floating-Point Conversions - -This section discusses the conversion specifications for floating-point -numbers: the @samp{%f}, @samp{%e}, @samp{%E}, @samp{%g}, and @samp{%G} -conversions. - -The @samp{%f} conversion prints its argument in fixed-point notation, -producing output of the form -@w{[@code{-}]@var{ddd}@code{.}@var{ddd}}, -where the number of digits following the decimal point is controlled -by the precision you specify. - -The @samp{%e} conversion prints its argument in exponential notation, -producing output of the form -@w{[@code{-}]@var{d}@code{.}@var{ddd}@code{e}[@code{+}|@code{-}]@var{dd}}. -Again, the number of digits following the decimal point is controlled by -the precision. The exponent always contains at least two digits. The -@samp{%E} conversion is similar but the exponent is marked with the letter -@samp{E} instead of @samp{e}. - -The @samp{%g} and @samp{%G} conversions print the argument in the style -of @samp{%e} or @samp{%E} (respectively) if the exponent would be less -than -4 or greater than or equal to the precision; otherwise they use the -@samp{%f} style. Trailing zeros are removed from the fractional portion -of the result and a decimal-point character appears only if it is -followed by a digit. - -The following flags can be used to modify the behavior: - -@c Not @samp so we can have ` ' as an item. -@table @asis -@item @samp{-} -Left-justify the result in the field. Normally the result is -right-justified. - -@item @samp{+} -Always include a plus or minus sign in the result. - -@item @samp{ } -If the result doesn't start with a plus or minus sign, prefix it with a -space instead. Since the @samp{+} flag ensures that the result includes -a sign, this flag is ignored if you supply both of them. - -@item @samp{#} -Specifies that the result should always include a decimal point, even -if no digits follow it. For the @samp{%g} and @samp{%G} conversions, -this also forces trailing zeros after the decimal point to be left -in place where they would otherwise be removed. - -@item @samp{0} -Pad the field with zeros instead of spaces; the zeros are placed -after any sign. This flag is ignored if the @samp{-} flag is also -specified. -@end table - -The precision specifies how many digits follow the decimal-point -character for the @samp{%f}, @samp{%e}, and @samp{%E} conversions. For -these conversions, the default precision is @code{6}. If the precision -is explicitly @code{0}, this suppresses the decimal point character -entirely. For the @samp{%g} and @samp{%G} conversions, the precision -specifies how many significant digits to print. Significant digits are -the first digit before the decimal point, and all the digits after it. -If the precision is @code{0} or not specified for @samp{%g} or -@samp{%G}, it is treated like a value of @code{1}. If the value being -printed cannot be expressed precisely in the specified number of digits, -the value is rounded to the nearest number that fits. - -@node Other Output Conversions, Formatted Input, Floating-Point Conversions, C-Style I/O Functions -@subsection Other Output Conversions - -This section describes miscellaneous conversions for @code{printf}. - -The @samp{%c} conversion prints a single character. The @samp{-} -flag can be used to specify left-justification in the field, but no -other flags are defined, and no precision or type modifier can be given. -For example: - -@smallexample -printf ("%c%c%c%c%c", "h", "e", "l", "l", "o"); -@end smallexample - -@noindent -prints @samp{hello}. - -The @samp{%s} conversion prints a string. The corresponding argument -must be a string. A precision can be specified to indicate the maximum -number of characters to write; otherwise characters in the string up to -but not including the terminating null character are written to the -output stream. The @samp{-} flag can be used to specify -left-justification in the field, but no other flags or type modifiers -are defined for this conversion. For example: - -@smallexample -printf ("%3s%-6s", "no", "where"); -@end smallexample - -@noindent -prints @samp{ nowhere } (note the leading and trailing spaces). - -@node Formatted Input, Input Conversion Syntax, Other Output Conversions, C-Style I/O Functions -@subsection Formatted Input - -Octave provides the @code{scanf}, @code{fscanf}, and @code{sscanf} -functions to read formatted input. There are two forms of each of these -functions. One can be used to extract vectors of data from a file, and -the other is more `C-like'. - -@deftypefn {Built-in Function} {[@var{val}, @var{count}] =} fscanf (@var{fid}, @var{template}, @var{size}) -@deftypefnx {Built-in Function} {[@var{v1}, @var{v2}, @dots{}] = } fscanf (@var{fid}, @var{template}, "C") -In the first form, read from @var{fid} according to @var{template}, -returning the result in the matrix @var{val}. - -The optional argument @var{size} specifies the amount of data to read -and may be one of - -@table @code -@item Inf -Read as much as possible, returning a column vector. - -@item @var{nr} -Read up to @var{nr} elements, returning a column vector. - -@item [@var{nr}, Inf] -Read as much as possible, returning a matrix with @var{nr} rows. If the -number of elements read is not an exact multiple of @var{nr}, the last -column is padded with zeros. - -@item [@var{nr}, @var{nc}] -Read up to @code{@var{nr} * @var{nc}} elements, returning a matrix with -@var{nr} rows. If the number of elements read is not an exact multiple -of @var{nr}, the last column is padded with zeros. -@end table - -@noindent -If @var{size} is omitted, a value of @code{Inf} is assumed. - -A string is returned if @var{template} specifies only character -conversions. - -The number of items successfully read is returned in @var{count}. - -In the second form, read from @var{fid} according to @var{template}, -with each conversion specifier in @var{template} corresponding to a -single scalar return value. This form is more `C-like', and also -compatible with previous versions of Octave. -@end deftypefn - -@deftypefn {Built-in Function} {[@var{val}, @var{count}] =} sscanf (@var{string}, @var{template}, @var{size}) -@deftypefnx {Built-in Function} {[@var{v1}, @var{v2}, @dots{}] = } sscanf (@var{string}, @var{template}, "C") -This is like @code{fscanf}, except that the characters are taken from the -string @var{string} instead of from a stream. Reaching the end of the -string is treated as an end-of-file condition. -@end deftypefn - -@deftypefn {Built-in Function} {[@var{val}, @var{count}] =} scanf (@var{template}, @var{size}) -@deftypefnx {Built-in Function} {[@var{v1}, @var{v2}, @dots{}] = } scanf (@var{template}, "C") -This is equivalent to calling @code{fscanf} with @var{fid} = @code{stdin}. - -It is currently not useful to call @code{scanf} in interactive -programs. -@end deftypefn - -Calls to @code{scanf} are superficially similar to calls to -@code{printf} in that arbitrary arguments are read under the control of -a template string. While the syntax of the conversion specifications in -the template is very similar to that for @code{printf}, the -interpretation of the template is oriented more towards free-format -input and simple pattern matching, rather than fixed-field formatting. -For example, most @code{scanf} conversions skip over any amount of -``white space'' (including spaces, tabs, and newlines) in the input -file, and there is no concept of precision for the numeric input -conversions as there is for the corresponding output conversions. -Ordinarily, non-whitespace characters in the template are expected to -match characters in the input stream exactly. -@cindex conversion specifications (@code{scanf}) - -When a @dfn{matching failure} occurs, @code{scanf} returns immediately, -leaving the first non-matching character as the next character to be -read from the stream, and @code{scanf} returns all the items that were -successfully converted. -@cindex matching failure, in @code{scanf} - -The formatted input functions are not used as frequently as the -formatted output functions. Partly, this is because it takes some care -to use them properly. Another reason is that it is difficult to recover -from a matching error. - -@node Input Conversion Syntax, Table of Input Conversions, Formatted Input, C-Style I/O Functions -@subsection Input Conversion Syntax - -A @code{scanf} template string is a string that contains ordinary -multibyte characters interspersed with conversion specifications that -start with @samp{%}. - -Any whitespace character in the template causes any number of whitespace -characters in the input stream to be read and discarded. The whitespace -characters that are matched need not be exactly the same whitespace -characters that appear in the template string. For example, write -@samp{ , } in the template to recognize a comma with optional whitespace -before and after. - -Other characters in the template string that are not part of conversion -specifications must match characters in the input stream exactly; if -this is not the case, a matching failure occurs. - -The conversion specifications in a @code{scanf} template string -have the general form: - -@smallexample -% @var{flags} @var{width} @var{type} @var{conversion} -@end smallexample - -In more detail, an input conversion specification consists of an initial -@samp{%} character followed in sequence by: - -@itemize @bullet -@item -An optional @dfn{flag character} @samp{*}, which says to ignore the text -read for this specification. When @code{scanf} finds a conversion -specification that uses this flag, it reads input as directed by the -rest of the conversion specification, but it discards this input, does -not return any value, and does not increment the count of -successful assignments. -@cindex flag character (@code{scanf}) - -@item -An optional decimal integer that specifies the @dfn{maximum field -width}. Reading of characters from the input stream stops either when -this maximum is reached or when a non-matching character is found, -whichever happens first. Most conversions discard initial whitespace -characters, and these discarded characters don't count towards the -maximum field width. Conversions that do not discard initial whitespace -are explicitly documented. -@cindex maximum field width (@code{scanf}) - -@item -An optional type modifier character. This character is ignored by -Octave's @code{scanf} function, but is recognized to provide -compatibility with the C language @code{scanf}. - -@item -A character that specifies the conversion to be applied. -@end itemize - -The exact options that are permitted and how they are interpreted vary -between the different conversion specifiers. See the descriptions of the -individual conversions for information about the particular options that -they allow. - -@node Table of Input Conversions, Numeric Input Conversions, Input Conversion Syntax, C-Style I/O Functions -@subsection Table of Input Conversions -@cindex input conversions, for @code{scanf} - -Here is a table that summarizes the various conversion specifications: - -@table @asis -@item @samp{%d} -Matches an optionally signed integer written in decimal. @xref{Numeric -Input Conversions}. - -@item @samp{%i} -Matches an optionally signed integer in any of the formats that the C -language defines for specifying an integer constant. @xref{Numeric -Input Conversions}. - -@item @samp{%o} -Matches an unsigned integer written in octal radix. -@xref{Numeric Input Conversions}. - -@item @samp{%u} -Matches an unsigned integer written in decimal radix. -@xref{Numeric Input Conversions}. - -@item @samp{%x}, @samp{%X} -Matches an unsigned integer written in hexadecimal radix. -@xref{Numeric Input Conversions}. - -@item @samp{%e}, @samp{%f}, @samp{%g}, @samp{%E}, @samp{%G} -Matches an optionally signed floating-point number. @xref{Numeric Input -Conversions}. - -@item @samp{%s} -Matches a string containing only non-whitespace characters. -@xref{String Input Conversions}. - -@item @samp{%c} -Matches a string of one or more characters; the number of characters -read is controlled by the maximum field width given for the conversion. -@xref{String Input Conversions}. - -@item @samp{%%} -This matches a literal @samp{%} character in the input stream. No -corresponding argument is used. -@end table - -If the syntax of a conversion specification is invalid, the behavior is -undefined. If there aren't enough function arguments provided to supply -addresses for all the conversion specifications in the template strings -that perform assignments, or if the arguments are not of the correct -types, the behavior is also undefined. On the other hand, extra -arguments are simply ignored. - -@node Numeric Input Conversions, String Input Conversions, Table of Input Conversions, C-Style I/O Functions -@subsection Numeric Input Conversions - -This section describes the @code{scanf} conversions for reading numeric -values. - -The @samp{%d} conversion matches an optionally signed integer in decimal -radix. - -The @samp{%i} conversion matches an optionally signed integer in any of -the formats that the C language defines for specifying an integer -constant. - -For example, any of the strings @samp{10}, @samp{0xa}, or @samp{012} -could be read in as integers under the @samp{%i} conversion. Each of -these specifies a number with decimal value @code{10}. - -The @samp{%o}, @samp{%u}, and @samp{%x} conversions match unsigned -integers in octal, decimal, and hexadecimal radices, respectively. - -The @samp{%X} conversion is identical to the @samp{%x} conversion. They -both permit either uppercase or lowercase letters to be used as digits. - -Unlike the C language @code{scanf}, Octave ignores the @samp{h}, -@samp{l}, and @samp{L} modifiers. - -@node String Input Conversions, Binary I/O, Numeric Input Conversions, C-Style I/O Functions -@subsection String Input Conversions - -This section describes the @code{scanf} input conversions for reading -string and character values: @samp{%s} and @samp{%c}. - -The @samp{%c} conversion is the simplest: it matches a fixed number of -characters, always. The maximum field with says how many characters to -read; if you don't specify the maximum, the default is 1. This -conversion does not skip over initial whitespace characters. It reads -precisely the next @var{n} characters, and fails if it cannot get that -many. - -The @samp{%s} conversion matches a string of non-whitespace characters. -It skips and discards initial whitespace, but stops when it encounters -more whitespace after having read something. - -For example, reading the input: - -@smallexample - hello, world -@end smallexample - -@noindent -with the conversion @samp{%10c} produces @code{" hello, wo"}, but -reading the same input with the conversion @samp{%10s} produces -@code{"hello,"}. - -@node Binary I/O, Temporary Files, String Input Conversions, C-Style I/O Functions -@subsection Binary I/O - -Octave can read and write binary data using the functions @code{fread} -and @code{fwrite}, which are patterned after the standard C functions -with the same names. The are able to automatically swap the byte order -of integer data and convert among ths supported floating point formats -as the data are read. - -@deftypefn {Built-in Function} {[@var{val}, @var{count}] =} fread (@var{fid}, @var{size}, @var{precision}, @var{skip}, @var{arch}) -Read binary data of type @var{precision} from the specified file ID -@var{fid}. - -The optional argument @var{size} specifies the amount of data to read -and may be one of - -@table @code -@item Inf -Read as much as possible, returning a column vector. - -@item @var{nr} -Read up to @var{nr} elements, returning a column vector. - -@item [@var{nr}, Inf] -Read as much as possible, returning a matrix with @var{nr} rows. If the -number of elements read is not an exact multiple of @var{nr}, the last -column is padded with zeros. - -@item [@var{nr}, @var{nc}] -Read up to @code{@var{nr} * @var{nc}} elements, returning a matrix with -@var{nr} rows. If the number of elements read is not an exact multiple -of @var{nr}, the last column is padded with zeros. -@end table - -@noindent -If @var{size} is omitted, a value of @code{Inf} is assumed. - -The optional argument @var{precision} is a string specifying the type of -data to read and may be one of - -@table @code -@item "char" -@itemx "char*1" -@itemx "integer*1" -@itemx "int8" -Single character. - -@item "signed char" -@itemx "schar" -Signed character. - -@item "unsigned char" -@itemx "uchar" -Unsigned character. - -@item "short" -Short integer. - -@item "unsigned short" -@itemx "ushort" -Unsigned short integer. - -@item "int" -Integer. - -@item "unsigned int" -@itemx "uint" -Unsigned integer. - -@item "long" -Long integer. - -@item "unsigned long" -@itemx "ulong" -Unsigned long integer. - -@item "float" -@itemx "float32" -@itemx "real*4" -Single precision float. - -@item "double" -@itemx "float64" -@itemx "real*8" -Double precision float. - -@item "integer*2" -@itemx "int16" -Two byte integer. - -@item "integer*4" -@itemx "int32" -Four byte integer. -@end table - -@noindent -The default precision is @code{"uchar"}. - -The optional argument @var{skip} specifies the number of bytes to skip -before each element is read. If it is not specified, a value of 0 is -assumed. - -The optional argument @var{arch} is a string specifying the data format -for the file. Valid values are - -@table @code -@item "native" -The format of the current machine. - -@item "ieee-le" -IEEE big endian. - -@item "ieee-be" -IEEE little endian. - -@item "vaxd" -VAX D floating format. - -@item "vaxg" -VAX G floating format. - -@item "cray" -Cray floating format. -@end table - -@noindent -Conversions are currently only supported for @code{"ieee-be"} and -@code{"ieee-le"} formats. - -The data read from the file is returned in @var{val}, and the number of -values read is returned in @code{count} -@end deftypefn - -@deftypefn {Built-in Function} {@var{count} =} fwrite (@var{fid}, @var{data}, @var{precision}, @var{skip}, @var{arch}) -Write data in binary form of type @var{precision} to the specified file -ID @var{fid}, returning the number of values successfully written to the -file. - -The argument @var{data} is a matrix of values that are to be written to -the file. The values are extracted in column-major order. - -The remaining arguments @var{precision}, @var{skip}, and @var{arch} are -optional, and are interpreted as described for @code{fread}. - -The behavior of @code{fwrite} is undefined if the values in @var{data} -are too large to fit in the specified precision. -@end deftypefn - -@node Temporary Files, EOF and Errors, Binary I/O, C-Style I/O Functions -@subsection Temporary Files - -@deftypefn {Built-in Function} {} tmpnam () -Return a unique temporary file name as a string. - -Since the named file is not opened, by @code{tmpnam}, it -is possible (though relatively unlikely) that it will not be available -by the time your program attempts to open it. -@end deftypefn - -@node EOF and Errors, File Positioning, Temporary Files, C-Style I/O Functions -@subsection End of File and Errors - -@deftypefn {Built-in Function} {} feof (@var{fid}) -Return 1 if an end-of-file condition has been encountered for a given -file and 0 otherwise. Note that it will only return 1 if the end of the -file has already been encountered, not if the next read operation will -result in an end-of-file condition. -@end deftypefn - -@deftypefn {Built-in Function} {} ferror (@var{fid}) -Return 1 if an error condition has been encountered for a given file -and 0 otherwise. Note that it will only return 1 if an error has -already been encountered, not if the next operation will result in an -error condition. -@end deftypefn - -@deftypefn {Built-in Function} {} freport () -Print a list of which files have been opened, and whether they are open -for reading, writing, or both. For example, - -@example -@group -freport () - - @print{} number mode name - @print{} - @print{} 0 r stdin - @print{} 1 w stdout - @print{} 2 w stderr - @print{} 3 r myfile -@end group -@end example -@end deftypefn - -@node File Positioning, , EOF and Errors, C-Style I/O Functions -@subsection File Positioning - -Three functions are available for setting and determining the position of -the file pointer for a given file. - -@deftypefn {Built-in Function} {} ftell (@var{fid}) -Return the position of the file pointer as the number of characters -from the beginning of the file @var{fid}. -@end deftypefn - -@deftypefn {Built-in Function} {} fseek (@var{fid}, @var{offset}, @var{origin}) -Set the file pointer to any location within the file @var{fid}. The -pointer is positioned @var{offset} characters from the @var{origin}, -which may be one of the predefined variables @code{SEEK_CUR} (current -position), @code{SEEK_SET} (beginning), or @code{SEEK_END} (end of -file). If @var{origin} is omitted, @code{SEEK_SET} is assumed. The -offset must be zero, or a value returned by @code{ftell} (in which case -@var{origin} must be @code{SEEK_SET}. -@end deftypefn - -@defvr {Built-in Variable} SEEK_SET -@defvrx {Built-in Variable} SEEK_CUR -@defvrx {Built-in Variable} SEEK_END -These variables may be used as the optional third argument for the -function @code{fseek}. -@end defvr - -@deftypefn {Built-in Function} {} frewind (@var{fid}) -Move the file pointer to the beginning of the file @var{fid}, returning -1 for success, and 0 if an error was encountered. It is equivalent to -@code{fseek (@var{fid}, 0, SEEK_SET)}. -@end deftypefn - -The following example stores the current file position in the variable -@code{marker}, moves the pointer to the beginning of the file, reads -four characters, and then returns to the original position. - -@example -marker = ftell (myfile); -frewind (myfile); -fourch = fgets (myfile, 4); -fseek (myfile, marker, SEEK_SET); -@end example - diff --git a/doc/interpreter/io.txi b/doc/interpreter/io.txi new file mode 100644 --- /dev/null +++ b/doc/interpreter/io.txi @@ -0,0 +1,1541 @@ +@c Copyright (C) 1996, 1997 John W. Eaton +@c This is part of the Octave manual. +@c For copying conditions, see the file gpl.texi. + +@node Input and Output, Plotting, Error Handling, Top +@chapter Input and Output + +There are two distinct classes of input and output functions. The first +set are modeled after the functions available in @sc{Matlab}. The +second set are modeled after the standard I/O library used by the C +programming language and offer more flexibility and control over the +output. + +When running interactively, Octave normally sends any output intended +for your terminal that is more than one screen long to a paging program, +such as @code{less} or @code{more}. This avoids the problem of having a +large volume of output stream by before you can read it. With +@code{less} (and some versions of @code{more}) you can also scan forward +and backward, and search for specific items. + +Normally, no output is displayed by the pager until just before Octave +is ready to print the top level prompt, or read from the standard input +(for example, by using the @code{fscanf} or @code{scanf} functions). +This means that there may be some delay before any output appears on +your screen if you have asked Octave to perform a significant amount of +work with a single command statement. The function @code{fflush} may be +used to force output to be sent to the pager (or any other stream) +immediately. + +You can select the program to run as the pager by setting the variable +@code{PAGER}, and you can turn paging off by setting the value of the +variable @code{page_screen_output} to 0. + +@deffn {Command} more +@deffnx {Command} more on +@deffnx {Command} more off +Turn output pagination on or off. Without an argument, @code{more} +toggles the current state. +@end deffn + +@defvr {Built-in Variable} PAGER +The default value is normally @code{"less"}, @code{"more"}, or +@code{"pg"}, depending on what programs are installed on your system. +@xref{Installation}. + +When running interactively, Octave sends any output intended for your +terminal that is more than one screen long to the program named by the +value of the variable @code{PAGER}. +@end defvr + +@defvr {Built-in Variable} page_screen_output +If the value of @code{page_screen_output} is nonzero, all output +intended for the screen that is longer than one page is sent through a +pager. This allows you to view one screenful at a time. Some pagers +(such as @code{less}---see @ref{Installation}) are also capable of moving +backward on the output. The default value is 1. +@end defvr + +@defvr {Built-in Variable} page_output_immediately +If the value of @code{page_output_immediately} is nonzero, Octave sends +output to the pager as soon as it is available. Otherwise, Octave +buffers its output and waits until just before the prompt is printed to +flush it to the pager. The default value is 0. + +@deftypefn {Built-in Function} {} fflush (@var{fid}) +Flush output to @var{fid}. This is useful for ensuring that all +pending output makes it to the screen before some other event occurs. +For example, it is always a good idea to flush the standard output +stream before calling @code{input}. +@end deftypefn + +@c XXX FIXME XXX -- maybe this would be a good place to describe the +@c following message: +@c +@c warning: connection to external pager (pid = 9334) lost -- +@c warning: pending computations and output may be lost +@c warning: broken pipe +@end defvr + +@menu +* Basic Input and Output:: +* C-Style I/O Functions:: +@end menu + +@node Basic Input and Output, C-Style I/O Functions, Input and Output, Input and Output +@section Basic Input and Output + +@menu +* Terminal Output:: +* Terminal Input:: +* Simple File I/O:: +@end menu + +@node Terminal Output, Terminal Input, Basic Input and Output, Basic Input and Output +@subsection Terminal Output + +Since Octave normally prints the value of an expression as soon as it +has been evaluated, the simplest of all I/O functions is a simple +expression. For example, the following expression will display the +value of pi + +@example +pi + @print{} pi = 3.1416 +@end example + +This works well as long as it is acceptable to have the name of the +variable (or @samp{ans}) printed along with the value. To print the +value of a variable without printing its name, use the function +@code{disp}. + +The @code{format} command offers some control over the way Octave prints +values with @code{disp} and through the normal echoing mechanism. + +@defvr {Built-in Variable} ans +This variable holds the most recently computed result that was not +explicitly assigned to a variable. For example, after the expression + +@example +3^2 + 4^2 +@end example + +@noindent +is evaluated, the value of @code{ans} is 25. +@end defvr + +@deftypefn {Built-in Function} {} disp (@var{x}) +Display the value of @var{x}. For example, + +@example +disp ("The value of pi is:"), disp (pi) + + @print{} the value of pi is: + @print{} 3.1416 +@end example + +@noindent +Note that the output from @code{disp} always ends with a newline. +@end deftypefn + +@deffn {Command} format options +Control the format of the output produced by @code{disp} and Octave's +normal echoing mechanism. Valid options are listed in the following +table. + +@table @code +@item short +Octave will try to print numbers with at +least 3 significant figures within a field that is a maximum of 8 +characters wide. + +If Octave is unable to format a matrix so that columns line up on the +decimal point and all the numbers fit within the maximum field width, +it switches to an @samp{e} format. + +@item long +Octave will try to print numbers with at least 15 significant figures +within a field that is a maximum of 24 characters wide. + +As will the @samp{short} format, Octave will switch to an @samp{e} +format if it is unable to format a matrix so that columns line up on the +decimal point and all the numbers fit within the maximum field width. + +@item long e +@itemx short e +The same as @samp{format long} or @samp{format short} but always display +output with an @samp{e} format. For example, with the @samp{short e} +format, pi is displayed as @code{3.14e+00}. + +@item long E +@itemx short E +The same as @samp{format long e} or @samp{format short e} but always +display output with an uppercase @samp{E} format. For example, with +the @samp{long E} format, pi is displayed as +@code{3.14159265358979E+00}. + +@item free +@itemx none +Print output in free format, without trying to line up columns of +matrices on the decimal point. This also causes complex numbers to be +formatted like this @samp{(0.604194, 0.607088)} instead of like this +@samp{0.60419 + 0.60709i}. + +@item bank +Print in a fixed format with two places to the right of the decimal +point. + +@item + +Print a @samp{+} symbol for nonzero matrix elements and a space for zero +matrix elements. This format can be very useful for examining the +structure of a large matrix. + +@item hex +Print the hexadecimal representation numbers as they are stored in +memory. For example, on a workstation which stores 8 byte real values +in IEEE format with the least significant byte first, the value of +@code{pi} when printed in @code{hex} format is @code{400921fb54442d18}. +This format only works for numeric values. + +@item bit +Print the bit representation of numbers as stored in memory. +For example, the value of @code{pi} is + +@example +@group +01000000000010010010000111111011 +01010100010001000010110100011000 +@end group +@end example + +(shown here in two 32 bit sections for typesetting purposes) when +printed in bit format on a workstation which stores 8 byte real values +in IEEE format with the least significant byte first. This format only +works for numeric types. +@end table + +By default, Octave will try to print numbers with at least 5 significant +figures within a field that is a maximum of 10 characters wide. + +If Octave is unable to format a matrix so that columns line up on the +decimal point and all the numbers fit within the maximum field width, +it switches to an @samp{e} format. + +If @code{format} is invoked without any options, the default format +state is restored. +@end deffn + +@defvr {Built-in Variable} print_answer_id_name +If the value of @code{print_answer_id_name} is nonzero, variable +names are printed along with the result. Otherwise, only the result +values are printed. The default value is 1. +@end defvr + +@node Terminal Input, Simple File I/O, Terminal Output, Basic Input and Output +@subsection Terminal Input + +Octave has three functions that make it easy to prompt users for +input. The @code{input} and @code{menu} functions are normally +used for managing an interactive dialog with a user, and the +@code{keyboard} function is normally used for doing simple debugging. + +@deftypefn {Built-in Function} {} input (@var{prompt}) +@deftypefnx {Built-in Function} {} input (@var{prompt}, "s") +Print a prompt and wait for user input. For example, + +@example +input ("Pick a number, any number! ") +@end example + +@noindent +prints the prompt + +@example +Pick a number, any number! +@end example + +@noindent +and waits for the user to enter a value. The string entered by the user +is evaluated as an expression, so it may be a literal constant, a +variable name, or any other valid expression. + +Currently, @code{input} only returns one value, regardless of the number +of values produced by the evaluation of the expression. + +If you are only interested in getting a literal string value, you can +call @code{input} with the character string @code{"s"} as the second +argument. This tells Octave to return the string entered by the user +directly, without evaluating it first. + +Because there may be output waiting to be displayed by the pager, it is +a good idea to always call @code{fflush (stdout)} before calling +@code{input}. This will ensure that all pending output is written to +the screen before your prompt. @xref{Input and Output}. +@end deftypefn + +@deftypefn {Function File} {} menu (@var{title}, @var{opt1}, @dots{}) +Print a title string followed by a series of options. Each option will +be printed along with a number. The return value is the number of the +option selected by the user. This function is useful for interactive +programs. There is no limit to the number of options that may be passed +in, but it may be confusing to present more than will fit easily on one +screen. +@end deftypefn + +@deftypefn {Built-in Function} {} keyboard (@var{prompt}) +This function is normally used for simple debugging. When the +@code{keyboard} function is executed, Octave prints a prompt and waits +for user input. The input strings are then evaluated and the results +are printed. This makes it possible to examine the values of variables +within a function, and to assign new values to variables. No value is +returned from the @code{keyboard} function, and it continues to prompt +for input until the user types @samp{quit}, or @samp{exit}. + +If @code{keyboard} is invoked without any arguments, a default prompt of +@samp{debug> } is used. +@end deftypefn + +For both @code{input} and @code{keyboard}, the normal command line +history and editing functions are available at the prompt. + +Octave also has a function that makes it possible to get a single +character from the keyboard without requiring the user to type a +carriage return. + +@c XXX FIXME XXX -- perhaps kbhit should also be able to print a prompt +@c string? + +@deftypefn {Built-in Function} {} kbhit () +Read a single keystroke from the keyboard. For example, + +@example +x = kbhit (); +@end example + +@noindent +will set @var{x} to the next character typed at the keyboard as soon as +it is typed. +@end deftypefn + +@node Simple File I/O, , Terminal Input, Basic Input and Output +@subsection Simple File I/O + +The @code{save} and @code{load} commands allow data to be written to and +read from disk files in various formats. The default format of files +written by the @code{save} command can be controlled using the built-in +variables @code{default_save_format} and @code{save_precision}. + +Note that Octave can not yet save or load structure variables or any +user-defined types. + +@deffn {Command} save options file v1 v2 @dots{} +Save the named variables @var{v1}, @var{v2}, @dots{} in the file +@var{file}. The special filename @samp{-} can be used to write the +output to your terminal. If no variable names are listed, Octave saves +all the variables in the current scope. Valid options for the +@code{save} command are listed in the following table. Options that +modify the output format override the format specified by the built-in +variable @code{default_save_format}. + +@table @code +@item -ascii +Save the data in Octave's text data format. + +@item -binary +Save the data in Octave's binary data format. + +@item -float-binary +Save the data in Octave's binary data format but only using single +precision. You should use this format only if you know that all the +values to be saved can be represented in single precision. + +@item -mat-binary +Save the data in @sc{Matlab}'s binary data format. + +@item -save-builtins +Force Octave to save the values of built-in variables too. By default, +Octave does not save built-in variables. +@end table + +The list of variables to save may include wildcard patterns containing +the following special characters: +@table @code +@item ? +Match any single character. + +@item * +Match zero or more characters. + +@item [ @var{list} ] +Match the list of characters specified by @var{list}. If the first +character is @code{!} or @code{^}, match all characters except those +specified by @var{list}. For example, the pattern @samp{[a-zA-Z]} will +match all lower and upper case alphabetic characters. +@end table + +Except when using the @sc{Matlab} binary data file format, saving global +variables also saves the global status of the variable, so that if it is +restored at a later time using @samp{load}, it will be restored as a +global variable. + +The command + +@example +save -binary data a b* +@end example + +@noindent +saves the variable @samp{a} and all variables beginning with @samp{b} to +the file @file{data} in Octave's binary format. +@end deffn + +There are two variables that modify the behavior of @code{save} and one +that controls whether variables are saved when Octave exits unexpectedly. + +@defvr {Built-in Variable} crash_dumps_octave_core +If this variable is set to a nonzero value, Octave tries to save all +current variables the the file "octave-core" if it crashes or receives a +hangup, terminate or similar signal. The default value is 1. +@end defvr + +@defvr {Built-in Variable} default_save_format +This variable specifies the default format for the @code{save} command. +It should have one of the following values: @code{"ascii"}, +@code{"binary"}, @code{float-binary}, or @code{"mat-binary"}. The +initial default save format is Octave's text format. +@end defvr + +@defvr {Built-in Variable} save_precision +This variable specifies the number of digits to keep when saving data in +text format. The default value is 17. +@end defvr + +@deffn {Command} load options file v1 v2 @dots{} +Load the named variables from the file @var{file}. As with @code{save}, +you may specify a list of variables and @code{load} will only extract +those variables with names that match. For example, to restore the +variables saved in the file @file{data}, use the command + +@example +load data +@end example + +Octave will refuse to overwrite existing variables unless you use the +option @samp{-force}. + +If a variable that is not marked as global is loaded from a file when a +global symbol with the same name already exists, it is loaded in the +global symbol table. Also, if a variable is marked as global in a file +and a local symbol exists, the local symbol is moved to the global +symbol table and given the value from the file. Since it seems that +both of these cases are likely to be the result of some sort of error, +they will generate warnings. + +The @code{load} command can read data stored in Octave's text and +binary formats, and @sc{Matlab}'s binary format. It will automatically +detect the type of file and do conversion from different floating point +formats (currently only IEEE big and little endian, though other formats +may added in the future). + +Valid options for @code{load} are listed in the following table. + +@table @code +@item -force +Force variables currently in memory to be overwritten by variables with +the same name found in the file. + +@item -ascii +Force Octave to assume the file is in Octave's text format. + +@item -binary +Force Octave to assume the file is in Octave's binary format. + +@item -mat-binary +Force Octave to assume the file is in @sc{Matlab}'s binary format. +@end table +@end deffn + +@node C-Style I/O Functions, , Basic Input and Output, Input and Output +@section C-Style I/O Functions + +Octave's C-style input and output functions provide most of the +functionality of the C programming language's standard I/O library. The +argument lists for some of the input functions are slightly different, +however, because Octave has no way of passing arguments by reference. + +In the following, @var{file} refers to a file name and @code{fid} refers +to an integer file number, as returned by @code{fopen}. + +There are three files that are always available. Although these files +can be accessed using their corresponding numeric file ids, you should +always use the symbolic names given in the table below, since it will +make your programs easier to understand. + +@defvr {Built-in Variable} stdin +The standard input stream (file id 0). When Octave is used +interactively, this is filtered through the command line editing +functions. +@end defvr + +@defvr {Built-in Variable} stdout +The standard output stream (file id 1). Data written to the +standard output is normally filtered through the pager. +@end defvr + +@defvr {Built-in Variable} stderr +The standard error stream (file id 2). Even if paging is turned on, +the standard error is not sent to the pager. It is useful for error +messages and prompts. +@end defvr + +@menu +* Opening and Closing Files:: +* Simple Output:: +* Line-Oriented Input:: +* Formatted Output:: +* Output Conversion for Matrices:: +* Output Conversion Syntax:: +* Table of Output Conversions:: +* Integer Conversions:: +* Floating-Point Conversions:: Other Output Conversions:: +* Other Output Conversions:: +* Formatted Input:: +* Input Conversion Syntax:: +* Table of Input Conversions:: +* Numeric Input Conversions:: +* String Input Conversions:: +* Binary I/O:: +* Temporary Files:: +* EOF and Errors:: +* File Positioning:: +@end menu + +@node Opening and Closing Files, Simple Output, C-Style I/O Functions, C-Style I/O Functions +@subsection Opening and Closing Files + +@deftypefn {Built-in Function} {[@var{fid}, @var{msg}] =} fopen (@var{name}, @var{mode}, @var{arch}) +@deftypefnx {Built-in Function} {@var{fid_list} =} fopen ("all") +@deftypefnx {Built-in Function} {@var{file} =} fopen (@var{fid}) +The first form of the @code{fopen} function opens the named file with +the specified mode (read-write, read-only, etc.) and architecture +interpretation (IEEE big endian, IEEE little endian, etc.), and returns +an integer value that may be used to refer to the file later. If an +error occurs, @var{fid} is set to @minus{}1 and @var{msg} contains the +corresponding system error message. The @var{mode} is a one or two +character string that specifies whether the file is to be opened for +reading, writing, or both. + +The second form of the @code{fopen} function returns a vector of file ids +corresponding to all the currently open files, excluding the +@code{stdin}, @code{stdout}, and @code{stderr} streams. + +The third form of the @code{fopen} function returns the name of a +currently open file given its file id. + +For example, + +@example +myfile = fopen ("splat.dat", "r", "ieee-le"); +@end example + +@noindent +opens the file @file{splat.dat} for reading. If necessary, binary +numeric values will be read assuming they are stored in IEEE format with +the least significant bit first, and then converted to the native +representation. + +Opening a file that is already open simply opens it again and returns a +separate file id. It is not an error to open a file several times, +though writing to the same file through several different file ids may +produce unexpected results. + +The possible values @samp{mode} may have are + +@table @asis +@item @samp{r} +Open a file for reading. + +@item @samp{w} +Open a file for writing. The previous contents are discared. + +@item @samp{a} +Open or create a file for writing at the end of the file. + +@item @samp{r+} +Open an existing file for reading and writing. + +@item @samp{w+} +Open a file for reading or writing. The previous contents are +discarded. + +@item @samp{a+} +Open or create a file for reading or writing at the end of the +file. +@end table + +The parameter @var{arch} is a string specifying the default data format +for the file. Valid values for @var{arch} are: + +@table @asis +@samp{native} +The format of the current machine (this is the default). + +@samp{ieee-le} +IEEE big endian format. + +@samp{ieee-be} +IEEE little endian format. + +@samp{vaxd} +VAX D floating format. + +@samp{vaxg} +VAX G floating format. + +@samp{cray} +Cray floating format. +@end table + +@noindent +however, conversions are currently only supported for @samp{native} +@samp{ieee-be}, and @samp{ieee-le} formats. +@end deftypefn + +@deftypefn {Built-in Function} {} fclose (@var{fid}) +Closes the specified file. If an error is encountered while trying to +close the file, an error message is printed and @code{fclose} returns +0. Otherwise, it returns 1. +@end deftypefn + +@node Simple Output, Line-Oriented Input, Opening and Closing Files, C-Style I/O Functions +@subsection Simple Output + +@deftypefn {Built-in Function} {} fputs (@var{fid}, @var{string}) +Write a string to a file with no formatting. +@end deftypefn + +@deftypefn {Built-in Function} {} puts (@var{string}) +Write a string to the standard output with no formatting. +@end deftypefn + +@node Line-Oriented Input, Formatted Output, Simple Output, C-Style I/O Functions +@subsection Line-Oriented Input + +@deftypefn {Built-in Function} {} fgetl (@var{fid}, @var{len}) +Read characters from a file, stopping after a newline, or EOF, +or @var{len} characters have been read. The characters read, excluding +the possible trailing newline, are returned as a string. + +If @var{len} is omitted, @code{fgetl} reads until the next newline +character. + +If there are no more characters to read, @code{fgetl} returns @minus{}1. +@end deftypefn + +@deftypefn {Built-in Function} {} fgets (@var{fid}, @var{len}) +Read characters from a file, stopping after a newline, or EOF, +or @var{len} characters have been read. The characters read, including +the possible trailing newline, are returned as a string. + +If @var{len} is omitted, @code{fgets} reads until the next newline +character. + +If there are no more characters to read, @code{fgets} returns @minus{}1. +@end deftypefn + +@node Formatted Output, Output Conversion for Matrices, Line-Oriented Input, C-Style I/O Functions +@subsection Formatted Output + +This section describes how to call @code{printf} and related functions. + +The following functions are available for formatted output. They are +modelled after the C language functions of the same name, but they +interpret the format template differently in order to improve the +performance of printing vector and matrix values. + +@deftypefn {Function File} {} printf (@var{template}, @dots{}) +The @code{printf} function prints the optional arguments under the +control of the template string @var{template} to the stream +@code{stdout}. +@end deftypefn + +@deftypefn {Built-in Function} {} fprintf (@var{fid}, @var{template}, @dots{}) +This function is just like @code{printf}, except that the output is +written to the stream @var{fid} instead of @code{stdout}. +@end deftypefn + +@deftypefn {Built-in Function} {} sprintf (@var{template}, @dots{}) +This is like @code{printf}, except that the output is returned as a +string. Unlike the C library function, which requires you to provide a +suitably sized string as an argument, Octave's @code{sprintf} function +returns the string, automatically sized to hold all of the items +converted. +@end deftypefn + +The @code{printf} function can be used to print any number of arguments. +The template string argument you supply in a call provides +information not only about the number of additional arguments, but also +about their types and what style should be used for printing them. + +Ordinary characters in the template string are simply written to the +output stream as-is, while @dfn{conversion specifications} introduced by +a @samp{%} character in the template cause subsequent arguments to be +formatted and written to the output stream. For example, +@cindex conversion specifications (@code{printf}) + +@smallexample +pct = 37; +filename = "foo.txt"; +printf ("Processing of `%s' is %d%% finished.\nPlease be patient.\n", + filename, pct); +@end smallexample + +@noindent +produces output like + +@smallexample +Processing of `foo.txt' is 37% finished. +Please be patient. +@end smallexample + +This example shows the use of the @samp{%d} conversion to specify that a +scalar argument should be printed in decimal notation, the @samp{%s} +conversion to specify printing of a string argument, and the @samp{%%} +conversion to print a literal @samp{%} character. + +There are also conversions for printing an integer argument as an +unsigned value in octal, decimal, or hexadecimal radix (@samp{%o}, +@samp{%u}, or @samp{%x}, respectively); or as a character value +(@samp{%c}). + +Floating-point numbers can be printed in normal, fixed-point notation +using the @samp{%f} conversion or in exponential notation using the +@samp{%e} conversion. The @samp{%g} conversion uses either @samp{%e} +or @samp{%f} format, depending on what is more appropriate for the +magnitude of the particular number. + +You can control formatting more precisely by writing @dfn{modifiers} +between the @samp{%} and the character that indicates which conversion +to apply. These slightly alter the ordinary behavior of the conversion. +For example, most conversion specifications permit you to specify a +minimum field width and a flag indicating whether you want the result +left- or right-justified within the field. + +The specific flags and modifiers that are permitted and their +interpretation vary depending on the particular conversion. They're all +described in more detail in the following sections. + +@node Output Conversion for Matrices, Output Conversion Syntax, Formatted Output, C-Style I/O Functions +@subsection Output Conversion for Matrices + +When given a matrix value, Octave's formatted output functions cycle +through the format template until all the values in the matrix have been +printed. For example, + +@example +@group +printf ("%4.2f %10.2e %8.4g\n", hilb (3)); + + @print{} 1.00 5.00e-01 0.3333 + @print{} 0.50 3.33e-01 0.25 + @print{} 0.33 2.50e-01 0.2 +@end group +@end example + +If more than one value is to be printed in a single call, the output +functions do not return to the beginning of the format template when +moving on from one value to the next. This can lead to confusing output +if the number of elements in the matrices are not exact multiples of the +number of conversions in the format template. For example, + +@example +@group +printf ("%4.2f %10.2e %8.4g\n", [1, 2], [3, 4]); + + @print{} 1.00 2.00e+00 3 + @print{} 4.00 +@end group +@end example + +If this is not what you want, use a series of calls instead of just one. + +@node Output Conversion Syntax, Table of Output Conversions, Output Conversion for Matrices, C-Style I/O Functions +@subsection Output Conversion Syntax + +This section provides details about the precise syntax of conversion +specifications that can appear in a @code{printf} template +string. + +Characters in the template string that are not part of a +conversion specification are printed as-is to the output stream. + +The conversion specifications in a @code{printf} template string have +the general form: + +@smallexample +% @var{flags} @var{width} @r{[} . @var{precision} @r{]} @var{type} @var{conversion} +@end smallexample + +For example, in the conversion specifier @samp{%-10.8ld}, the @samp{-} +is a flag, @samp{10} specifies the field width, the precision is +@samp{8}, the letter @samp{l} is a type modifier, and @samp{d} specifies +the conversion style. (This particular type specifier says to print a +numeric argument in decimal notation, with a minimum of 8 digits +left-justified in a field at least 10 characters wide.) + +In more detail, output conversion specifications consist of an +initial @samp{%} character followed in sequence by: + +@itemize @bullet +@item +Zero or more @dfn{flag characters} that modify the normal behavior of +the conversion specification. +@cindex flag character (@code{printf}) + +@item +An optional decimal integer specifying the @dfn{minimum field width}. +If the normal conversion produces fewer characters than this, the field +is padded with spaces to the specified width. This is a @emph{minimum} +value; if the normal conversion produces more characters than this, the +field is @emph{not} truncated. Normally, the output is right-justified +within the field. +@cindex minimum field width (@code{printf}) + +You can also specify a field width of @samp{*}. This means that the +next argument in the argument list (before the actual value to be +printed) is used as the field width. The value is rounded to the +nearest integer. If the value is negative, this means to set the +@samp{-} flag (see below) and to use the absolute value as the field +width. + +@item +An optional @dfn{precision} to specify the number of digits to be +written for the numeric conversions. If the precision is specified, it +consists of a period (@samp{.}) followed optionally by a decimal integer +(which defaults to zero if omitted). +@cindex precision (@code{printf}) + +You can also specify a precision of @samp{*}. This means that the next +argument in the argument list (before the actual value to be printed) is +used as the precision. The value must be an integer, and is ignored +if it is negative. + +@item +An optional @dfn{type modifier character}. This character is ignored by +Octave's @code{printf} function, but is recognized to provide +compatibility with the C language @code{printf}. + +@item +A character that specifies the conversion to be applied. +@end itemize + +The exact options that are permitted and how they are interpreted vary +between the different conversion specifiers. See the descriptions of the +individual conversions for information about the particular options that +they use. + +@node Table of Output Conversions, Integer Conversions, Output Conversion Syntax, C-Style I/O Functions +@subsection Table of Output Conversions +@cindex output conversions, for @code{printf} + +Here is a table summarizing what all the different conversions do: + +@table @asis +@item @samp{%d}, @samp{%i} +Print an integer as a signed decimal number. @xref{Integer +Conversions}, for details. @samp{%d} and @samp{%i} are synonymous for +output, but are different when used with @code{scanf} for input +(@pxref{Table of Input Conversions}). + +@item @samp{%o} +Print an integer as an unsigned octal number. @xref{Integer +Conversions}, for details. + +@item @samp{%u} +Print an integer as an unsigned decimal number. @xref{Integer +Conversions}, for details. + +@item @samp{%x}, @samp{%X} +Print an integer as an unsigned hexadecimal number. @samp{%x} uses +lower-case letters and @samp{%X} uses upper-case. @xref{Integer +Conversions}, for details. + +@item @samp{%f} +Print a floating-point number in normal (fixed-point) notation. +@xref{Floating-Point Conversions}, for details. + +@item @samp{%e}, @samp{%E} +Print a floating-point number in exponential notation. @samp{%e} uses +lower-case letters and @samp{%E} uses upper-case. @xref{Floating-Point +Conversions}, for details. + +@item @samp{%g}, @samp{%G} +Print a floating-point number in either normal (fixed-point) or +exponential notation, whichever is more appropriate for its magnitude. +@samp{%g} uses lower-case letters and @samp{%G} uses upper-case. +@xref{Floating-Point Conversions}, for details. + +@item @samp{%c} +Print a single character. @xref{Other Output Conversions}. + +@item @samp{%s} +Print a string. @xref{Other Output Conversions}. + +@item @samp{%%} +Print a literal @samp{%} character. @xref{Other Output Conversions}. +@end table + +If the syntax of a conversion specification is invalid, unpredictable +things will happen, so don't do this. If there aren't enough function +arguments provided to supply values for all the conversion +specifications in the template string, or if the arguments are not of +the correct types, the results are unpredictable. If you supply more +arguments than conversion specifications, the extra argument values are +simply ignored; this is sometimes useful. + +@node Integer Conversions, Floating-Point Conversions, Table of Output Conversions, C-Style I/O Functions +@subsection Integer Conversions + +This section describes the options for the @samp{%d}, @samp{%i}, +@samp{%o}, @samp{%u}, @samp{%x}, and @samp{%X} conversion +specifications. These conversions print integers in various formats. + +The @samp{%d} and @samp{%i} conversion specifications both print an +numeric argument as a signed decimal number; while @samp{%o}, +@samp{%u}, and @samp{%x} print the argument as an unsigned octal, +decimal, or hexadecimal number (respectively). The @samp{%X} conversion +specification is just like @samp{%x} except that it uses the characters +@samp{ABCDEF} as digits instead of @samp{abcdef}. + +The following flags are meaningful: + +@table @asis +@item @samp{-} +Left-justify the result in the field (instead of the normal +right-justification). + +@item @samp{+} +For the signed @samp{%d} and @samp{%i} conversions, print a +plus sign if the value is positive. + +@item @samp{ } +For the signed @samp{%d} and @samp{%i} conversions, if the result +doesn't start with a plus or minus sign, prefix it with a space +character instead. Since the @samp{+} flag ensures that the result +includes a sign, this flag is ignored if you supply both of them. + +@item @samp{#} +For the @samp{%o} conversion, this forces the leading digit to be +@samp{0}, as if by increasing the precision. For @samp{%x} or +@samp{%X}, this prefixes a leading @samp{0x} or @samp{0X} (respectively) +to the result. This doesn't do anything useful for the @samp{%d}, +@samp{%i}, or @samp{%u} conversions. + +@item @samp{0} +Pad the field with zeros instead of spaces. The zeros are placed after +any indication of sign or base. This flag is ignored if the @samp{-} +flag is also specified, or if a precision is specified. +@end table + +If a precision is supplied, it specifies the minimum number of digits to +appear; leading zeros are produced if necessary. If you don't specify a +precision, the number is printed with as many digits as it needs. If +you convert a value of zero with an explicit precision of zero, then no +characters at all are produced. + +@node Floating-Point Conversions, Other Output Conversions, Integer Conversions, C-Style I/O Functions +@subsection Floating-Point Conversions + +This section discusses the conversion specifications for floating-point +numbers: the @samp{%f}, @samp{%e}, @samp{%E}, @samp{%g}, and @samp{%G} +conversions. + +The @samp{%f} conversion prints its argument in fixed-point notation, +producing output of the form +@w{[@code{-}]@var{ddd}@code{.}@var{ddd}}, +where the number of digits following the decimal point is controlled +by the precision you specify. + +The @samp{%e} conversion prints its argument in exponential notation, +producing output of the form +@w{[@code{-}]@var{d}@code{.}@var{ddd}@code{e}[@code{+}|@code{-}]@var{dd}}. +Again, the number of digits following the decimal point is controlled by +the precision. The exponent always contains at least two digits. The +@samp{%E} conversion is similar but the exponent is marked with the letter +@samp{E} instead of @samp{e}. + +The @samp{%g} and @samp{%G} conversions print the argument in the style +of @samp{%e} or @samp{%E} (respectively) if the exponent would be less +than -4 or greater than or equal to the precision; otherwise they use the +@samp{%f} style. Trailing zeros are removed from the fractional portion +of the result and a decimal-point character appears only if it is +followed by a digit. + +The following flags can be used to modify the behavior: + +@c Not @samp so we can have ` ' as an item. +@table @asis +@item @samp{-} +Left-justify the result in the field. Normally the result is +right-justified. + +@item @samp{+} +Always include a plus or minus sign in the result. + +@item @samp{ } +If the result doesn't start with a plus or minus sign, prefix it with a +space instead. Since the @samp{+} flag ensures that the result includes +a sign, this flag is ignored if you supply both of them. + +@item @samp{#} +Specifies that the result should always include a decimal point, even +if no digits follow it. For the @samp{%g} and @samp{%G} conversions, +this also forces trailing zeros after the decimal point to be left +in place where they would otherwise be removed. + +@item @samp{0} +Pad the field with zeros instead of spaces; the zeros are placed +after any sign. This flag is ignored if the @samp{-} flag is also +specified. +@end table + +The precision specifies how many digits follow the decimal-point +character for the @samp{%f}, @samp{%e}, and @samp{%E} conversions. For +these conversions, the default precision is @code{6}. If the precision +is explicitly @code{0}, this suppresses the decimal point character +entirely. For the @samp{%g} and @samp{%G} conversions, the precision +specifies how many significant digits to print. Significant digits are +the first digit before the decimal point, and all the digits after it. +If the precision is @code{0} or not specified for @samp{%g} or +@samp{%G}, it is treated like a value of @code{1}. If the value being +printed cannot be expressed precisely in the specified number of digits, +the value is rounded to the nearest number that fits. + +@node Other Output Conversions, Formatted Input, Floating-Point Conversions, C-Style I/O Functions +@subsection Other Output Conversions + +This section describes miscellaneous conversions for @code{printf}. + +The @samp{%c} conversion prints a single character. The @samp{-} +flag can be used to specify left-justification in the field, but no +other flags are defined, and no precision or type modifier can be given. +For example: + +@smallexample +printf ("%c%c%c%c%c", "h", "e", "l", "l", "o"); +@end smallexample + +@noindent +prints @samp{hello}. + +The @samp{%s} conversion prints a string. The corresponding argument +must be a string. A precision can be specified to indicate the maximum +number of characters to write; otherwise characters in the string up to +but not including the terminating null character are written to the +output stream. The @samp{-} flag can be used to specify +left-justification in the field, but no other flags or type modifiers +are defined for this conversion. For example: + +@smallexample +printf ("%3s%-6s", "no", "where"); +@end smallexample + +@noindent +prints @samp{ nowhere } (note the leading and trailing spaces). + +@node Formatted Input, Input Conversion Syntax, Other Output Conversions, C-Style I/O Functions +@subsection Formatted Input + +Octave provides the @code{scanf}, @code{fscanf}, and @code{sscanf} +functions to read formatted input. There are two forms of each of these +functions. One can be used to extract vectors of data from a file, and +the other is more `C-like'. + +@deftypefn {Built-in Function} {[@var{val}, @var{count}] =} fscanf (@var{fid}, @var{template}, @var{size}) +@deftypefnx {Built-in Function} {[@var{v1}, @var{v2}, @dots{}] = } fscanf (@var{fid}, @var{template}, "C") +In the first form, read from @var{fid} according to @var{template}, +returning the result in the matrix @var{val}. + +The optional argument @var{size} specifies the amount of data to read +and may be one of + +@table @code +@item Inf +Read as much as possible, returning a column vector. + +@item @var{nr} +Read up to @var{nr} elements, returning a column vector. + +@item [@var{nr}, Inf] +Read as much as possible, returning a matrix with @var{nr} rows. If the +number of elements read is not an exact multiple of @var{nr}, the last +column is padded with zeros. + +@item [@var{nr}, @var{nc}] +Read up to @code{@var{nr} * @var{nc}} elements, returning a matrix with +@var{nr} rows. If the number of elements read is not an exact multiple +of @var{nr}, the last column is padded with zeros. +@end table + +@noindent +If @var{size} is omitted, a value of @code{Inf} is assumed. + +A string is returned if @var{template} specifies only character +conversions. + +The number of items successfully read is returned in @var{count}. + +In the second form, read from @var{fid} according to @var{template}, +with each conversion specifier in @var{template} corresponding to a +single scalar return value. This form is more `C-like', and also +compatible with previous versions of Octave. +@end deftypefn + +@deftypefn {Built-in Function} {[@var{val}, @var{count}] =} sscanf (@var{string}, @var{template}, @var{size}) +@deftypefnx {Built-in Function} {[@var{v1}, @var{v2}, @dots{}] = } sscanf (@var{string}, @var{template}, "C") +This is like @code{fscanf}, except that the characters are taken from the +string @var{string} instead of from a stream. Reaching the end of the +string is treated as an end-of-file condition. +@end deftypefn + +@deftypefn {Built-in Function} {[@var{val}, @var{count}] =} scanf (@var{template}, @var{size}) +@deftypefnx {Built-in Function} {[@var{v1}, @var{v2}, @dots{}] = } scanf (@var{template}, "C") +This is equivalent to calling @code{fscanf} with @var{fid} = @code{stdin}. + +It is currently not useful to call @code{scanf} in interactive +programs. +@end deftypefn + +Calls to @code{scanf} are superficially similar to calls to +@code{printf} in that arbitrary arguments are read under the control of +a template string. While the syntax of the conversion specifications in +the template is very similar to that for @code{printf}, the +interpretation of the template is oriented more towards free-format +input and simple pattern matching, rather than fixed-field formatting. +For example, most @code{scanf} conversions skip over any amount of +``white space'' (including spaces, tabs, and newlines) in the input +file, and there is no concept of precision for the numeric input +conversions as there is for the corresponding output conversions. +Ordinarily, non-whitespace characters in the template are expected to +match characters in the input stream exactly. +@cindex conversion specifications (@code{scanf}) + +When a @dfn{matching failure} occurs, @code{scanf} returns immediately, +leaving the first non-matching character as the next character to be +read from the stream, and @code{scanf} returns all the items that were +successfully converted. +@cindex matching failure, in @code{scanf} + +The formatted input functions are not used as frequently as the +formatted output functions. Partly, this is because it takes some care +to use them properly. Another reason is that it is difficult to recover +from a matching error. + +@node Input Conversion Syntax, Table of Input Conversions, Formatted Input, C-Style I/O Functions +@subsection Input Conversion Syntax + +A @code{scanf} template string is a string that contains ordinary +multibyte characters interspersed with conversion specifications that +start with @samp{%}. + +Any whitespace character in the template causes any number of whitespace +characters in the input stream to be read and discarded. The whitespace +characters that are matched need not be exactly the same whitespace +characters that appear in the template string. For example, write +@samp{ , } in the template to recognize a comma with optional whitespace +before and after. + +Other characters in the template string that are not part of conversion +specifications must match characters in the input stream exactly; if +this is not the case, a matching failure occurs. + +The conversion specifications in a @code{scanf} template string +have the general form: + +@smallexample +% @var{flags} @var{width} @var{type} @var{conversion} +@end smallexample + +In more detail, an input conversion specification consists of an initial +@samp{%} character followed in sequence by: + +@itemize @bullet +@item +An optional @dfn{flag character} @samp{*}, which says to ignore the text +read for this specification. When @code{scanf} finds a conversion +specification that uses this flag, it reads input as directed by the +rest of the conversion specification, but it discards this input, does +not return any value, and does not increment the count of +successful assignments. +@cindex flag character (@code{scanf}) + +@item +An optional decimal integer that specifies the @dfn{maximum field +width}. Reading of characters from the input stream stops either when +this maximum is reached or when a non-matching character is found, +whichever happens first. Most conversions discard initial whitespace +characters, and these discarded characters don't count towards the +maximum field width. Conversions that do not discard initial whitespace +are explicitly documented. +@cindex maximum field width (@code{scanf}) + +@item +An optional type modifier character. This character is ignored by +Octave's @code{scanf} function, but is recognized to provide +compatibility with the C language @code{scanf}. + +@item +A character that specifies the conversion to be applied. +@end itemize + +The exact options that are permitted and how they are interpreted vary +between the different conversion specifiers. See the descriptions of the +individual conversions for information about the particular options that +they allow. + +@node Table of Input Conversions, Numeric Input Conversions, Input Conversion Syntax, C-Style I/O Functions +@subsection Table of Input Conversions +@cindex input conversions, for @code{scanf} + +Here is a table that summarizes the various conversion specifications: + +@table @asis +@item @samp{%d} +Matches an optionally signed integer written in decimal. @xref{Numeric +Input Conversions}. + +@item @samp{%i} +Matches an optionally signed integer in any of the formats that the C +language defines for specifying an integer constant. @xref{Numeric +Input Conversions}. + +@item @samp{%o} +Matches an unsigned integer written in octal radix. +@xref{Numeric Input Conversions}. + +@item @samp{%u} +Matches an unsigned integer written in decimal radix. +@xref{Numeric Input Conversions}. + +@item @samp{%x}, @samp{%X} +Matches an unsigned integer written in hexadecimal radix. +@xref{Numeric Input Conversions}. + +@item @samp{%e}, @samp{%f}, @samp{%g}, @samp{%E}, @samp{%G} +Matches an optionally signed floating-point number. @xref{Numeric Input +Conversions}. + +@item @samp{%s} +Matches a string containing only non-whitespace characters. +@xref{String Input Conversions}. + +@item @samp{%c} +Matches a string of one or more characters; the number of characters +read is controlled by the maximum field width given for the conversion. +@xref{String Input Conversions}. + +@item @samp{%%} +This matches a literal @samp{%} character in the input stream. No +corresponding argument is used. +@end table + +If the syntax of a conversion specification is invalid, the behavior is +undefined. If there aren't enough function arguments provided to supply +addresses for all the conversion specifications in the template strings +that perform assignments, or if the arguments are not of the correct +types, the behavior is also undefined. On the other hand, extra +arguments are simply ignored. + +@node Numeric Input Conversions, String Input Conversions, Table of Input Conversions, C-Style I/O Functions +@subsection Numeric Input Conversions + +This section describes the @code{scanf} conversions for reading numeric +values. + +The @samp{%d} conversion matches an optionally signed integer in decimal +radix. + +The @samp{%i} conversion matches an optionally signed integer in any of +the formats that the C language defines for specifying an integer +constant. + +For example, any of the strings @samp{10}, @samp{0xa}, or @samp{012} +could be read in as integers under the @samp{%i} conversion. Each of +these specifies a number with decimal value @code{10}. + +The @samp{%o}, @samp{%u}, and @samp{%x} conversions match unsigned +integers in octal, decimal, and hexadecimal radices, respectively. + +The @samp{%X} conversion is identical to the @samp{%x} conversion. They +both permit either uppercase or lowercase letters to be used as digits. + +Unlike the C language @code{scanf}, Octave ignores the @samp{h}, +@samp{l}, and @samp{L} modifiers. + +@node String Input Conversions, Binary I/O, Numeric Input Conversions, C-Style I/O Functions +@subsection String Input Conversions + +This section describes the @code{scanf} input conversions for reading +string and character values: @samp{%s} and @samp{%c}. + +The @samp{%c} conversion is the simplest: it matches a fixed number of +characters, always. The maximum field with says how many characters to +read; if you don't specify the maximum, the default is 1. This +conversion does not skip over initial whitespace characters. It reads +precisely the next @var{n} characters, and fails if it cannot get that +many. + +The @samp{%s} conversion matches a string of non-whitespace characters. +It skips and discards initial whitespace, but stops when it encounters +more whitespace after having read something. + +For example, reading the input: + +@smallexample + hello, world +@end smallexample + +@noindent +with the conversion @samp{%10c} produces @code{" hello, wo"}, but +reading the same input with the conversion @samp{%10s} produces +@code{"hello,"}. + +@node Binary I/O, Temporary Files, String Input Conversions, C-Style I/O Functions +@subsection Binary I/O + +Octave can read and write binary data using the functions @code{fread} +and @code{fwrite}, which are patterned after the standard C functions +with the same names. The are able to automatically swap the byte order +of integer data and convert among ths supported floating point formats +as the data are read. + +@deftypefn {Built-in Function} {[@var{val}, @var{count}] =} fread (@var{fid}, @var{size}, @var{precision}, @var{skip}, @var{arch}) +Read binary data of type @var{precision} from the specified file ID +@var{fid}. + +The optional argument @var{size} specifies the amount of data to read +and may be one of + +@table @code +@item Inf +Read as much as possible, returning a column vector. + +@item @var{nr} +Read up to @var{nr} elements, returning a column vector. + +@item [@var{nr}, Inf] +Read as much as possible, returning a matrix with @var{nr} rows. If the +number of elements read is not an exact multiple of @var{nr}, the last +column is padded with zeros. + +@item [@var{nr}, @var{nc}] +Read up to @code{@var{nr} * @var{nc}} elements, returning a matrix with +@var{nr} rows. If the number of elements read is not an exact multiple +of @var{nr}, the last column is padded with zeros. +@end table + +@noindent +If @var{size} is omitted, a value of @code{Inf} is assumed. + +The optional argument @var{precision} is a string specifying the type of +data to read and may be one of + +@table @code +@item "char" +@itemx "char*1" +@itemx "integer*1" +@itemx "int8" +Single character. + +@item "signed char" +@itemx "schar" +Signed character. + +@item "unsigned char" +@itemx "uchar" +Unsigned character. + +@item "short" +Short integer. + +@item "unsigned short" +@itemx "ushort" +Unsigned short integer. + +@item "int" +Integer. + +@item "unsigned int" +@itemx "uint" +Unsigned integer. + +@item "long" +Long integer. + +@item "unsigned long" +@itemx "ulong" +Unsigned long integer. + +@item "float" +@itemx "float32" +@itemx "real*4" +Single precision float. + +@item "double" +@itemx "float64" +@itemx "real*8" +Double precision float. + +@item "integer*2" +@itemx "int16" +Two byte integer. + +@item "integer*4" +@itemx "int32" +Four byte integer. +@end table + +@noindent +The default precision is @code{"uchar"}. + +The optional argument @var{skip} specifies the number of bytes to skip +before each element is read. If it is not specified, a value of 0 is +assumed. + +The optional argument @var{arch} is a string specifying the data format +for the file. Valid values are + +@table @code +@item "native" +The format of the current machine. + +@item "ieee-le" +IEEE big endian. + +@item "ieee-be" +IEEE little endian. + +@item "vaxd" +VAX D floating format. + +@item "vaxg" +VAX G floating format. + +@item "cray" +Cray floating format. +@end table + +@noindent +Conversions are currently only supported for @code{"ieee-be"} and +@code{"ieee-le"} formats. + +The data read from the file is returned in @var{val}, and the number of +values read is returned in @code{count} +@end deftypefn + +@deftypefn {Built-in Function} {@var{count} =} fwrite (@var{fid}, @var{data}, @var{precision}, @var{skip}, @var{arch}) +Write data in binary form of type @var{precision} to the specified file +ID @var{fid}, returning the number of values successfully written to the +file. + +The argument @var{data} is a matrix of values that are to be written to +the file. The values are extracted in column-major order. + +The remaining arguments @var{precision}, @var{skip}, and @var{arch} are +optional, and are interpreted as described for @code{fread}. + +The behavior of @code{fwrite} is undefined if the values in @var{data} +are too large to fit in the specified precision. +@end deftypefn + +@node Temporary Files, EOF and Errors, Binary I/O, C-Style I/O Functions +@subsection Temporary Files + +@deftypefn {Built-in Function} {} tmpnam () +Return a unique temporary file name as a string. + +Since the named file is not opened, by @code{tmpnam}, it +is possible (though relatively unlikely) that it will not be available +by the time your program attempts to open it. +@end deftypefn + +@node EOF and Errors, File Positioning, Temporary Files, C-Style I/O Functions +@subsection End of File and Errors + +@deftypefn {Built-in Function} {} feof (@var{fid}) +Return 1 if an end-of-file condition has been encountered for a given +file and 0 otherwise. Note that it will only return 1 if the end of the +file has already been encountered, not if the next read operation will +result in an end-of-file condition. +@end deftypefn + +@deftypefn {Built-in Function} {} ferror (@var{fid}) +Return 1 if an error condition has been encountered for a given file +and 0 otherwise. Note that it will only return 1 if an error has +already been encountered, not if the next operation will result in an +error condition. +@end deftypefn + +@deftypefn {Built-in Function} {} freport () +Print a list of which files have been opened, and whether they are open +for reading, writing, or both. For example, + +@example +@group +freport () + + @print{} number mode name + @print{} + @print{} 0 r stdin + @print{} 1 w stdout + @print{} 2 w stderr + @print{} 3 r myfile +@end group +@end example +@end deftypefn + +@node File Positioning, , EOF and Errors, C-Style I/O Functions +@subsection File Positioning + +Three functions are available for setting and determining the position of +the file pointer for a given file. + +@deftypefn {Built-in Function} {} ftell (@var{fid}) +Return the position of the file pointer as the number of characters +from the beginning of the file @var{fid}. +@end deftypefn + +@deftypefn {Built-in Function} {} fseek (@var{fid}, @var{offset}, @var{origin}) +Set the file pointer to any location within the file @var{fid}. The +pointer is positioned @var{offset} characters from the @var{origin}, +which may be one of the predefined variables @code{SEEK_CUR} (current +position), @code{SEEK_SET} (beginning), or @code{SEEK_END} (end of +file). If @var{origin} is omitted, @code{SEEK_SET} is assumed. The +offset must be zero, or a value returned by @code{ftell} (in which case +@var{origin} must be @code{SEEK_SET}. +@end deftypefn + +@defvr {Built-in Variable} SEEK_SET +@defvrx {Built-in Variable} SEEK_CUR +@defvrx {Built-in Variable} SEEK_END +These variables may be used as the optional third argument for the +function @code{fseek}. +@end defvr + +@deftypefn {Built-in Function} {} frewind (@var{fid}) +Move the file pointer to the beginning of the file @var{fid}, returning +1 for success, and 0 if an error was encountered. It is equivalent to +@code{fseek (@var{fid}, 0, SEEK_SET)}. +@end deftypefn + +The following example stores the current file position in the variable +@code{marker}, moves the pointer to the beginning of the file, reads +four characters, and then returns to the original position. + +@example +marker = ftell (myfile); +frewind (myfile); +fourch = fgets (myfile, 4); +fseek (myfile, marker, SEEK_SET); +@end example + diff --git a/doc/interpreter/linalg.texi b/doc/interpreter/linalg.texi deleted file mode 100644 --- a/doc/interpreter/linalg.texi +++ /dev/null @@ -1,906 +0,0 @@ -@c Copyright (C) 1996, 1997 John W. Eaton -@c This is part of the Octave manual. -@c For copying conditions, see the file gpl.texi. - -@node Linear Algebra, Nonlinear Equations, Arithmetic, Top -@chapter Linear Algebra - -This chapter documents the linear algebra functions of Octave. -Reference material for many of these functions may be found in -Golub and Van Loan, @cite{Matrix Computations, 2nd Ed.}, Johns Hopkins, -1989, and in @cite{@sc{Lapack} Users' Guide}, SIAM, 1992. - -@menu -* Basic Matrix Functions:: -* Matrix Factorizations:: -* Functions of a Matrix:: -@end menu - -@node Basic Matrix Functions, Matrix Factorizations, Linear Algebra, Linear Algebra -@section Basic Matrix Functions - -@deftypefn {Loadable Function} {@var{aa} =} balance (@var{a}, @var{opt}) -@deftypefnx {Loadable Function} {[@var{dd}, @var{aa}] =} balance (@var{a}, @var{opt}) -@deftypefnx {Loadable Function} {[@var{cc}, @var{dd}, @var{aa}, @var{bb]} =} balance (@var{a}, @var{b}, @var{opt}) - -@code{[dd, aa] = balance (a)} returns @code{aa = dd \ a * dd}. -@code{aa} is a matrix whose row and column norms are roughly equal in -magnitude, and @code{dd} = @code{p * d}, where @code{p} is a permutation -matrix and @code{d} is a diagonal matrix of powers of two. This allows -the equilibration to be computed without roundoff. Results of -eigenvalue calculation are typically improved by balancing first. - -@code{[cc, dd, aa, bb] = balance (a, b)} returns @code{aa = cc*a*dd} and -@code{bb = cc*b*dd)}, where @code{aa} and @code{bb} have non-zero -elements of approximately the same magnitude and @code{cc} and @code{dd} -are permuted diagonal matrices as in @code{dd} for the algebraic -eigenvalue problem. - -The eigenvalue balancing option @code{opt} is selected as follows: - -@table @asis -@item @code{"N"}, @code{"n"} -No balancing; arguments copied, transformation(s) set to identity. - -@item @code{"P"}, @code{"p"} -Permute argument(s) to isolate eigenvalues where possible. - -@item @code{"S"}, @code{"s"} -Scale to improve accuracy of computed eigenvalues. - -@item @code{"B"}, @code{"b"} -Permute and scale, in that order. Rows/columns of a (and b) -that are isolated by permutation are not scaled. This is the default -behavior. -@end table - -Algebraic eigenvalue balancing uses standard @sc{Lapack} routines. - -Generalized eigenvalue problem balancing uses Ward's algorithm -(SIAM Journal on Scientific and Statistical Computing, 1981). -@end deftypefn - -@deftypefn {} {} cond (@var{a}) -Compute the (two-norm) condition number of a matrix. @code{cond (a)} is -defined as @code{norm (a) * norm (inv (a))}, and is computed via a -singular value decomposition. -@end deftypefn - -@deftypefn {Loadable Function} {} det (@var{a}) -Compute the determinant of @var{a} using @sc{Linpack}. -@end deftypefn - -@deftypefn {Loadable Function} {@var{lambda} =} eig (@var{a}) -@deftypefnx {Loadable Function} {[@var{v}, @var{lambda}] =} eig (@var{a}) -The eigenvalues (and eigenvectors) of a matrix are computed in a several -step process which begins with a Hessenberg decomposition, followed by a -Schur decomposition, from which the eigenvalues are apparent. The -eigenvectors, when desired, are computed by further manipulations of the -Schur decomposition. -@end deftypefn - -@deftypefn {Loadable Function} {@var{G} =} givens (@var{x}, @var{y}) -@deftypefnx {Loadable Function} {[@var{c}, @var{s}] =} givens (@var{x}, @var{y}) -@iftex -@tex -Return a $2\times 2$ orthogonal matrix -$$ - G = \left[\matrix{c & s\cr -s'& c\cr}\right] -$$ -such that -$$ - G \left[\matrix{x\cr y}\right] = \left[\matrix{\ast\cr 0}\right] -$$ -with $x$ and $y$ scalars. -@end tex -@end iftex -@ifinfo -Return a 2 by 2 orthogonal matrix -@code{@var{G} = [@var{c} @var{s}; -@var{s}' @var{c}]} such that -@code{@var{G} [@var{x}; @var{y}] = [*; 0]} with @var{x} and @var{y} scalars. -@end ifinfo - -For example, - -@example -@group -givens (1, 1) - @result{} 0.70711 0.70711 - -0.70711 0.70711 -@end group -@end example -@end deftypefn - -@deftypefn {Loadable Function} {} inv (@var{a}) -@deftypefnx {Loadable Function} {} inverse (@var{a}) -Compute the inverse of the square matrix @var{a}. -@end deftypefn - -@deftypefn {Function File} {} norm (@var{a}, @var{p}) -Compute the p-norm of the matrix @var{a}. If the second argument is -missing, @code{p = 2} is assumed. - -If @var{a} is a matrix: - -@table @asis -@item @var{p} = @code{1} -1-norm, the largest column sum of @var{a}. - -@item @var{p} = @code{2} -Largest singular value of @var{a}. - -@item @var{p} = @code{Inf} -@cindex infinity norm -Infinity norm, the largest row sum of @var{a}. - -@item @var{p} = @code{"fro"} -@cindex Frobenius norm -Frobenius norm of @var{a}, @code{sqrt (sum (diag (@var{a}' * @var{a})))}. -@end table - -If @var{a} is a vector or a scalar: - -@table @asis -@item @var{p} = @code{Inf} -@code{max (abs (@var{a}))}. - -@item @var{p} = @code{-Inf} -@code{min (abs (@var{a}))}. - -@item other -p-norm of @var{a}, @code{(sum (abs (@var{a}) .^ @var{p})) ^ (1/@var{p})}. -@end table -@end deftypefn - -@deftypefn {Function File} {} null (@var{a}, @var{tol}) -Return an orthonormal basis of the null space of @var{a}. - -The dimension of the null space is taken as the number of singular -values of @var{a} not greater than @var{tol}. If the argument @var{tol} -is missing, it is computed as - -@example -max (size (@var{a})) * max (svd (@var{a})) * eps -@end example -@end deftypefn - -@deftypefn {Function File} {} orth (@var{a}, @var{tol}) -Return an orthonormal basis of the range space of @var{a}. - -The dimension of the range space is taken as the number of singular -values of @var{a} greater than @var{tol}. If the argument @var{tol} is -missing, it is computed as - -@example -max (size (@var{a})) * max (svd (@var{a})) * eps -@end example -@end deftypefn - -@deftypefn {Function File} {} pinv (@var{x}, @var{tol}) -Return the pseudoinverse of @var{x}. Singular values less than -@var{tol} are ignored. - -If the second argument is omitted, it is assumed that - -@example -tol = max (size (@var{x})) * sigma_max (@var{x}) * eps, -@end example - -@noindent -where @code{sigma_max (@var{x})} is the maximal singular value of @var{x}. -@end deftypefn - -@deftypefn {Function File} {} rank (@var{a}, @var{tol}) -Compute the rank of @var{a}, using the singular value decomposition. -The rank is taken to be the number of singular values of @var{a} that -are greater than the specified tolerance @var{tol}. If the second -argument is omitted, it is taken to be - -@example -tol = max (size (@var{a})) * sigma (1) * eps; -@end example - -@noindent -where @code{eps} is machine precision and @code{sigma} is the largest -singular value of @var{a}. -@end deftypefn - -@deftypefn {Function File} {} trace (@var{a}) -Compute the trace of @var{a}, @code{sum (diag (@var{a}))}. -@end deftypefn - -@node Matrix Factorizations, Functions of a Matrix, Basic Matrix Functions, Linear Algebra -@section Matrix Factorizations - -@deftypefn {Loadable Function} {} chol (@var{a}) -@cindex Cholesky factorization -Compute the Cholesky factor, @var{r}, of the symmetric positive definite -matrix @var{a}, where -@iftex -@tex -$ R^T R = A $. -@end tex -@end iftex -@ifinfo - -@example -r' * r = a. -@end example -@end ifinfo -@end deftypefn - -@deftypefn {Loadable Function} {@var{h} =} hess (@var{a}) -@deftypefnx {Loadable Function} {[@var{p}, @var{h}] =} hess (@var{a}) -@cindex Hessenberg decomposition -Compute the Hessenberg decomposition of the matrix @var{a}. - -The Hessenberg decomposition is usually used as the first step in an -eigenvalue computation, but has other applications as well (see Golub, -Nash, and Van Loan, IEEE Transactions on Automatic Control, 1979. The -Hessenberg decomposition is -@iftex -@tex -$$ -A = PHP^T -$$ -where $P$ is a square unitary matrix ($P^HP = I$), and $H$ -is upper Hessenberg ($H_{i,j} = 0, \forall i \ge j+1$). -@end tex -@end iftex -@ifinfo -@code{p * h * p' = a} where @code{p} is a square unitary matrix -(@code{p' * p = I}, using complex-conjugate transposition) and @code{h} -is upper Hessenberg (@code{i >= j+1 => h (i, j) = 0}). -@end ifinfo -@end deftypefn - -@deftypefn {Loadable Function} {[@var{l}, @var{u}, @var{p}] =} lu (@var{a}) -@cindex LU decomposition -Compute the LU decomposition of @var{a}, using subroutines from -@sc{Lapack}. The result is returned in a permuted form, according to -the optional return value @var{p}. For example, given the matrix -@code{a = [1, 2; 3, 4]}, - -@example -[l, u, p] = lu (a) -@end example - -@noindent -returns - -@example -l = - - 1.00000 0.00000 - 0.33333 1.00000 - -u = - - 3.00000 4.00000 - 0.00000 0.66667 - -p = - - 0 1 - 1 0 -@end example -@end deftypefn - -@deftypefn {Loadable Function} {[@var{q}, @var{r}, @var{p}] =} qr (@var{a}) -@cindex QR factorization -Compute the QR factorization of @var{a}, using standard @sc{Lapack} -subroutines. For example, given the matrix @code{a = [1, 2; 3, 4]}, - -@example -[q, r] = qr (a) -@end example - -@noindent -returns - -@example -q = - - -0.31623 -0.94868 - -0.94868 0.31623 - -r = - - -3.16228 -4.42719 - 0.00000 -0.63246 -@end example - -The @code{qr} factorization has applications in the solution of least -squares problems -@iftex -@tex -$$ -\min_x \left\Vert A x - b \right\Vert_2 -$$ -@end tex -@end iftex -@ifinfo - -@example -@code{min norm(A x - b)} -@end example - -@end ifinfo -for overdetermined systems of equations (i.e., -@iftex -@tex -$A$ -@end tex -@end iftex -@ifinfo -@code{a} -@end ifinfo - is a tall, thin matrix). The QR factorization is -@iftex -@tex -$QR = A$ where $Q$ is an orthogonal matrix and $R$ is upper triangular. -@end tex -@end iftex -@ifinfo -@code{q * r = a} where @code{q} is an orthogonal matrix and @code{r} is -upper triangular. -@end ifinfo - -The permuted QR factorization @code{[@var{q}, @var{r}, @var{p}] = -qr (@var{a})} forms the QR factorization such that the diagonal -entries of @code{r} are decreasing in magnitude order. For example, -given the matrix @code{a = [1, 2; 3, 4]}, - -@example -[q, r, pi] = qr(a) -@end example - -@noindent -returns - -@example -q = - - -0.44721 -0.89443 - -0.89443 0.44721 - -r = - - -4.47214 -3.13050 - 0.00000 0.44721 - -p = - - 0 1 - 1 0 -@end example - -The permuted @code{qr} factorization @code{[q, r, p] = qr (a)} -factorization allows the construction of an orthogonal basis of -@code{span (a)}. -@end deftypefn - - -@deftypefn {Function File} {@var{lambda} =} qz (@var{a}, @var{b}) -Generalized eigenvalue problem @math{A x = s B x}, -@var{QZ} decomposition. Three ways to call: -@enumerate -@item @code{lambda = qz(A,B)} - -Computes the generalized eigenvalues @var{lambda} of @math{(A - sB)}. - -@item @code{[AA, BB, Q, Z @{, V, W, lambda@}] = qz (A, B)} - -Computes qz decomposition, generalized eigenvectors, and - generalized eigenvalues of @math{(A - sB)} -@example -@group - A V = B V diag(lambda) - W' A = diag(lambda) W' B - AA = Q'*A*Z, BB = Q'*B*Z with Q, Z orthogonal (unitary)= I -@end group -@end example - -@item @code{[AA,BB,Z@{,lambda@}] = qz(A,B,opt)} - -As in form [2], but allows ordering of generalized eigenpairs - for (e.g.) solution of discrete time algebraic Riccati equations. - Form 3 is not available for complex matrices and does not compute - the generalized eigenvectors V, W, nor the orthogonal matrix Q. -@table @var -@item opt - for ordering eigenvalues of the GEP pencil. The leading block - of the revised pencil contains all eigenvalues that satisfy: -@table @code -@item "N" - = unordered (default) - -@item "S" -= small: leading block has all |lambda| <=1 - -@item "B" - = big: leading block has all |lambda >= 1 - -@item "-" - = negative real part: leading block has all eigenvalues - in the open left half-plant - -@item "+" - = nonnegative real part: leading block has all eigenvalues - in the closed right half-plane -@end table -@end table -@end enumerate - -Note: qz performs permutation balancing, but not scaling (see balance). - Order of output arguments was selected for compatibility with MATLAB - -See also: balance, dare, eig, schur -@end deftypefn - -@deftypefn {Function File} {[@var{aa}, @var{bb}, @var{q}, @var{z}] =} qzhess (@var{a}, @var{b}) -Compute the Hessenberg-triangular decomposition of the matrix pencil -@code{(@var{a}, @var{b})}, returning -@code{@var{aa} = @var{q} * @var{a} * @var{z}}, -@code{@var{bb} = @var{q} * @var{b} * @var{z}}, with @var{q} and @var{z} -orthogonal. For example, - -@example -@group -[aa, bb, q, z] = qzhess ([1, 2; 3, 4], [5, 6; 7, 8]) - @result{} aa = [ -3.02244, -4.41741; 0.92998, 0.69749 ] - @result{} bb = [ -8.60233, -9.99730; 0.00000, -0.23250 ] - @result{} q = [ -0.58124, -0.81373; -0.81373, 0.58124 ] - @result{} z = [ 1, 0; 0, 1 ] -@end group -@end example - -The Hessenberg-triangular decomposition is the first step in -Moler and Stewart's QZ decomposition algorithm. - -Algorithm taken from Golub and Van Loan, @cite{Matrix Computations, 2nd -edition}. -@end deftypefn - -@deftypefn {Loadable Function} {} qzval (@var{a}, @var{b}) -Compute generalized eigenvalues of the matrix pencil -@iftex -@tex -$a - \lambda b$. -@end tex -@end iftex -@ifinfo -@code{@var{a} - lambda @var{b}}. -@end ifinfo - -The arguments @var{a} and @var{b} must be real matrices. -@end deftypefn - -@deftypefn {Loadable Function} {@var{s} =} schur (@var{a}) -@deftypefnx {Loadable Function} {[@var{u}, @var{s}] =} schur (@var{a}, @var{opt}) -@cindex Schur decomposition -The Schur decomposition is used to compute eigenvalues of a -square matrix, and has applications in the solution of algebraic -Riccati equations in control (see @code{are} and @code{dare}). -@code{schur} always returns -@iftex -@tex -$S = U^T A U$ -@end tex -@end iftex -@ifinfo -@code{s = u' * a * u} -@end ifinfo -where -@iftex -@tex -$U$ -@end tex -@end iftex -@ifinfo -@code{u} -@end ifinfo - is a unitary matrix -@iftex -@tex -($U^T U$ is identity) -@end tex -@end iftex -@ifinfo -(@code{u'* u} is identity) -@end ifinfo -and -@iftex -@tex -$S$ -@end tex -@end iftex -@ifinfo -@code{s} -@end ifinfo -is upper triangular. The eigenvalues of -@iftex -@tex -$A$ (and $S$) -@end tex -@end iftex -@ifinfo -@code{a} (and @code{s}) -@end ifinfo -are the diagonal elements of -@iftex -@tex -$S$ -@end tex -@end iftex -@ifinfo -@code{s} -@end ifinfo -If the matrix -@iftex -@tex -$A$ -@end tex -@end iftex -@ifinfo -@code{a} -@end ifinfo -is real, then the real Schur decomposition is computed, in which the -matrix -@iftex -@tex -$U$ -@end tex -@end iftex -@ifinfo -@code{u} -@end ifinfo -is orthogonal and -@iftex -@tex -$S$ -@end tex -@end iftex -@ifinfo -@code{s} -@end ifinfo -is block upper triangular -with blocks of size at most -@iftex -@tex -$2\times 2$ -@end tex -@end iftex -@ifinfo -@code{2 x 2} -@end ifinfo -blocks along the diagonal. The diagonal elements of -@iftex -@tex -$S$ -@end tex -@end iftex -@ifinfo -@code{s} -@end ifinfo -(or the eigenvalues of the -@iftex -@tex -$2\times 2$ -@end tex -@end iftex -@ifinfo -@code{2 x 2} -@end ifinfo -blocks, when -appropriate) are the eigenvalues of -@iftex -@tex -$A$ -@end tex -@end iftex -@ifinfo -@code{a} -@end ifinfo -and -@iftex -@tex -$S$. -@end tex -@end iftex -@ifinfo -@code{s}. -@end ifinfo - -The eigenvalues are optionally ordered along the diagonal according to -the value of @code{opt}. @code{opt = "a"} indicates that all -eigenvalues with negative real parts should be moved to the leading -block of -@iftex -@tex -$S$ -@end tex -@end iftex -@ifinfo -@code{s} -@end ifinfo -(used in @code{are}), @code{opt = "d"} indicates that all eigenvalues -with magnitude less than one should be moved to the leading block of -@iftex -@tex -$S$ -@end tex -@end iftex -@ifinfo -@code{s} -@end ifinfo -(used in @code{dare}), and @code{opt = "u"}, the default, indicates that -no ordering of eigenvalues should occur. The leading -@iftex -@tex -$k$ -@end tex -@end iftex -@ifinfo -@code{k} -@end ifinfo -columns of -@iftex -@tex -$U$ -@end tex -@end iftex -@ifinfo -@code{u} -@end ifinfo -always span the -@iftex -@tex -$A$-invariant -@end tex -@end iftex -@ifinfo -@code{a}-invariant -@end ifinfo -subspace corresponding to the -@iftex -@tex -$k$ -@end tex -@end iftex -@ifinfo -@code{k} -@end ifinfo -leading eigenvalues of -@iftex -@tex -$S$. -@end tex -@end iftex -@ifinfo -@code{s}. -@end ifinfo -@end deftypefn - -@deftypefn {Loadable Function} {@var{s} =} svd (@var{a}) -@deftypefnx {Loadable Function} {[@var{u}, @var{s}, @var{v}] =} svd (@var{a}) -@cindex singular value decomposition -Compute the singular value decomposition of @var{a} -@iftex -@tex -$$ - A = U\Sigma V^H -$$ -@end tex -@end iftex -@ifinfo - -@example -a = u * sigma * v' -@end example -@end ifinfo - -The function @code{svd} normally returns the vector of singular values. -If asked for three return values, it computes -@iftex -@tex -$U$, $S$, and $V$. -@end tex -@end iftex -@ifinfo -U, S, and V. -@end ifinfo -For example, - -@example -svd (hilb (3)) -@end example - -@noindent -returns - -@example -ans = - - 1.4083189 - 0.1223271 - 0.0026873 -@end example - -@noindent -and - -@example -[u, s, v] = svd (hilb (3)) -@end example - -@noindent -returns - -@example -u = - - -0.82704 0.54745 0.12766 - -0.45986 -0.52829 -0.71375 - -0.32330 -0.64901 0.68867 - -s = - - 1.40832 0.00000 0.00000 - 0.00000 0.12233 0.00000 - 0.00000 0.00000 0.00269 - -v = - - -0.82704 0.54745 0.12766 - -0.45986 -0.52829 -0.71375 - -0.32330 -0.64901 0.68867 -@end example - -If given a second argument, @code{svd} returns an economy-sized -decomposition, eliminating the unnecessary rows or columns of @var{u} or -@var{v}. -@end deftypefn - -@node Functions of a Matrix, , Matrix Factorizations, Linear Algebra -@section Functions of a Matrix - -@deftypefn {Loadable Function} {} expm (@var{a}) -Return the exponential of a matrix, defined as the infinite Taylor -series -@iftex -@tex -$$ - \exp (A) = I + A + {A^2 \over 2!} + {A^3 \over 3!} + \cdots -$$ -@end tex -@end iftex -@ifinfo - -@example -expm(a) = I + a + a^2/2! + a^3/3! + ... -@end example - -@end ifinfo -The Taylor series is @emph{not} the way to compute the matrix -exponential; see Moler and Van Loan, @cite{Nineteen Dubious Ways to -Compute the Exponential of a Matrix}, SIAM Review, 1978. This routine -uses Ward's diagonal -@iftex -@tex -Pad\'e -@end tex -@end iftex -@ifinfo -Pade' -@end ifinfo -approximation method with three step preconditioning (SIAM Journal on -Numerical Analysis, 1977). Diagonal -@iftex -@tex -Pad\'e -@end tex -@end iftex -@ifinfo -Pade' -@end ifinfo - approximations are rational polynomials of matrices -@iftex -@tex -$D_q(a)^{-1}N_q(a)$ -@end tex -@end iftex -@ifinfo - -@example - -1 -D (a) N (a) -@end example - -@end ifinfo - whose Taylor series matches the first -@iftex -@tex -$2 q + 1 $ -@end tex -@end iftex -@ifinfo -@code{2q+1} -@end ifinfo -terms of the Taylor series above; direct evaluation of the Taylor series -(with the same preconditioning steps) may be desirable in lieu of the -@iftex -@tex -Pad\'e -@end tex -@end iftex -@ifinfo -Pade' -@end ifinfo -approximation when -@iftex -@tex -$D_q(a)$ -@end tex -@end iftex -@ifinfo -@code{Dq(a)} -@end ifinfo -is ill-conditioned. -@end deftypefn - -@deftypefn {Loadable Function} {} logm (@var{a}) -Compute the matrix logarithm of the square matrix @var{a}. Note that -this is currently implemented in terms of an eigenvalue expansion and -needs to be improved to be more robust. -@end deftypefn - -@deftypefn {Loadable Function} {} sqrtm (@var{a}) -Compute the matrix square root of the square matrix @var{a}. Note that -this is currently implemented in terms of an eigenvalue expansion and -needs to be improved to be more robust. -@end deftypefn - -@deftypefn {Function File} {} kron (@var{a}, @var{b}) -Form the kronecker product of two matrices, defined block by block as - -@example -x = [a(i, j) b] -@end example - -For example, - -@example -@group -kron (1:4, ones (3, 1)) - @result{} 1 2 3 4 - 1 2 3 4 - 1 2 3 4 -@end group -@end example -@end deftypefn - -@deftypefn {Loadable Function} {@var{x} =} syl (@var{a}, @var{b}, @var{c}) -Solve the Sylvester equation -@iftex -@tex -$$ - A X + X B + C = 0 -$$ -@end tex -@end iftex -@ifinfo - -@example -A X + X B + C = 0 -@end example -@end ifinfo -using standard @sc{Lapack} subroutines. For example, - -@example -@group -syl ([1, 2; 3, 4], [5, 6; 7, 8], [9, 10; 11, 12]) - @result{} [ -0.50000, -0.66667; -0.66667, -0.50000 ] -@end group -@end example -@end deftypefn diff --git a/doc/interpreter/linalg.txi b/doc/interpreter/linalg.txi new file mode 100644 --- /dev/null +++ b/doc/interpreter/linalg.txi @@ -0,0 +1,906 @@ +@c Copyright (C) 1996, 1997 John W. Eaton +@c This is part of the Octave manual. +@c For copying conditions, see the file gpl.texi. + +@node Linear Algebra, Nonlinear Equations, Arithmetic, Top +@chapter Linear Algebra + +This chapter documents the linear algebra functions of Octave. +Reference material for many of these functions may be found in +Golub and Van Loan, @cite{Matrix Computations, 2nd Ed.}, Johns Hopkins, +1989, and in @cite{@sc{Lapack} Users' Guide}, SIAM, 1992. + +@menu +* Basic Matrix Functions:: +* Matrix Factorizations:: +* Functions of a Matrix:: +@end menu + +@node Basic Matrix Functions, Matrix Factorizations, Linear Algebra, Linear Algebra +@section Basic Matrix Functions + +@deftypefn {Loadable Function} {@var{aa} =} balance (@var{a}, @var{opt}) +@deftypefnx {Loadable Function} {[@var{dd}, @var{aa}] =} balance (@var{a}, @var{opt}) +@deftypefnx {Loadable Function} {[@var{cc}, @var{dd}, @var{aa}, @var{bb]} =} balance (@var{a}, @var{b}, @var{opt}) + +@code{[dd, aa] = balance (a)} returns @code{aa = dd \ a * dd}. +@code{aa} is a matrix whose row and column norms are roughly equal in +magnitude, and @code{dd} = @code{p * d}, where @code{p} is a permutation +matrix and @code{d} is a diagonal matrix of powers of two. This allows +the equilibration to be computed without roundoff. Results of +eigenvalue calculation are typically improved by balancing first. + +@code{[cc, dd, aa, bb] = balance (a, b)} returns @code{aa = cc*a*dd} and +@code{bb = cc*b*dd)}, where @code{aa} and @code{bb} have non-zero +elements of approximately the same magnitude and @code{cc} and @code{dd} +are permuted diagonal matrices as in @code{dd} for the algebraic +eigenvalue problem. + +The eigenvalue balancing option @code{opt} is selected as follows: + +@table @asis +@item @code{"N"}, @code{"n"} +No balancing; arguments copied, transformation(s) set to identity. + +@item @code{"P"}, @code{"p"} +Permute argument(s) to isolate eigenvalues where possible. + +@item @code{"S"}, @code{"s"} +Scale to improve accuracy of computed eigenvalues. + +@item @code{"B"}, @code{"b"} +Permute and scale, in that order. Rows/columns of a (and b) +that are isolated by permutation are not scaled. This is the default +behavior. +@end table + +Algebraic eigenvalue balancing uses standard @sc{Lapack} routines. + +Generalized eigenvalue problem balancing uses Ward's algorithm +(SIAM Journal on Scientific and Statistical Computing, 1981). +@end deftypefn + +@deftypefn {} {} cond (@var{a}) +Compute the (two-norm) condition number of a matrix. @code{cond (a)} is +defined as @code{norm (a) * norm (inv (a))}, and is computed via a +singular value decomposition. +@end deftypefn + +@deftypefn {Loadable Function} {} det (@var{a}) +Compute the determinant of @var{a} using @sc{Linpack}. +@end deftypefn + +@deftypefn {Loadable Function} {@var{lambda} =} eig (@var{a}) +@deftypefnx {Loadable Function} {[@var{v}, @var{lambda}] =} eig (@var{a}) +The eigenvalues (and eigenvectors) of a matrix are computed in a several +step process which begins with a Hessenberg decomposition, followed by a +Schur decomposition, from which the eigenvalues are apparent. The +eigenvectors, when desired, are computed by further manipulations of the +Schur decomposition. +@end deftypefn + +@deftypefn {Loadable Function} {@var{G} =} givens (@var{x}, @var{y}) +@deftypefnx {Loadable Function} {[@var{c}, @var{s}] =} givens (@var{x}, @var{y}) +@iftex +@tex +Return a $2\times 2$ orthogonal matrix +$$ + G = \left[\matrix{c & s\cr -s'& c\cr}\right] +$$ +such that +$$ + G \left[\matrix{x\cr y}\right] = \left[\matrix{\ast\cr 0}\right] +$$ +with $x$ and $y$ scalars. +@end tex +@end iftex +@ifinfo +Return a 2 by 2 orthogonal matrix +@code{@var{G} = [@var{c} @var{s}; -@var{s}' @var{c}]} such that +@code{@var{G} [@var{x}; @var{y}] = [*; 0]} with @var{x} and @var{y} scalars. +@end ifinfo + +For example, + +@example +@group +givens (1, 1) + @result{} 0.70711 0.70711 + -0.70711 0.70711 +@end group +@end example +@end deftypefn + +@deftypefn {Loadable Function} {} inv (@var{a}) +@deftypefnx {Loadable Function} {} inverse (@var{a}) +Compute the inverse of the square matrix @var{a}. +@end deftypefn + +@deftypefn {Function File} {} norm (@var{a}, @var{p}) +Compute the p-norm of the matrix @var{a}. If the second argument is +missing, @code{p = 2} is assumed. + +If @var{a} is a matrix: + +@table @asis +@item @var{p} = @code{1} +1-norm, the largest column sum of @var{a}. + +@item @var{p} = @code{2} +Largest singular value of @var{a}. + +@item @var{p} = @code{Inf} +@cindex infinity norm +Infinity norm, the largest row sum of @var{a}. + +@item @var{p} = @code{"fro"} +@cindex Frobenius norm +Frobenius norm of @var{a}, @code{sqrt (sum (diag (@var{a}' * @var{a})))}. +@end table + +If @var{a} is a vector or a scalar: + +@table @asis +@item @var{p} = @code{Inf} +@code{max (abs (@var{a}))}. + +@item @var{p} = @code{-Inf} +@code{min (abs (@var{a}))}. + +@item other +p-norm of @var{a}, @code{(sum (abs (@var{a}) .^ @var{p})) ^ (1/@var{p})}. +@end table +@end deftypefn + +@deftypefn {Function File} {} null (@var{a}, @var{tol}) +Return an orthonormal basis of the null space of @var{a}. + +The dimension of the null space is taken as the number of singular +values of @var{a} not greater than @var{tol}. If the argument @var{tol} +is missing, it is computed as + +@example +max (size (@var{a})) * max (svd (@var{a})) * eps +@end example +@end deftypefn + +@deftypefn {Function File} {} orth (@var{a}, @var{tol}) +Return an orthonormal basis of the range space of @var{a}. + +The dimension of the range space is taken as the number of singular +values of @var{a} greater than @var{tol}. If the argument @var{tol} is +missing, it is computed as + +@example +max (size (@var{a})) * max (svd (@var{a})) * eps +@end example +@end deftypefn + +@deftypefn {Function File} {} pinv (@var{x}, @var{tol}) +Return the pseudoinverse of @var{x}. Singular values less than +@var{tol} are ignored. + +If the second argument is omitted, it is assumed that + +@example +tol = max (size (@var{x})) * sigma_max (@var{x}) * eps, +@end example + +@noindent +where @code{sigma_max (@var{x})} is the maximal singular value of @var{x}. +@end deftypefn + +@deftypefn {Function File} {} rank (@var{a}, @var{tol}) +Compute the rank of @var{a}, using the singular value decomposition. +The rank is taken to be the number of singular values of @var{a} that +are greater than the specified tolerance @var{tol}. If the second +argument is omitted, it is taken to be + +@example +tol = max (size (@var{a})) * sigma (1) * eps; +@end example + +@noindent +where @code{eps} is machine precision and @code{sigma} is the largest +singular value of @var{a}. +@end deftypefn + +@deftypefn {Function File} {} trace (@var{a}) +Compute the trace of @var{a}, @code{sum (diag (@var{a}))}. +@end deftypefn + +@node Matrix Factorizations, Functions of a Matrix, Basic Matrix Functions, Linear Algebra +@section Matrix Factorizations + +@deftypefn {Loadable Function} {} chol (@var{a}) +@cindex Cholesky factorization +Compute the Cholesky factor, @var{r}, of the symmetric positive definite +matrix @var{a}, where +@iftex +@tex +$ R^T R = A $. +@end tex +@end iftex +@ifinfo + +@example +r' * r = a. +@end example +@end ifinfo +@end deftypefn + +@deftypefn {Loadable Function} {@var{h} =} hess (@var{a}) +@deftypefnx {Loadable Function} {[@var{p}, @var{h}] =} hess (@var{a}) +@cindex Hessenberg decomposition +Compute the Hessenberg decomposition of the matrix @var{a}. + +The Hessenberg decomposition is usually used as the first step in an +eigenvalue computation, but has other applications as well (see Golub, +Nash, and Van Loan, IEEE Transactions on Automatic Control, 1979. The +Hessenberg decomposition is +@iftex +@tex +$$ +A = PHP^T +$$ +where $P$ is a square unitary matrix ($P^HP = I$), and $H$ +is upper Hessenberg ($H_{i,j} = 0, \forall i \ge j+1$). +@end tex +@end iftex +@ifinfo +@code{p * h * p' = a} where @code{p} is a square unitary matrix +(@code{p' * p = I}, using complex-conjugate transposition) and @code{h} +is upper Hessenberg (@code{i >= j+1 => h (i, j) = 0}). +@end ifinfo +@end deftypefn + +@deftypefn {Loadable Function} {[@var{l}, @var{u}, @var{p}] =} lu (@var{a}) +@cindex LU decomposition +Compute the LU decomposition of @var{a}, using subroutines from +@sc{Lapack}. The result is returned in a permuted form, according to +the optional return value @var{p}. For example, given the matrix +@code{a = [1, 2; 3, 4]}, + +@example +[l, u, p] = lu (a) +@end example + +@noindent +returns + +@example +l = + + 1.00000 0.00000 + 0.33333 1.00000 + +u = + + 3.00000 4.00000 + 0.00000 0.66667 + +p = + + 0 1 + 1 0 +@end example +@end deftypefn + +@deftypefn {Loadable Function} {[@var{q}, @var{r}, @var{p}] =} qr (@var{a}) +@cindex QR factorization +Compute the QR factorization of @var{a}, using standard @sc{Lapack} +subroutines. For example, given the matrix @code{a = [1, 2; 3, 4]}, + +@example +[q, r] = qr (a) +@end example + +@noindent +returns + +@example +q = + + -0.31623 -0.94868 + -0.94868 0.31623 + +r = + + -3.16228 -4.42719 + 0.00000 -0.63246 +@end example + +The @code{qr} factorization has applications in the solution of least +squares problems +@iftex +@tex +$$ +\min_x \left\Vert A x - b \right\Vert_2 +$$ +@end tex +@end iftex +@ifinfo + +@example +@code{min norm(A x - b)} +@end example + +@end ifinfo +for overdetermined systems of equations (i.e., +@iftex +@tex +$A$ +@end tex +@end iftex +@ifinfo +@code{a} +@end ifinfo + is a tall, thin matrix). The QR factorization is +@iftex +@tex +$QR = A$ where $Q$ is an orthogonal matrix and $R$ is upper triangular. +@end tex +@end iftex +@ifinfo +@code{q * r = a} where @code{q} is an orthogonal matrix and @code{r} is +upper triangular. +@end ifinfo + +The permuted QR factorization @code{[@var{q}, @var{r}, @var{p}] = +qr (@var{a})} forms the QR factorization such that the diagonal +entries of @code{r} are decreasing in magnitude order. For example, +given the matrix @code{a = [1, 2; 3, 4]}, + +@example +[q, r, pi] = qr(a) +@end example + +@noindent +returns + +@example +q = + + -0.44721 -0.89443 + -0.89443 0.44721 + +r = + + -4.47214 -3.13050 + 0.00000 0.44721 + +p = + + 0 1 + 1 0 +@end example + +The permuted @code{qr} factorization @code{[q, r, p] = qr (a)} +factorization allows the construction of an orthogonal basis of +@code{span (a)}. +@end deftypefn + + +@deftypefn {Function File} {@var{lambda} =} qz (@var{a}, @var{b}) +Generalized eigenvalue problem @math{A x = s B x}, +@var{QZ} decomposition. Three ways to call: +@enumerate +@item @code{lambda = qz(A,B)} + +Computes the generalized eigenvalues @var{lambda} of @math{(A - sB)}. + +@item @code{[AA, BB, Q, Z @{, V, W, lambda@}] = qz (A, B)} + +Computes qz decomposition, generalized eigenvectors, and + generalized eigenvalues of @math{(A - sB)} +@example +@group + A V = B V diag(lambda) + W' A = diag(lambda) W' B + AA = Q'*A*Z, BB = Q'*B*Z with Q, Z orthogonal (unitary)= I +@end group +@end example + +@item @code{[AA,BB,Z@{,lambda@}] = qz(A,B,opt)} + +As in form [2], but allows ordering of generalized eigenpairs + for (e.g.) solution of discrete time algebraic Riccati equations. + Form 3 is not available for complex matrices and does not compute + the generalized eigenvectors V, W, nor the orthogonal matrix Q. +@table @var +@item opt + for ordering eigenvalues of the GEP pencil. The leading block + of the revised pencil contains all eigenvalues that satisfy: +@table @code +@item "N" + = unordered (default) + +@item "S" += small: leading block has all |lambda| <=1 + +@item "B" + = big: leading block has all |lambda >= 1 + +@item "-" + = negative real part: leading block has all eigenvalues + in the open left half-plant + +@item "+" + = nonnegative real part: leading block has all eigenvalues + in the closed right half-plane +@end table +@end table +@end enumerate + +Note: qz performs permutation balancing, but not scaling (see balance). + Order of output arguments was selected for compatibility with MATLAB + +See also: balance, dare, eig, schur +@end deftypefn + +@deftypefn {Function File} {[@var{aa}, @var{bb}, @var{q}, @var{z}] =} qzhess (@var{a}, @var{b}) +Compute the Hessenberg-triangular decomposition of the matrix pencil +@code{(@var{a}, @var{b})}, returning +@code{@var{aa} = @var{q} * @var{a} * @var{z}}, +@code{@var{bb} = @var{q} * @var{b} * @var{z}}, with @var{q} and @var{z} +orthogonal. For example, + +@example +@group +[aa, bb, q, z] = qzhess ([1, 2; 3, 4], [5, 6; 7, 8]) + @result{} aa = [ -3.02244, -4.41741; 0.92998, 0.69749 ] + @result{} bb = [ -8.60233, -9.99730; 0.00000, -0.23250 ] + @result{} q = [ -0.58124, -0.81373; -0.81373, 0.58124 ] + @result{} z = [ 1, 0; 0, 1 ] +@end group +@end example + +The Hessenberg-triangular decomposition is the first step in +Moler and Stewart's QZ decomposition algorithm. + +Algorithm taken from Golub and Van Loan, @cite{Matrix Computations, 2nd +edition}. +@end deftypefn + +@deftypefn {Loadable Function} {} qzval (@var{a}, @var{b}) +Compute generalized eigenvalues of the matrix pencil +@iftex +@tex +$a - \lambda b$. +@end tex +@end iftex +@ifinfo +@code{@var{a} - lambda @var{b}}. +@end ifinfo + +The arguments @var{a} and @var{b} must be real matrices. +@end deftypefn + +@deftypefn {Loadable Function} {@var{s} =} schur (@var{a}) +@deftypefnx {Loadable Function} {[@var{u}, @var{s}] =} schur (@var{a}, @var{opt}) +@cindex Schur decomposition +The Schur decomposition is used to compute eigenvalues of a +square matrix, and has applications in the solution of algebraic +Riccati equations in control (see @code{are} and @code{dare}). +@code{schur} always returns +@iftex +@tex +$S = U^T A U$ +@end tex +@end iftex +@ifinfo +@code{s = u' * a * u} +@end ifinfo +where +@iftex +@tex +$U$ +@end tex +@end iftex +@ifinfo +@code{u} +@end ifinfo + is a unitary matrix +@iftex +@tex +($U^T U$ is identity) +@end tex +@end iftex +@ifinfo +(@code{u'* u} is identity) +@end ifinfo +and +@iftex +@tex +$S$ +@end tex +@end iftex +@ifinfo +@code{s} +@end ifinfo +is upper triangular. The eigenvalues of +@iftex +@tex +$A$ (and $S$) +@end tex +@end iftex +@ifinfo +@code{a} (and @code{s}) +@end ifinfo +are the diagonal elements of +@iftex +@tex +$S$ +@end tex +@end iftex +@ifinfo +@code{s} +@end ifinfo +If the matrix +@iftex +@tex +$A$ +@end tex +@end iftex +@ifinfo +@code{a} +@end ifinfo +is real, then the real Schur decomposition is computed, in which the +matrix +@iftex +@tex +$U$ +@end tex +@end iftex +@ifinfo +@code{u} +@end ifinfo +is orthogonal and +@iftex +@tex +$S$ +@end tex +@end iftex +@ifinfo +@code{s} +@end ifinfo +is block upper triangular +with blocks of size at most +@iftex +@tex +$2\times 2$ +@end tex +@end iftex +@ifinfo +@code{2 x 2} +@end ifinfo +blocks along the diagonal. The diagonal elements of +@iftex +@tex +$S$ +@end tex +@end iftex +@ifinfo +@code{s} +@end ifinfo +(or the eigenvalues of the +@iftex +@tex +$2\times 2$ +@end tex +@end iftex +@ifinfo +@code{2 x 2} +@end ifinfo +blocks, when +appropriate) are the eigenvalues of +@iftex +@tex +$A$ +@end tex +@end iftex +@ifinfo +@code{a} +@end ifinfo +and +@iftex +@tex +$S$. +@end tex +@end iftex +@ifinfo +@code{s}. +@end ifinfo + +The eigenvalues are optionally ordered along the diagonal according to +the value of @code{opt}. @code{opt = "a"} indicates that all +eigenvalues with negative real parts should be moved to the leading +block of +@iftex +@tex +$S$ +@end tex +@end iftex +@ifinfo +@code{s} +@end ifinfo +(used in @code{are}), @code{opt = "d"} indicates that all eigenvalues +with magnitude less than one should be moved to the leading block of +@iftex +@tex +$S$ +@end tex +@end iftex +@ifinfo +@code{s} +@end ifinfo +(used in @code{dare}), and @code{opt = "u"}, the default, indicates that +no ordering of eigenvalues should occur. The leading +@iftex +@tex +$k$ +@end tex +@end iftex +@ifinfo +@code{k} +@end ifinfo +columns of +@iftex +@tex +$U$ +@end tex +@end iftex +@ifinfo +@code{u} +@end ifinfo +always span the +@iftex +@tex +$A$-invariant +@end tex +@end iftex +@ifinfo +@code{a}-invariant +@end ifinfo +subspace corresponding to the +@iftex +@tex +$k$ +@end tex +@end iftex +@ifinfo +@code{k} +@end ifinfo +leading eigenvalues of +@iftex +@tex +$S$. +@end tex +@end iftex +@ifinfo +@code{s}. +@end ifinfo +@end deftypefn + +@deftypefn {Loadable Function} {@var{s} =} svd (@var{a}) +@deftypefnx {Loadable Function} {[@var{u}, @var{s}, @var{v}] =} svd (@var{a}) +@cindex singular value decomposition +Compute the singular value decomposition of @var{a} +@iftex +@tex +$$ + A = U\Sigma V^H +$$ +@end tex +@end iftex +@ifinfo + +@example +a = u * sigma * v' +@end example +@end ifinfo + +The function @code{svd} normally returns the vector of singular values. +If asked for three return values, it computes +@iftex +@tex +$U$, $S$, and $V$. +@end tex +@end iftex +@ifinfo +U, S, and V. +@end ifinfo +For example, + +@example +svd (hilb (3)) +@end example + +@noindent +returns + +@example +ans = + + 1.4083189 + 0.1223271 + 0.0026873 +@end example + +@noindent +and + +@example +[u, s, v] = svd (hilb (3)) +@end example + +@noindent +returns + +@example +u = + + -0.82704 0.54745 0.12766 + -0.45986 -0.52829 -0.71375 + -0.32330 -0.64901 0.68867 + +s = + + 1.40832 0.00000 0.00000 + 0.00000 0.12233 0.00000 + 0.00000 0.00000 0.00269 + +v = + + -0.82704 0.54745 0.12766 + -0.45986 -0.52829 -0.71375 + -0.32330 -0.64901 0.68867 +@end example + +If given a second argument, @code{svd} returns an economy-sized +decomposition, eliminating the unnecessary rows or columns of @var{u} or +@var{v}. +@end deftypefn + +@node Functions of a Matrix, , Matrix Factorizations, Linear Algebra +@section Functions of a Matrix + +@deftypefn {Loadable Function} {} expm (@var{a}) +Return the exponential of a matrix, defined as the infinite Taylor +series +@iftex +@tex +$$ + \exp (A) = I + A + {A^2 \over 2!} + {A^3 \over 3!} + \cdots +$$ +@end tex +@end iftex +@ifinfo + +@example +expm(a) = I + a + a^2/2! + a^3/3! + ... +@end example + +@end ifinfo +The Taylor series is @emph{not} the way to compute the matrix +exponential; see Moler and Van Loan, @cite{Nineteen Dubious Ways to +Compute the Exponential of a Matrix}, SIAM Review, 1978. This routine +uses Ward's diagonal +@iftex +@tex +Pad\'e +@end tex +@end iftex +@ifinfo +Pade' +@end ifinfo +approximation method with three step preconditioning (SIAM Journal on +Numerical Analysis, 1977). Diagonal +@iftex +@tex +Pad\'e +@end tex +@end iftex +@ifinfo +Pade' +@end ifinfo + approximations are rational polynomials of matrices +@iftex +@tex +$D_q(a)^{-1}N_q(a)$ +@end tex +@end iftex +@ifinfo + +@example + -1 +D (a) N (a) +@end example + +@end ifinfo + whose Taylor series matches the first +@iftex +@tex +$2 q + 1 $ +@end tex +@end iftex +@ifinfo +@code{2q+1} +@end ifinfo +terms of the Taylor series above; direct evaluation of the Taylor series +(with the same preconditioning steps) may be desirable in lieu of the +@iftex +@tex +Pad\'e +@end tex +@end iftex +@ifinfo +Pade' +@end ifinfo +approximation when +@iftex +@tex +$D_q(a)$ +@end tex +@end iftex +@ifinfo +@code{Dq(a)} +@end ifinfo +is ill-conditioned. +@end deftypefn + +@deftypefn {Loadable Function} {} logm (@var{a}) +Compute the matrix logarithm of the square matrix @var{a}. Note that +this is currently implemented in terms of an eigenvalue expansion and +needs to be improved to be more robust. +@end deftypefn + +@deftypefn {Loadable Function} {} sqrtm (@var{a}) +Compute the matrix square root of the square matrix @var{a}. Note that +this is currently implemented in terms of an eigenvalue expansion and +needs to be improved to be more robust. +@end deftypefn + +@deftypefn {Function File} {} kron (@var{a}, @var{b}) +Form the kronecker product of two matrices, defined block by block as + +@example +x = [a(i, j) b] +@end example + +For example, + +@example +@group +kron (1:4, ones (3, 1)) + @result{} 1 2 3 4 + 1 2 3 4 + 1 2 3 4 +@end group +@end example +@end deftypefn + +@deftypefn {Loadable Function} {@var{x} =} syl (@var{a}, @var{b}, @var{c}) +Solve the Sylvester equation +@iftex +@tex +$$ + A X + X B + C = 0 +$$ +@end tex +@end iftex +@ifinfo + +@example +A X + X B + C = 0 +@end example +@end ifinfo +using standard @sc{Lapack} subroutines. For example, + +@example +@group +syl ([1, 2; 3, 4], [5, 6; 7, 8], [9, 10; 11, 12]) + @result{} [ -0.50000, -0.66667; -0.66667, -0.50000 ] +@end group +@end example +@end deftypefn diff --git a/doc/interpreter/matrix.texi b/doc/interpreter/matrix.texi deleted file mode 100644 --- a/doc/interpreter/matrix.texi +++ /dev/null @@ -1,792 +0,0 @@ -@c Copyright (C) 1996, 1997 John W. Eaton -@c This is part of the Octave manual. -@c For copying conditions, see the file gpl.texi. - -@node Matrix Manipulation, Arithmetic, Plotting, Top -@chapter Matrix Manipulation - -There are a number of functions available for checking to see if the -elements of a matrix meet some condition, and for rearranging the -elements of a matrix. For example, Octave can easily tell you if all -the elements of a matrix are finite, or are less than some specified -value. Octave can also rotate the elements, extract the upper- or -lower-triangular parts, or sort the columns of a matrix. - -@menu -* Finding Elements and Checking Conditions:: -* Rearranging Matrices:: -* Special Utility Matrices:: -* Famous Matrices:: -@end menu - -@node Finding Elements and Checking Conditions, Rearranging Matrices, Matrix Manipulation, Matrix Manipulation -@section Finding Elements and Checking Conditions - -The functions @code{any} and @code{all} are useful for determining -whether any or all of the elements of a matrix satisfy some condition. -The @code{find} function is also useful in determining which elements of -a matrix meet a specified condition. - -@deftypefn {Built-in Function} {} any (@var{x}) -For a vector argument, return 1 if any element of the vector is -nonzero. - -For a matrix argument, return a row vector of ones and -zeros with each element indicating whether any of the elements of the -corresponding column of the matrix are nonzero. For example, - -@example -@group -any (eye (2, 4)) - @result{} [ 1, 1, 0, 0 ] -@end group -@end example - -To see if any of the elements of a matrix are nonzero, you can use a -statement like - -@example -any (any (a)) -@end example -@end deftypefn - -@deftypefn {Built-in Function} {} all (@var{x}) -The function @code{all} behaves like the function @code{any}, except -that it returns true only if all the elements of a vector, or all the -elements in a column of a matrix, are nonzero. -@end deftypefn - -Since the comparison operators (@pxref{Comparison Ops}) return matrices -of ones and zeros, it is easy to test a matrix for many things, not just -whether the elements are nonzero. For example, - -@example -@group -all (all (rand (5) < 0.9)) - @result{} 0 -@end group -@end example - -@noindent -tests a random 5 by 5 matrix to see if all of its elements are less -than 0.9. - -Note that in conditional contexts (like the test clause of @code{if} and -@code{while} statements) Octave treats the test as if you had typed -@code{all (all (condition))}. - -@deftypefn {Function File} {[@var{err}, @var{y1}, ...] =} common_size (@var{x1}, ...) -Determine if all input arguments are either scalar or of common -size. If so, @var{err} is zero, and @var{yi} is a matrix of the -common size with all entries equal to @var{xi} if this is a scalar or -@var{xi} otherwise. If the inputs cannot be brought to a common size, -errorcode is 1, and @var{yi} is @var{xi}. For example, - -@example -@group -[errorcode, a, b] = common_size ([1 2; 3 4], 5) - @result{} errorcode = 0 - @result{} a = [ 1, 2; 3, 4 ] - @result{} b = [ 5, 5; 5, 5 ] -@end group -@end example - -@noindent -This is useful for implementing functions where arguments can either -be scalars or of common size. -@end deftypefn - -@deftypefn {Function File} {} diff (@var{x}, @var{k}) -If @var{x} is a vector of length @var{n}, @code{diff (@var{x})} is the -vector of first differences -@iftex -@tex - $x_2 - x_1, \ldots{}, x_n - x_{n-1}$. -@end tex -@end iftex -@ifinfo - @var{x}(2) - @var{x}(1), @dots{}, @var{x}(n) - @var{x}(n-1). -@end ifinfo - -If @var{x} is a matrix, @code{diff (@var{x})} is the matrix of column -differences. - -The second argument is optional. If supplied, @code{diff (@var{x}, -@var{k})}, where @var{k} is a nonnegative integer, returns the -@var{k}-th differences. -@end deftypefn - -@deftypefn {Mapping Function} {} isinf (@var{x}) -Return 1 for elements of @var{x} that are infinite and zero -otherwise. For example, - -@example -@group -isinf ([13, Inf, NaN]) - @result{} [ 0, 1, 0 ] -@end group -@end example -@end deftypefn - -@deftypefn {Mapping Function} {} isnan (@var{x}) -Return 1 for elements of @var{x} that are NaN values and zero -otherwise. For example, - -@example -@group -isnan ([13, Inf, NaN]) - @result{} [ 0, 0, 1 ] -@end group -@end example -@end deftypefn - -@deftypefn {Mapping Function} {} finite (@var{x}) -Return 1 for elements of @var{x} that are NaN values and zero -otherwise. For example, - -@example -@group -finite ([13, Inf, NaN]) - @result{} [ 1, 0, 0 ] -@end group -@end example -@end deftypefn - -@deftypefn {Loadable Function} {} find (@var{x}) -Return a vector of indices of nonzero elements of a matrix. To obtain a -single index for each matrix element, Octave pretends that the columns -of a matrix form one long vector (like Fortran arrays are stored). For -example, - -@example -@group -find (eye (2)) - @result{} [ 1; 4 ] -@end group -@end example - -If two outputs are requested, @code{find} returns the row and column -indices of nonzero elements of a matrix. For example, - -@example -@group -[i, j] = find (2 * eye (2)) - @result{} i = [ 1; 2 ] - @result{} j = [ 1; 2 ] -@end group -@end example - -If three outputs are requested, @code{find} also returns a vector -containing the nonzero values. For example, - -@example -@group -[i, j, v] = find (3 * eye (2)) - @result{} i = [ 1; 2 ] - @result{} j = [ 1; 2 ] - @result{} v = [ 3; 3 ] -@end group -@end example -@end deftypefn - -@node Rearranging Matrices, Special Utility Matrices, Finding Elements and Checking Conditions, Matrix Manipulation -@section Rearranging Matrices - -@deftypefn {Function File} {} fliplr (@var{x}) -Return a copy of @var{x} with the order of the columns reversed. For -example, - -@example -@group -fliplr ([1, 2; 3, 4]) - @result{} 2 1 - 4 3 -@end group -@end example -@end deftypefn - -@deftypefn {Function File} {} flipud (@var{x}) -Return a copy of @var{x} with the order of the rows reversed. For -example, - -@example -@group -flipud ([1, 2; 3, 4]) - @result{} 3 4 - 1 2 -@end group -@end example -@end deftypefn - -@deftypefn {Function File} {} rot90 (@var{x}, @var{n}) -Return a copy of @var{x} with the elements rotated counterclockwise in -90-degree increments. The second argument is optional, and specifies -how many 90-degree rotations are to be applied (the default value is 1). -Negative values of @var{n} rotate the matrix in a clockwise direction. -For example, - -@example -@group -rot90 ([1, 2; 3, 4], -1) - @result{} 3 1 - 4 2 -@end group -@end example - -@noindent -rotates the given matrix clockwise by 90 degrees. The following are all -equivalent statements: - -@example -@group -rot90 ([1, 2; 3, 4], -1) -@equiv{} -rot90 ([1, 2; 3, 4], 3) -@equiv{} -rot90 ([1, 2; 3, 4], 7) -@end group -@end example -@end deftypefn - -@deftypefn {Function File} {} reshape (@var{a}, @var{m}, @var{n}) -Return a matrix with @var{m} rows and @var{n} columns whose elements are -taken from the matrix @var{a}. To decide how to order the elements, -Octave pretends that the elements of a matrix are stored in column-major -order (like Fortran arrays are stored). - -For example, - -@example -@group -reshape ([1, 2, 3, 4], 2, 2) - @result{} 1 3 - 2 4 -@end group -@end example - -If the variable @code{do_fortran_indexing} is nonzero, the -@code{reshape} function is equivalent to - -@example -@group -retval = zeros (m, n); -retval (:) = a; -@end group -@end example - -@noindent -but it is somewhat less cryptic to use @code{reshape} instead of the -colon operator. Note that the total number of elements in the original -matrix must match the total number of elements in the new matrix. -@end deftypefn - -@deftypefn {Function File} {} shift (@var{x}, @var{b}) -If @var{x} is a vector, perform a circular shift of length @var{b} of -the elements of @var{x}. - -If @var{x} is a matrix, do the same for each column of @var{x}. -@end deftypefn - -@deftypefn {Loadable Function} {[@var{s}, @var{i}] =} sort (@var{x}) -Return a copy of @var{x} with the elements elements arranged in -increasing order. For matrices, @code{sort} orders the elements in each -column. - -For example, - -@example -@group -sort ([1, 2; 2, 3; 3, 1]) - @result{} 1 1 - 2 2 - 3 3 -@end group -@end example - -The @code{sort} function may also be used to produce a matrix -containing the original row indices of the elements in the sorted -matrix. For example, - -@example -@group -[s, i] = sort ([1, 2; 2, 3; 3, 1]) - @result{} s = 1 1 - 2 2 - 3 3 - @result{} i = 1 3 - 2 1 - 3 2 -@end group -@end example -@end deftypefn - -Since the @code{sort} function does not allow sort keys to be specified, -it can't be used to order the rows of a matrix according to the values -of the elements in various columns@footnote{For example, to first sort -based on the values in column 1, and then, for any values that are -repeated in column 1, sort based on the values found in column 2, etc.} -in a single call. Using the second output, however, it is possible to -sort all rows based on the values in a given column. Here's an example -that sorts the rows of a matrix based on the values in the second -column. - -@example -@group -a = [1, 2; 2, 3; 3, 1]; -[s, i] = sort (a (:, 2)); -a (i, :) - @result{} 3 1 - 1 2 - 2 3 -@end group -@end example - -@deftypefn {Function File} {} tril (@var{a}, @var{k}) -@deftypefnx {Function File} {} triu (@var{a}, @var{k}) -Return a new matrix formed by extracting extract the lower (@code{tril}) -or upper (@code{triu}) triangular part of the matrix @var{a}, and -setting all other elements to zero. The second argument is optional, -and specifies how many diagonals above or below the main diagonal should -also be set to zero. - -The default value of @var{k} is zero, so that @code{triu} and -@code{tril} normally include the main diagonal as part of the result -matrix. - -If the value of @var{k} is negative, additional elements above (for -@code{tril}) or below (for @code{triu}) the main diagonal are also -selected. - -The absolute value of @var{k} must not be greater than the number of -sub- or super-diagonals. - -For example, - -@example -@group -tril (ones (3), -1) - @result{} 0 0 0 - 1 0 0 - 1 1 0 -@end group -@end example - -@noindent -and - -@example -@group -tril (ones (3), 1) - @result{} 1 1 0 - 1 1 1 - 1 1 1 -@end group -@end example -@end deftypefn - -@deftypefn {Function File} {} vec (@var{x}) -Return the vector obtained by stacking the columns of the matrix @var{x} -one above the other. -@end deftypefn - -@deftypefn {Function File} {} vech (@var{x}) -Return the vector obtained by eliminating all supradiagonal elements of -the square matrix @var{x} and stacking the result one column above the -other. -@end deftypefn - -@node Special Utility Matrices, Famous Matrices, Rearranging Matrices, Matrix Manipulation -@section Special Utility Matrices - -@deftypefn {Built-in Function} {} eye (@var{x}) -@deftypefnx {Built-in Function} {} eye (@var{n}, @var{m}) -Return an identity matrix. If invoked with a single scalar argument, -@code{eye} returns a square matrix with the dimension specified. If you -supply two scalar arguments, @code{eye} takes them to be the number of -rows and columns. If given a vector with two elements, @code{eye} uses -the values of the elements as the number of rows and columns, -respectively. For example, - -@example -@group -eye (3) - @result{} 1 0 0 - 0 1 0 - 0 0 1 -@end group -@end example - -The following expressions all produce the same result: - -@example -@group -eye (2) -@equiv{} -eye (2, 2) -@equiv{} -eye (size ([1, 2; 3, 4]) -@end group -@end example - -For compatibility with @sc{Matlab}, calling @code{eye} with no arguments -is equivalent to calling it with an argument of 1. -@end deftypefn - -@deftypefn {Built-in Function} {} ones (@var{x}) -@deftypefnx {Built-in Function} {} ones (@var{n}, @var{m}) -Return a matrix whose elements are all 1. The arguments are handled -the same as the arguments for @code{eye}. - -If you need to create a matrix whose values are all the same, you should -use an expression like - -@example -val_matrix = val * ones (n, m) -@end example -@end deftypefn - -@deftypefn {Built-in Function} {} zeros (@var{x}) -@deftypefnx {Built-in Function} {} zeros (@var{n}, @var{m}) -Return a matrix whose elements are all 0. The arguments are handled -the same as the arguments for @code{eye}. -@end deftypefn - -@deftypefn {Loadable Function} {} rand (@var{x}) -@deftypefnx {Loadable Function} {} rand (@var{n}, @var{m}) -@deftypefnx {Loadable Function} {} rand (@code{"seed"}, @var{x}) -Return a matrix with random elements uniformly distributed on the -interval (0, 1). The arguments are handled the same as the arguments -for @code{eye}. In -addition, you can set the seed for the random number generator using the -form - -@example -rand ("seed", @var{x}) -@end example - -@noindent -where @var{x} is a scalar value. If called as - -@example -rand ("seed") -@end example - -@noindent -@code{rand} returns the current value of the seed. -@end deftypefn - -@deftypefn {Loadable Function} {} randn (@var{x}) -@deftypefnx {Loadable Function} {} randn (@var{n}, @var{m}) -@deftypefnx {Loadable Function} {} randn (@code{"seed"}, @var{x}) -Return a matrix with normally distributed random elements. The -arguments are handled the same as the arguments for @code{eye}. In -addition, you can set the seed for the random number generator using the -form - -@example -randn ("seed", @var{x}) -@end example - -@noindent -where @var{x} is a scalar value. If called as - -@example -randn ("seed") -@end example - -@noindent -@code{randn} returns the current value of the seed. -@end deftypefn - -The @code{rand} and @code{randn} functions use separate generators. -This ensures that - -@example -@group -rand ("seed", 13); -randn ("seed", 13); -u = rand (100, 1); -n = randn (100, 1); -@end group -@end example - -@noindent -and - -@example -@group -rand ("seed", 13); -randn ("seed", 13); -u = zeros (100, 1); -n = zeros (100, 1); -for i = 1:100 - u(i) = rand (); - n(i) = randn (); -end -@end group -@end example - -@noindent -produce equivalent results. - -Normally, @code{rand} and @code{randn} obtain their initial -seeds from the system clock, so that the sequence of random numbers is -not the same each time you run Octave. If you really do need for to -reproduce a sequence of numbers exactly, you can set the seed to a -specific value. - -If it is invoked without arguments, @code{rand} and @code{randn} return a -single element of a random sequence. - -The @code{rand} and @code{randn} functions use Fortran code from -@sc{Ranlib}, a library of fortran routines for random number generation, -compiled by Barry W. Brown and James Lovato of the Department of -Biomathematics at The University of Texas, M.D. Anderson Cancer Center, -Houston, TX 77030. - -@deftypefn {Built-in Function} {} diag (@var{v}, @var{k}) -Return a diagonal matrix with vector @var{v} on diagonal @var{k}. The -second argument is optional. If it is positive, the vector is placed on -the @var{k}-th super-diagonal. If it is negative, it is placed on the -@var{-k}-th sub-diagonal. The default value of @var{k} is 0, and the -vector is placed on the main diagonal. For example, - -@example -@group -diag ([1, 2, 3], 1) - @result{} 0 1 0 0 - 0 0 2 0 - 0 0 0 3 - 0 0 0 0 -@end group -@end example -@end deftypefn - -@c XXX FIXME XXX -- is this really worth documenting? -@c -@c @defvr {Built-in Variable} ok_to_lose_imaginary_part -@c If the value of @code{ok_to_lose_imaginary_part} is nonzero, implicit -@c conversions of complex numbers to real numbers are allowed (for example, -@c by fsolve). If the value is @code{"warn"}, the conversion is allowed, -@c but a warning is printed. Otherwise, an error message is printed and -@c control is returned to the top level. The default value is -@c @code{"warn"}. -@c -@c XXX FIXME XXX -- this is here because it is used by @code{ones}, -@c @code{zeros}, @code{rand}, etc. -@c @end defvr - -The functions @code{linspace} and @code{logspace} make it very easy to -create vectors with evenly or logarithmically spaced elements. -@xref{Ranges}. - -@deftypefn {Function File} {} linspace (@var{base}, @var{limit}, @var{n}) -Return a row vector with @var{n} linearly spaced elements between -@var{base} and @var{limit}. The number of elements, @var{n}, must be -greater than 1. The @var{base} and @var{limit} are always included in -the range. If @var{base} is greater than @var{limit}, the elements are -stored in decreasing order. If the number of points is not specified, a -value of 100 is used. - -The @code{linspace} function always returns a row vector, regardless of -the value of @code{prefer_column_vectors}. -@end deftypefn - -@deftypefn {Function File} {} logspace (@var{base}, @var{limit}, @var{n}) -Similar to @code{linspace} except that the values are logarithmically -spaced from -@iftex -@tex -$10^{base}$ to $10^{limit}$. -@end tex -@end iftex -@ifinfo -10^base to 10^limit. -@end ifinfo - -If @var{limit} is equal to -@iftex -@tex -$\pi$, -@end tex -@end iftex -@ifinfo -pi, -@end ifinfo -the points are between -@iftex -@tex -$10^{base}$ and $\pi$, -@end tex -@end iftex -@ifinfo -10^base and pi, -@end ifinfo -@emph{not} -@iftex -@tex -$10^{base}$ and $10^{\pi}$, -@end tex -@end iftex -@ifinfo -10^base and 10^pi, -@end ifinfo -in order to be compatible with the corresponding @sc{Matlab} function. -@end deftypefn - -@defvr {Built-in Variable} treat_neg_dim_as_zero -If the value of @code{treat_neg_dim_as_zero} is nonzero, expressions -like - -@example -eye (-1) -@end example - -@noindent -produce an empty matrix (i.e., row and column dimensions are zero). -Otherwise, an error message is printed and control is returned to the -top level. The default value is 0. -@end defvr - -@node Famous Matrices, , Special Utility Matrices, Matrix Manipulation -@section Famous Matrices - -The following functions return famous matrix forms. - -@deftypefn {Function File} {} hankel (@var{c}, @var{r}) -Return the Hankel matrix constructed given the first column @var{c}, and -(optionally) the last row @var{r}. If the last element of @var{c} is -not the same as the first element of @var{r}, the last element of -@var{c} is used. If the second argument is omitted, the last row is -taken to be the same as the first column. - -A Hankel matrix formed from an m-vector @var{c}, and an n-vector -@var{r}, has the elements -@iftex -@tex -$$ -H (i, j) = \cases{c_{i+j-1},&$i+j-1\le m$;\cr r_{i+j-m},&otherwise.\cr} -$$ -@end tex -@end iftex -@ifinfo - -@example -@group -H (i, j) = c (i+j-1), i+j-1 <= m; -H (i, j) = r (i+j-m), otherwise -@end group -@end example -@end ifinfo -@end deftypefn - -@deftypefn {Function File} {} hilb (@var{n}) -Return the Hilbert matrix of order @var{n}. The -@iftex -@tex -$i,\,j$ -@end tex -@end iftex -@ifinfo -i, j -@end ifinfo -element of a Hilbert matrix is defined as -@iftex -@tex -$$ -H (i, j) = {1 \over (i + j - 1)} -$$ -@end tex -@end iftex -@ifinfo - -@example -H (i, j) = 1 / (i + j - 1) -@end example -@end ifinfo -@end deftypefn - -@deftypefn {Function File} {} invhilb (@var{n}) -Return the inverse of a Hilbert matrix of order @var{n}. This is exact. -Compare with the numerical calculation of @code{inverse (hilb (n))}, -which suffers from the ill-conditioning of the Hilbert matrix, and the -finite precision of your computer's floating point arithmetic. -@end deftypefn - -@deftypefn {Function File} {} sylvester_matrix (@var{k}) -Return the Sylvester matrix of order -@iftex -@tex -$n = 2^k$. -@end tex -@end iftex -@ifinfo -n = 2^k. -@end ifinfo -@end deftypefn - -@deftypefn {Function File} {} toeplitz (@var{c}, @var{r}) -Return the Toeplitz matrix constructed given the first column @var{c}, -and (optionally) the first row @var{r}. If the first element of @var{c} -is not the same as the first element of @var{r}, the first element of -@var{c} is used. If the second argument is omitted, the first row is -taken to be the same as the first column. - -A square Toeplitz matrix has the form -@iftex -@tex -$$ -\left[\matrix{c_0 & r_1 & r_2 & \ldots & r_n\cr - c_1 & c_0 & r_1 & & c_{n-1}\cr - c_2 & c_1 & c_0 & & c_{n-2}\cr - \vdots & & & & \vdots\cr - c_n & c_{n-1} & c_{n-2} & \ldots & c_0}\right]. -$$ -@end tex -@end iftex -@ifinfo - -@example -@group -c(0) r(1) r(2) ... r(n) -c(1) c(0) r(1) r(n-1) -c(2) c(1) c(0) r(n-2) - . . - . . - . . - -c(n) c(n-1) c(n-2) ... c(0) -@end group -@end example -@end ifinfo -@end deftypefn - -@deftypefn {Function File} {} vander (@var{c}) -Return the Vandermonde matrix whose next to last column is @var{c}. - -A Vandermonde matrix has the form -@iftex -@tex -$$ -\left[\matrix{c_0^n & \ldots & c_0^2 & c_0 & 1\cr - c_1^n & \ldots & c_1^2 & c_1 & 1\cr - \vdots & & \vdots & \vdots & \vdots\cr - c_n^n & \ldots & c_n^2 & c_n & 1}\right]. -$$ -@end tex -@end iftex -@ifinfo - -@example -@group -c(0)^n ... c(0)^2 c(0) 1 -c(1)^n ... c(1)^2 c(1) 1 - . . . . - . . . . - . . . . - -c(n)^n ... c(n)^2 c(n) 1 -@end group -@end example -@end ifinfo -@end deftypefn diff --git a/doc/interpreter/matrix.txi b/doc/interpreter/matrix.txi new file mode 100644 --- /dev/null +++ b/doc/interpreter/matrix.txi @@ -0,0 +1,792 @@ +@c Copyright (C) 1996, 1997 John W. Eaton +@c This is part of the Octave manual. +@c For copying conditions, see the file gpl.texi. + +@node Matrix Manipulation, Arithmetic, Plotting, Top +@chapter Matrix Manipulation + +There are a number of functions available for checking to see if the +elements of a matrix meet some condition, and for rearranging the +elements of a matrix. For example, Octave can easily tell you if all +the elements of a matrix are finite, or are less than some specified +value. Octave can also rotate the elements, extract the upper- or +lower-triangular parts, or sort the columns of a matrix. + +@menu +* Finding Elements and Checking Conditions:: +* Rearranging Matrices:: +* Special Utility Matrices:: +* Famous Matrices:: +@end menu + +@node Finding Elements and Checking Conditions, Rearranging Matrices, Matrix Manipulation, Matrix Manipulation +@section Finding Elements and Checking Conditions + +The functions @code{any} and @code{all} are useful for determining +whether any or all of the elements of a matrix satisfy some condition. +The @code{find} function is also useful in determining which elements of +a matrix meet a specified condition. + +@deftypefn {Built-in Function} {} any (@var{x}) +For a vector argument, return 1 if any element of the vector is +nonzero. + +For a matrix argument, return a row vector of ones and +zeros with each element indicating whether any of the elements of the +corresponding column of the matrix are nonzero. For example, + +@example +@group +any (eye (2, 4)) + @result{} [ 1, 1, 0, 0 ] +@end group +@end example + +To see if any of the elements of a matrix are nonzero, you can use a +statement like + +@example +any (any (a)) +@end example +@end deftypefn + +@deftypefn {Built-in Function} {} all (@var{x}) +The function @code{all} behaves like the function @code{any}, except +that it returns true only if all the elements of a vector, or all the +elements in a column of a matrix, are nonzero. +@end deftypefn + +Since the comparison operators (@pxref{Comparison Ops}) return matrices +of ones and zeros, it is easy to test a matrix for many things, not just +whether the elements are nonzero. For example, + +@example +@group +all (all (rand (5) < 0.9)) + @result{} 0 +@end group +@end example + +@noindent +tests a random 5 by 5 matrix to see if all of its elements are less +than 0.9. + +Note that in conditional contexts (like the test clause of @code{if} and +@code{while} statements) Octave treats the test as if you had typed +@code{all (all (condition))}. + +@deftypefn {Function File} {[@var{err}, @var{y1}, ...] =} common_size (@var{x1}, ...) +Determine if all input arguments are either scalar or of common +size. If so, @var{err} is zero, and @var{yi} is a matrix of the +common size with all entries equal to @var{xi} if this is a scalar or +@var{xi} otherwise. If the inputs cannot be brought to a common size, +errorcode is 1, and @var{yi} is @var{xi}. For example, + +@example +@group +[errorcode, a, b] = common_size ([1 2; 3 4], 5) + @result{} errorcode = 0 + @result{} a = [ 1, 2; 3, 4 ] + @result{} b = [ 5, 5; 5, 5 ] +@end group +@end example + +@noindent +This is useful for implementing functions where arguments can either +be scalars or of common size. +@end deftypefn + +@deftypefn {Function File} {} diff (@var{x}, @var{k}) +If @var{x} is a vector of length @var{n}, @code{diff (@var{x})} is the +vector of first differences +@iftex +@tex + $x_2 - x_1, \ldots{}, x_n - x_{n-1}$. +@end tex +@end iftex +@ifinfo + @var{x}(2) - @var{x}(1), @dots{}, @var{x}(n) - @var{x}(n-1). +@end ifinfo + +If @var{x} is a matrix, @code{diff (@var{x})} is the matrix of column +differences. + +The second argument is optional. If supplied, @code{diff (@var{x}, +@var{k})}, where @var{k} is a nonnegative integer, returns the +@var{k}-th differences. +@end deftypefn + +@deftypefn {Mapping Function} {} isinf (@var{x}) +Return 1 for elements of @var{x} that are infinite and zero +otherwise. For example, + +@example +@group +isinf ([13, Inf, NaN]) + @result{} [ 0, 1, 0 ] +@end group +@end example +@end deftypefn + +@deftypefn {Mapping Function} {} isnan (@var{x}) +Return 1 for elements of @var{x} that are NaN values and zero +otherwise. For example, + +@example +@group +isnan ([13, Inf, NaN]) + @result{} [ 0, 0, 1 ] +@end group +@end example +@end deftypefn + +@deftypefn {Mapping Function} {} finite (@var{x}) +Return 1 for elements of @var{x} that are NaN values and zero +otherwise. For example, + +@example +@group +finite ([13, Inf, NaN]) + @result{} [ 1, 0, 0 ] +@end group +@end example +@end deftypefn + +@deftypefn {Loadable Function} {} find (@var{x}) +Return a vector of indices of nonzero elements of a matrix. To obtain a +single index for each matrix element, Octave pretends that the columns +of a matrix form one long vector (like Fortran arrays are stored). For +example, + +@example +@group +find (eye (2)) + @result{} [ 1; 4 ] +@end group +@end example + +If two outputs are requested, @code{find} returns the row and column +indices of nonzero elements of a matrix. For example, + +@example +@group +[i, j] = find (2 * eye (2)) + @result{} i = [ 1; 2 ] + @result{} j = [ 1; 2 ] +@end group +@end example + +If three outputs are requested, @code{find} also returns a vector +containing the nonzero values. For example, + +@example +@group +[i, j, v] = find (3 * eye (2)) + @result{} i = [ 1; 2 ] + @result{} j = [ 1; 2 ] + @result{} v = [ 3; 3 ] +@end group +@end example +@end deftypefn + +@node Rearranging Matrices, Special Utility Matrices, Finding Elements and Checking Conditions, Matrix Manipulation +@section Rearranging Matrices + +@deftypefn {Function File} {} fliplr (@var{x}) +Return a copy of @var{x} with the order of the columns reversed. For +example, + +@example +@group +fliplr ([1, 2; 3, 4]) + @result{} 2 1 + 4 3 +@end group +@end example +@end deftypefn + +@deftypefn {Function File} {} flipud (@var{x}) +Return a copy of @var{x} with the order of the rows reversed. For +example, + +@example +@group +flipud ([1, 2; 3, 4]) + @result{} 3 4 + 1 2 +@end group +@end example +@end deftypefn + +@deftypefn {Function File} {} rot90 (@var{x}, @var{n}) +Return a copy of @var{x} with the elements rotated counterclockwise in +90-degree increments. The second argument is optional, and specifies +how many 90-degree rotations are to be applied (the default value is 1). +Negative values of @var{n} rotate the matrix in a clockwise direction. +For example, + +@example +@group +rot90 ([1, 2; 3, 4], -1) + @result{} 3 1 + 4 2 +@end group +@end example + +@noindent +rotates the given matrix clockwise by 90 degrees. The following are all +equivalent statements: + +@example +@group +rot90 ([1, 2; 3, 4], -1) +@equiv{} +rot90 ([1, 2; 3, 4], 3) +@equiv{} +rot90 ([1, 2; 3, 4], 7) +@end group +@end example +@end deftypefn + +@deftypefn {Function File} {} reshape (@var{a}, @var{m}, @var{n}) +Return a matrix with @var{m} rows and @var{n} columns whose elements are +taken from the matrix @var{a}. To decide how to order the elements, +Octave pretends that the elements of a matrix are stored in column-major +order (like Fortran arrays are stored). + +For example, + +@example +@group +reshape ([1, 2, 3, 4], 2, 2) + @result{} 1 3 + 2 4 +@end group +@end example + +If the variable @code{do_fortran_indexing} is nonzero, the +@code{reshape} function is equivalent to + +@example +@group +retval = zeros (m, n); +retval (:) = a; +@end group +@end example + +@noindent +but it is somewhat less cryptic to use @code{reshape} instead of the +colon operator. Note that the total number of elements in the original +matrix must match the total number of elements in the new matrix. +@end deftypefn + +@deftypefn {Function File} {} shift (@var{x}, @var{b}) +If @var{x} is a vector, perform a circular shift of length @var{b} of +the elements of @var{x}. + +If @var{x} is a matrix, do the same for each column of @var{x}. +@end deftypefn + +@deftypefn {Loadable Function} {[@var{s}, @var{i}] =} sort (@var{x}) +Return a copy of @var{x} with the elements elements arranged in +increasing order. For matrices, @code{sort} orders the elements in each +column. + +For example, + +@example +@group +sort ([1, 2; 2, 3; 3, 1]) + @result{} 1 1 + 2 2 + 3 3 +@end group +@end example + +The @code{sort} function may also be used to produce a matrix +containing the original row indices of the elements in the sorted +matrix. For example, + +@example +@group +[s, i] = sort ([1, 2; 2, 3; 3, 1]) + @result{} s = 1 1 + 2 2 + 3 3 + @result{} i = 1 3 + 2 1 + 3 2 +@end group +@end example +@end deftypefn + +Since the @code{sort} function does not allow sort keys to be specified, +it can't be used to order the rows of a matrix according to the values +of the elements in various columns@footnote{For example, to first sort +based on the values in column 1, and then, for any values that are +repeated in column 1, sort based on the values found in column 2, etc.} +in a single call. Using the second output, however, it is possible to +sort all rows based on the values in a given column. Here's an example +that sorts the rows of a matrix based on the values in the second +column. + +@example +@group +a = [1, 2; 2, 3; 3, 1]; +[s, i] = sort (a (:, 2)); +a (i, :) + @result{} 3 1 + 1 2 + 2 3 +@end group +@end example + +@deftypefn {Function File} {} tril (@var{a}, @var{k}) +@deftypefnx {Function File} {} triu (@var{a}, @var{k}) +Return a new matrix formed by extracting extract the lower (@code{tril}) +or upper (@code{triu}) triangular part of the matrix @var{a}, and +setting all other elements to zero. The second argument is optional, +and specifies how many diagonals above or below the main diagonal should +also be set to zero. + +The default value of @var{k} is zero, so that @code{triu} and +@code{tril} normally include the main diagonal as part of the result +matrix. + +If the value of @var{k} is negative, additional elements above (for +@code{tril}) or below (for @code{triu}) the main diagonal are also +selected. + +The absolute value of @var{k} must not be greater than the number of +sub- or super-diagonals. + +For example, + +@example +@group +tril (ones (3), -1) + @result{} 0 0 0 + 1 0 0 + 1 1 0 +@end group +@end example + +@noindent +and + +@example +@group +tril (ones (3), 1) + @result{} 1 1 0 + 1 1 1 + 1 1 1 +@end group +@end example +@end deftypefn + +@deftypefn {Function File} {} vec (@var{x}) +Return the vector obtained by stacking the columns of the matrix @var{x} +one above the other. +@end deftypefn + +@deftypefn {Function File} {} vech (@var{x}) +Return the vector obtained by eliminating all supradiagonal elements of +the square matrix @var{x} and stacking the result one column above the +other. +@end deftypefn + +@node Special Utility Matrices, Famous Matrices, Rearranging Matrices, Matrix Manipulation +@section Special Utility Matrices + +@deftypefn {Built-in Function} {} eye (@var{x}) +@deftypefnx {Built-in Function} {} eye (@var{n}, @var{m}) +Return an identity matrix. If invoked with a single scalar argument, +@code{eye} returns a square matrix with the dimension specified. If you +supply two scalar arguments, @code{eye} takes them to be the number of +rows and columns. If given a vector with two elements, @code{eye} uses +the values of the elements as the number of rows and columns, +respectively. For example, + +@example +@group +eye (3) + @result{} 1 0 0 + 0 1 0 + 0 0 1 +@end group +@end example + +The following expressions all produce the same result: + +@example +@group +eye (2) +@equiv{} +eye (2, 2) +@equiv{} +eye (size ([1, 2; 3, 4]) +@end group +@end example + +For compatibility with @sc{Matlab}, calling @code{eye} with no arguments +is equivalent to calling it with an argument of 1. +@end deftypefn + +@deftypefn {Built-in Function} {} ones (@var{x}) +@deftypefnx {Built-in Function} {} ones (@var{n}, @var{m}) +Return a matrix whose elements are all 1. The arguments are handled +the same as the arguments for @code{eye}. + +If you need to create a matrix whose values are all the same, you should +use an expression like + +@example +val_matrix = val * ones (n, m) +@end example +@end deftypefn + +@deftypefn {Built-in Function} {} zeros (@var{x}) +@deftypefnx {Built-in Function} {} zeros (@var{n}, @var{m}) +Return a matrix whose elements are all 0. The arguments are handled +the same as the arguments for @code{eye}. +@end deftypefn + +@deftypefn {Loadable Function} {} rand (@var{x}) +@deftypefnx {Loadable Function} {} rand (@var{n}, @var{m}) +@deftypefnx {Loadable Function} {} rand (@code{"seed"}, @var{x}) +Return a matrix with random elements uniformly distributed on the +interval (0, 1). The arguments are handled the same as the arguments +for @code{eye}. In +addition, you can set the seed for the random number generator using the +form + +@example +rand ("seed", @var{x}) +@end example + +@noindent +where @var{x} is a scalar value. If called as + +@example +rand ("seed") +@end example + +@noindent +@code{rand} returns the current value of the seed. +@end deftypefn + +@deftypefn {Loadable Function} {} randn (@var{x}) +@deftypefnx {Loadable Function} {} randn (@var{n}, @var{m}) +@deftypefnx {Loadable Function} {} randn (@code{"seed"}, @var{x}) +Return a matrix with normally distributed random elements. The +arguments are handled the same as the arguments for @code{eye}. In +addition, you can set the seed for the random number generator using the +form + +@example +randn ("seed", @var{x}) +@end example + +@noindent +where @var{x} is a scalar value. If called as + +@example +randn ("seed") +@end example + +@noindent +@code{randn} returns the current value of the seed. +@end deftypefn + +The @code{rand} and @code{randn} functions use separate generators. +This ensures that + +@example +@group +rand ("seed", 13); +randn ("seed", 13); +u = rand (100, 1); +n = randn (100, 1); +@end group +@end example + +@noindent +and + +@example +@group +rand ("seed", 13); +randn ("seed", 13); +u = zeros (100, 1); +n = zeros (100, 1); +for i = 1:100 + u(i) = rand (); + n(i) = randn (); +end +@end group +@end example + +@noindent +produce equivalent results. + +Normally, @code{rand} and @code{randn} obtain their initial +seeds from the system clock, so that the sequence of random numbers is +not the same each time you run Octave. If you really do need for to +reproduce a sequence of numbers exactly, you can set the seed to a +specific value. + +If it is invoked without arguments, @code{rand} and @code{randn} return a +single element of a random sequence. + +The @code{rand} and @code{randn} functions use Fortran code from +@sc{Ranlib}, a library of fortran routines for random number generation, +compiled by Barry W. Brown and James Lovato of the Department of +Biomathematics at The University of Texas, M.D. Anderson Cancer Center, +Houston, TX 77030. + +@deftypefn {Built-in Function} {} diag (@var{v}, @var{k}) +Return a diagonal matrix with vector @var{v} on diagonal @var{k}. The +second argument is optional. If it is positive, the vector is placed on +the @var{k}-th super-diagonal. If it is negative, it is placed on the +@var{-k}-th sub-diagonal. The default value of @var{k} is 0, and the +vector is placed on the main diagonal. For example, + +@example +@group +diag ([1, 2, 3], 1) + @result{} 0 1 0 0 + 0 0 2 0 + 0 0 0 3 + 0 0 0 0 +@end group +@end example +@end deftypefn + +@c XXX FIXME XXX -- is this really worth documenting? +@c +@c @defvr {Built-in Variable} ok_to_lose_imaginary_part +@c If the value of @code{ok_to_lose_imaginary_part} is nonzero, implicit +@c conversions of complex numbers to real numbers are allowed (for example, +@c by fsolve). If the value is @code{"warn"}, the conversion is allowed, +@c but a warning is printed. Otherwise, an error message is printed and +@c control is returned to the top level. The default value is +@c @code{"warn"}. +@c +@c XXX FIXME XXX -- this is here because it is used by @code{ones}, +@c @code{zeros}, @code{rand}, etc. +@c @end defvr + +The functions @code{linspace} and @code{logspace} make it very easy to +create vectors with evenly or logarithmically spaced elements. +@xref{Ranges}. + +@deftypefn {Function File} {} linspace (@var{base}, @var{limit}, @var{n}) +Return a row vector with @var{n} linearly spaced elements between +@var{base} and @var{limit}. The number of elements, @var{n}, must be +greater than 1. The @var{base} and @var{limit} are always included in +the range. If @var{base} is greater than @var{limit}, the elements are +stored in decreasing order. If the number of points is not specified, a +value of 100 is used. + +The @code{linspace} function always returns a row vector, regardless of +the value of @code{prefer_column_vectors}. +@end deftypefn + +@deftypefn {Function File} {} logspace (@var{base}, @var{limit}, @var{n}) +Similar to @code{linspace} except that the values are logarithmically +spaced from +@iftex +@tex +$10^{base}$ to $10^{limit}$. +@end tex +@end iftex +@ifinfo +10^base to 10^limit. +@end ifinfo + +If @var{limit} is equal to +@iftex +@tex +$\pi$, +@end tex +@end iftex +@ifinfo +pi, +@end ifinfo +the points are between +@iftex +@tex +$10^{base}$ and $\pi$, +@end tex +@end iftex +@ifinfo +10^base and pi, +@end ifinfo +@emph{not} +@iftex +@tex +$10^{base}$ and $10^{\pi}$, +@end tex +@end iftex +@ifinfo +10^base and 10^pi, +@end ifinfo +in order to be compatible with the corresponding @sc{Matlab} function. +@end deftypefn + +@defvr {Built-in Variable} treat_neg_dim_as_zero +If the value of @code{treat_neg_dim_as_zero} is nonzero, expressions +like + +@example +eye (-1) +@end example + +@noindent +produce an empty matrix (i.e., row and column dimensions are zero). +Otherwise, an error message is printed and control is returned to the +top level. The default value is 0. +@end defvr + +@node Famous Matrices, , Special Utility Matrices, Matrix Manipulation +@section Famous Matrices + +The following functions return famous matrix forms. + +@deftypefn {Function File} {} hankel (@var{c}, @var{r}) +Return the Hankel matrix constructed given the first column @var{c}, and +(optionally) the last row @var{r}. If the last element of @var{c} is +not the same as the first element of @var{r}, the last element of +@var{c} is used. If the second argument is omitted, the last row is +taken to be the same as the first column. + +A Hankel matrix formed from an m-vector @var{c}, and an n-vector +@var{r}, has the elements +@iftex +@tex +$$ +H (i, j) = \cases{c_{i+j-1},&$i+j-1\le m$;\cr r_{i+j-m},&otherwise.\cr} +$$ +@end tex +@end iftex +@ifinfo + +@example +@group +H (i, j) = c (i+j-1), i+j-1 <= m; +H (i, j) = r (i+j-m), otherwise +@end group +@end example +@end ifinfo +@end deftypefn + +@deftypefn {Function File} {} hilb (@var{n}) +Return the Hilbert matrix of order @var{n}. The +@iftex +@tex +$i,\,j$ +@end tex +@end iftex +@ifinfo +i, j +@end ifinfo +element of a Hilbert matrix is defined as +@iftex +@tex +$$ +H (i, j) = {1 \over (i + j - 1)} +$$ +@end tex +@end iftex +@ifinfo + +@example +H (i, j) = 1 / (i + j - 1) +@end example +@end ifinfo +@end deftypefn + +@deftypefn {Function File} {} invhilb (@var{n}) +Return the inverse of a Hilbert matrix of order @var{n}. This is exact. +Compare with the numerical calculation of @code{inverse (hilb (n))}, +which suffers from the ill-conditioning of the Hilbert matrix, and the +finite precision of your computer's floating point arithmetic. +@end deftypefn + +@deftypefn {Function File} {} sylvester_matrix (@var{k}) +Return the Sylvester matrix of order +@iftex +@tex +$n = 2^k$. +@end tex +@end iftex +@ifinfo +n = 2^k. +@end ifinfo +@end deftypefn + +@deftypefn {Function File} {} toeplitz (@var{c}, @var{r}) +Return the Toeplitz matrix constructed given the first column @var{c}, +and (optionally) the first row @var{r}. If the first element of @var{c} +is not the same as the first element of @var{r}, the first element of +@var{c} is used. If the second argument is omitted, the first row is +taken to be the same as the first column. + +A square Toeplitz matrix has the form +@iftex +@tex +$$ +\left[\matrix{c_0 & r_1 & r_2 & \ldots & r_n\cr + c_1 & c_0 & r_1 & & c_{n-1}\cr + c_2 & c_1 & c_0 & & c_{n-2}\cr + \vdots & & & & \vdots\cr + c_n & c_{n-1} & c_{n-2} & \ldots & c_0}\right]. +$$ +@end tex +@end iftex +@ifinfo + +@example +@group +c(0) r(1) r(2) ... r(n) +c(1) c(0) r(1) r(n-1) +c(2) c(1) c(0) r(n-2) + . . + . . + . . + +c(n) c(n-1) c(n-2) ... c(0) +@end group +@end example +@end ifinfo +@end deftypefn + +@deftypefn {Function File} {} vander (@var{c}) +Return the Vandermonde matrix whose next to last column is @var{c}. + +A Vandermonde matrix has the form +@iftex +@tex +$$ +\left[\matrix{c_0^n & \ldots & c_0^2 & c_0 & 1\cr + c_1^n & \ldots & c_1^2 & c_1 & 1\cr + \vdots & & \vdots & \vdots & \vdots\cr + c_n^n & \ldots & c_n^2 & c_n & 1}\right]. +$$ +@end tex +@end iftex +@ifinfo + +@example +@group +c(0)^n ... c(0)^2 c(0) 1 +c(1)^n ... c(1)^2 c(1) 1 + . . . . + . . . . + . . . . + +c(n)^n ... c(n)^2 c(n) 1 +@end group +@end example +@end ifinfo +@end deftypefn diff --git a/doc/interpreter/munge-texi.cc b/doc/interpreter/munge-texi.cc new file mode 100644 --- /dev/null +++ b/doc/interpreter/munge-texi.cc @@ -0,0 +1,160 @@ +#include +#include +#include +#include + +static const char doc_delim = ''; + +static map help_text; + +static void +fatal (const string& msg) +{ + cerr << msg << "\n"; + exit (1); +} + +static void +usage (void) +{ + cerr << "usage: munge-texi -d DOCSTRING-FILE file ...\n"; + exit (1); +} + +static string +extract_symbol_name (istream& is) +{ + string symbol_name; + + int c; + while ((c = is.get ()) != EOF && c != '\n') + symbol_name += (char) c; + + return symbol_name; +} + +static string +extract_docstring (istream& is) +{ + string doc; + + int c; + while ((c = is.get ()) != EOF && c != doc_delim) + doc += (char) c; + + return doc; +} + +static void +process_doc_file (const string& fname) +{ + ifstream infile (fname.c_str ()); + + if (infile) + { + if (infile.get () != doc_delim) + fatal ("invalid doc file format"); + + string symbol_name; + + do + { + symbol_name = extract_symbol_name (infile); + + if (! symbol_name.empty ()) + { + string doc_string = extract_docstring (infile); + + if (help_text.find (symbol_name) != help_text.end ()) + cerr << "ignoring duplicate entry for " << symbol_name << "\n"; + else + help_text[symbol_name] = doc_string; + } + } + while (! symbol_name.empty ()); + } + else + fatal ("unable to open docfile"); +} + +static void +process_texi_input_file (istream& is, ostream& os) +{ + os << "@c DO NOT EDIT! Generated automatically by munge-texi.\n\n"; + + bool bol = true; + + int c; + while ((c = is.get ()) != EOF) + { + if (bol) + { + if (c == '@') + { + string symbol_name; + + char buf[16]; + int i = 0; + buf[i++] = c; + + if ((buf[i++] = (char) is.get ()) == 'D' + && (buf[i++] = (char) is.get ()) == 'O' + && (buf[i++] = (char) is.get ()) == 'C' + && (buf[i++] = (char) is.get ()) == 'S' + && (buf[i++] = (char) is.get ()) == 'T' + && (buf[i++] = (char) is.get ()) == 'R' + && (buf[i++] = (char) is.get ()) == 'I' + && (buf[i++] = (char) is.get ()) == 'N' + && (buf[i++] = (char) is.get ()) == 'G' + && (buf[i++] = (char) is.get ()) == '(') + { + while ((c = is.get ()) != EOF && c != ')') + symbol_name += (char) c; + + if (is.eof ()) + fatal ("end of file while reading @DOCSTRING command"); + else + os << help_text[symbol_name]; + } + else + { + buf[i] = '\0'; + os << buf; + + if (buf[i - 1] == '\n') + bol = true; + } + } + else + os.put ((char) c); + } + else + { + if (c == '\n') + bol = true; + + os.put ((char) (c)); + } + } +} + +int +main (int argc, char **argv) +{ + while (*++argv) + { + if (! strcmp (*argv, "-d")) + { + if (*++argv) + process_doc_file (*argv); + else + usage (); + } + else + break; + } + + process_texi_input_file (cin, cout); + + return 0; +} diff --git a/doc/interpreter/nonlin.texi b/doc/interpreter/nonlin.texi deleted file mode 100644 --- a/doc/interpreter/nonlin.texi +++ /dev/null @@ -1,103 +0,0 @@ -@c Copyright (C) 1996, 1997 John W. Eaton -@c This is part of the Octave manual. -@c For copying conditions, see the file gpl.texi. - -@node Nonlinear Equations, Quadrature, Linear Algebra, Top -@chapter Nonlinear Equations -@cindex nonlinear equations -@cindex equations, nonlinear - -Octave can solve sets of nonlinear equations of the form -@iftex -@tex -$$ - f (x) = 0 -$$ -@end tex -@end iftex -@ifinfo - -@example -F (x) = 0 -@end example -@end ifinfo - -@noindent -using the function @code{fsolve}, which is based on the @sc{Minpack} -subroutine @code{hybrd}. - -@deftypefn {Loadable Function} {[@var{x}, @var{info}] =} fsolve (@var{fcn}, @var{x0}) -Given @var{fcn}, the name of a function of the form @code{f (@var{x})} -and an initial starting point @var{x0}, @code{fsolve} solves the set of -equations such that @code{f(@var{x}) == 0}. -@end deftypefn - -@deftypefn {Loadable Function} {} fsolve_options (@var{opt}, @var{val}) -When called with two arguments, this function allows you set options -parameters for the function @code{fsolve}. Given one argument, -@code{fsolve_options} returns the value of the corresponding option. If -no arguments are supplied, the names of all the available options and -their current values are displayed. -@end deftypefn - -Here is a complete example. To solve the set of equations -@iftex -@tex -$$ - \eqalign{-2x^2 + 3xy + 4\sin(y) - 6 &= 0\cr - 3x^2 - 2xy^2 + 3\cos(x) + 4 &= 0} -$$ -@end tex -@end iftex -@ifinfo - -@example --2x^2 + 3xy + 4 sin(y) = 6 - 3x^2 - 2xy^2 + 3 cos(x) = -4 -@end example -@end ifinfo - -@noindent -you first need to write a function to compute the value of the given -function. For example: - -@example -function y = f (x) - y(1) = -2*x(1)^2 + 3*x(1)*x(2) + 4*sin(x(2)) - 6; - y(2) = 3*x(1)^2 - 2*x(1)*x(2)^2 + 3*cos(x(1)) + 4; -endfunction -@end example - -Then, call @code{fsolve} with a specified initial condition to find the -roots of the system of equations. For example, given the function -@code{f} defined above, - -@example -[x, info] = fsolve ("f", [1; 2]) -@end example - -@noindent -results in the solution - -@example -x = - - 0.57983 - 2.54621 - -info = 1 -@end example - -A value of @code{info = 1} indicates that the solution has converged. - -The function @code{perror} may be used to print English messages -corresponding to the numeric error codes. For example, - -@example -@group -perror ("fsolve", 1) - @print{} solution converged to requested tolerance -@end group -@end example - - diff --git a/doc/interpreter/nonlin.txi b/doc/interpreter/nonlin.txi new file mode 100644 --- /dev/null +++ b/doc/interpreter/nonlin.txi @@ -0,0 +1,103 @@ +@c Copyright (C) 1996, 1997 John W. Eaton +@c This is part of the Octave manual. +@c For copying conditions, see the file gpl.texi. + +@node Nonlinear Equations, Quadrature, Linear Algebra, Top +@chapter Nonlinear Equations +@cindex nonlinear equations +@cindex equations, nonlinear + +Octave can solve sets of nonlinear equations of the form +@iftex +@tex +$$ + f (x) = 0 +$$ +@end tex +@end iftex +@ifinfo + +@example +F (x) = 0 +@end example +@end ifinfo + +@noindent +using the function @code{fsolve}, which is based on the @sc{Minpack} +subroutine @code{hybrd}. + +@deftypefn {Loadable Function} {[@var{x}, @var{info}] =} fsolve (@var{fcn}, @var{x0}) +Given @var{fcn}, the name of a function of the form @code{f (@var{x})} +and an initial starting point @var{x0}, @code{fsolve} solves the set of +equations such that @code{f(@var{x}) == 0}. +@end deftypefn + +@deftypefn {Loadable Function} {} fsolve_options (@var{opt}, @var{val}) +When called with two arguments, this function allows you set options +parameters for the function @code{fsolve}. Given one argument, +@code{fsolve_options} returns the value of the corresponding option. If +no arguments are supplied, the names of all the available options and +their current values are displayed. +@end deftypefn + +Here is a complete example. To solve the set of equations +@iftex +@tex +$$ + \eqalign{-2x^2 + 3xy + 4\sin(y) - 6 &= 0\cr + 3x^2 - 2xy^2 + 3\cos(x) + 4 &= 0} +$$ +@end tex +@end iftex +@ifinfo + +@example +-2x^2 + 3xy + 4 sin(y) = 6 + 3x^2 - 2xy^2 + 3 cos(x) = -4 +@end example +@end ifinfo + +@noindent +you first need to write a function to compute the value of the given +function. For example: + +@example +function y = f (x) + y(1) = -2*x(1)^2 + 3*x(1)*x(2) + 4*sin(x(2)) - 6; + y(2) = 3*x(1)^2 - 2*x(1)*x(2)^2 + 3*cos(x(1)) + 4; +endfunction +@end example + +Then, call @code{fsolve} with a specified initial condition to find the +roots of the system of equations. For example, given the function +@code{f} defined above, + +@example +[x, info] = fsolve ("f", [1; 2]) +@end example + +@noindent +results in the solution + +@example +x = + + 0.57983 + 2.54621 + +info = 1 +@end example + +A value of @code{info = 1} indicates that the solution has converged. + +The function @code{perror} may be used to print English messages +corresponding to the numeric error codes. For example, + +@example +@group +perror ("fsolve", 1) + @print{} solution converged to requested tolerance +@end group +@end example + + diff --git a/doc/interpreter/numbers.texi b/doc/interpreter/numbers.texi deleted file mode 100644 --- a/doc/interpreter/numbers.texi +++ /dev/null @@ -1,571 +0,0 @@ -@c Copyright (C) 1996, 1997 John W. Eaton -@c This is part of the Octave manual. -@c For copying conditions, see the file gpl.texi. - -@node Numeric Data Types, Strings, Data Types, Top -@chapter Numeric Data Types -@cindex numeric constant -@cindex numeric value - -A @dfn{numeric constant} may be a scalar, a vector, or a matrix, and it -may contain complex values. - -The simplest form of a numeric constant, a scalar, is a single number -that can be an integer, a decimal fraction, a number in scientific -(exponential) notation, or a complex number. Note that all numeric -constants are represented within Octave in double-precision floating -point format (complex constants are stored as pairs of double-precision -floating point values). Here are some examples of real-valued numeric -constants, which all have the same value: - -@example -@group -105 -1.05e+2 -1050e-1 -@end group -@end example - -To specify complex constants, you can write an expression of the form - -@example -@group -3 + 4i -3.0 + 4.0i -0.3e1 + 40e-1i -@end group -@end example - -all of which are equivalent. The letter @samp{i} in the previous example -stands for the pure imaginary constant, defined as -@iftex -@tex - $\sqrt{-1}$. -@end tex -@end iftex -@ifinfo - @code{sqrt (-1)}. -@end ifinfo - -For Octave to recognize a value as the imaginary part of a complex -constant, a space must not appear between the number and the @samp{i}. -If it does, Octave will print an error message, like this: - -@example -@group -octave:13> 3 + 4 i - -parse error: - - 3 + 4 i - ^ -@end group -@end example - -You may also use @samp{j}, @samp{I}, or @samp{J} in place of the -@samp{i} above. All four forms are equivalent. - -@menu -* Matrices:: -* Ranges:: -* Predicates for Numeric Objects:: -@end menu - -@node Matrices, Ranges, Numeric Data Types, Numeric Data Types -@section Matrices -@cindex matrices - -@opindex [ -@opindex ] -@opindex ; -@opindex , - -It is easy to define a matrix of values in Octave. The size of the -matrix is determined automatically, so it is not necessary to explicitly -state the dimensions. The expression - -@example -a = [1, 2; 3, 4] -@end example - -@noindent -results in the matrix -@iftex -@tex -$$ a = \left[ \matrix{ 1 & 2 \cr 3 & 4 } \right] $$ -@end tex -@end iftex -@ifinfo - -@example -@group - - / \ - | 1 2 | - a = | | - | 3 4 | - \ / - -@end group -@end example -@end ifinfo - -Elements of a matrix may be arbitrary expressions, provided that the -dimensions all make sense when combining the various pieces. For -example, given the above matrix, the expression - -@example -[ a, a ] -@end example - -@noindent -produces the matrix - -@example -@group -ans = - - 1 2 1 2 - 3 4 3 4 -@end group -@end example - -@noindent -but the expression - -@example -[ a, 1 ] -@end example - -@noindent -produces the error - -@example -error: number of rows must match near line 13, column 6 -@end example - -@noindent -(assuming that this expression was entered as the first thing on line -13, of course). - -Inside the square brackets that delimit a matrix expression, Octave -looks at the surrounding context to determine whether spaces and newline -characters should be converted into element and row separators, or -simply ignored, so commands like - -@example -[ linspace (1, 2) ] -@end example - -@noindent -and - -@example -@group -a = [ 1 2 - 3 4 ] -@end group -@end example - -@noindent -will work. However, some possible sources of confusion remain. For -example, in the expression - -@example -[ 1 - 1 ] -@end example - -@noindent -the @samp{-} is treated as a binary operator and the result is the -scalar 0, but in the expression - -@example -[ 1 -1 ] -@end example - -@noindent -the @samp{-} is treated as a unary operator and the result is the -vector @code{[ 1, -1 ]}. - -Given @code{a = 1}, the expression - -@example -[ 1 a' ] -@end example - -@noindent -results in the single quote character @samp{'} being treated as a -transpose operator and the result is the vector @code{[ 1, 1 ]}, but the -expression - -@example -[ 1 a ' ] -@end example - -@noindent -produces the error message - -@example -error: unterminated string constant -@end example - -@noindent -because to not do so would make it impossible to correctly parse the -valid expression - -@example -[ a 'foo' ] -@end example - -For clarity, it is probably best to always use commas and semicolons to -separate matrix elements and rows. It is possible to enforce this style -by setting the built-in variable @code{whitespace_in_literal_matrix} to -@code{"ignore"}. - -@defvr {Built-in Variable} whitespace_in_literal_matrix -This variable allows some control over how Octave decides to convert -spaces to commas and semicolons in matrix expressions like -@code{[m (1)]} or - -@example -[ 1, 2, - 3, 4 ] -@end example - -If the value of @code{whitespace_in_literal_matrix} is @code{"ignore"}, -Octave will never insert a comma or a semicolon in a literal matrix -list. For example, the expression @code{[1 2]} will result in an error -instead of being treated the same as @code{[1, 2]}, and the expression - -@example -[ 1, 2, - 3, 4 ] -@end example - -@noindent -will result in the vector @code{[ 1, 2, 3, 4 ]} instead of a matrix. - -If the value of @code{whitespace_in_literal_matrix} is @code{"traditional"}, -Octave will convert spaces to a comma between identifiers and @samp{(}. For -example, given the matrix - -@example -m = [3 2] -@end example - -@noindent -the expression - -@example -[m (1)] -@end example - -@noindent -will be parsed as - -@example -[m, (1)] -@end example - -@noindent -and will result in - -@example -[3 2 1] -@end example - -@noindent -and the expression - -@example -[ 1, 2, - 3, 4 ] -@end example - -@noindent -will result in a matrix because the newline character is converted to a -semicolon (row separator) even though there is a comma at the end of the -first line (trailing commas or semicolons are ignored). This is -apparently how @sc{Matlab} behaves. - -Any other value for @code{whitespace_in_literal_matrix} results in behavior -that is the same as traditional, except that Octave does not -convert spaces to a comma between identifiers and @samp{(}. For -example, the expression - -@example -[m (1)] -@end example - -will produce @samp{3}. This is the way Octave has always behaved. -@end defvr - -When you type a matrix or the name of a variable whose value is a -matrix, Octave responds by printing the matrix in with neatly aligned -rows and columns. If the rows of the matrix are too large to fit on the -screen, Octave splits the matrix and displays a header before each -section to indicate which columns are being displayed. You can use the -following variables to control the format of the output. - -@defvr {Built-in Variable} output_max_field_width -This variable specifies the maximum width of a numeric output field. -The default value is 10. -@end defvr - -@defvr {Built-in Variable} output_precision -This variable specifies the minimum number of significant figures to -display for numeric output. The default value is 5. -@end defvr - -It is possible to achieve a wide range of output styles by using -different values of @code{output_precision} and -@code{output_max_field_width}. Reasonable combinations can be set using -the @code{format} function. @xref{Basic Input and Output}. - -@defvr {Built-in Variable} split_long_rows -For large matrices, Octave may not be able to display all the columns of -a given row on one line of your screen. This can result in missing -information or output that is nearly impossible to decipher, depending -on whether your terminal truncates or wraps long lines. - -If the value of @code{split_long_rows} is nonzero, Octave will display -the matrix in a series of smaller pieces, each of which can fit within -the limits of your terminal width. Each set of rows is labeled so that -you can easily see which columns are currently being displayed. -For example: - -@smallexample -@group -octave:13> rand (2,10) -ans = - - Columns 1 through 6: - - 0.75883 0.93290 0.40064 0.43818 0.94958 0.16467 - 0.75697 0.51942 0.40031 0.61784 0.92309 0.40201 - - Columns 7 through 10: - - 0.90174 0.11854 0.72313 0.73326 - 0.44672 0.94303 0.56564 0.82150 -@end group -@end smallexample - -@noindent -The default value of @code{split_long_rows} is nonzero. -@end defvr - -Octave automatically switches to scientific notation when values become -very large or very small. This guarantees that you will see several -significant figures for every value in a matrix. If you would prefer to -see all values in a matrix printed in a fixed point format, you can set -the built-in variable @code{fixed_point_format} to a nonzero value. But -doing so is not recommended, because it can produce output that can -easily be misinterpreted. - -@defvr {Built-in Variable} fixed_point_format -If the value of this variable is nonzero, Octave will scale all values -in a matrix so that the largest may be written with one leading digit. -The scaling factor is printed on the first line of output. For example, - -@example -@group -octave:1> logspace (1, 7, 5)' -ans = - - 1.0e+07 * - - 0.00000 - 0.00003 - 0.00100 - 0.03162 - 1.00000 -@end group -@end example - -@noindent -Notice that first value appears to be zero when it is actually 1. For -this reason, you should be careful when setting -@code{fixed_point_format} to a nonzero value. - -The default value of @code{fixed_point_format} is 0. -@end defvr - -@menu -* Empty Matrices:: -@end menu - -@node Empty Matrices, , Matrices, Matrices -@subsection Empty Matrices - -A matrix may have one or both dimensions zero, and operations on empty -matrices are handled as described by Carl de Boor in @cite{An Empty -Exercise}, SIGNUM, Volume 25, pages 2--6, 1990 and C. N. Nett and W. M. -Haddad, in @cite{A System-Theoretic Appropriate Realization of the Empty -Matrix Concept}, IEEE Transactions on Automatic Control, Volume 38, -Number 5, May 1993. -@iftex -@tex -Briefly, given a scalar $s$, an $m\times n$ matrix $M_{m\times n}$, -and an $m\times n$ empty matrix $[\,]_{m\times n}$ (with either one or -both dimensions equal to zero), the following are true: -$$ -\eqalign{% -s \cdot [\,]_{m\times n} = [\,]_{m\times n} \cdot s &= [\,]_{m\times n}\cr -[\,]_{m\times n} + [\,]_{m\times n} &= [\,]_{m\times n}\cr -[\,]_{0\times m} \cdot M_{m\times n} &= [\,]_{0\times n}\cr -M_{m\times n} \cdot [\,]_{n\times 0} &= [\,]_{m\times 0}\cr -[\,]_{m\times 0} \cdot [\,]_{0\times n} &= 0_{m\times n}} -$$ -@end tex -@end iftex -@ifinfo -Briefly, given a scalar @var{s}, an @var{m} by -@var{n} matrix @code{M(mxn)}, and an @var{m} by @var{n} empty matrix -@code{[](mxn)} (with either one or both dimensions equal to zero), the -following are true: - -@example -@group -s * [](mxn) = [](mxn) * s = [](mxn) - - [](mxn) + [](mxn) = [](mxn) - - [](0xm) * M(mxn) = [](0xn) - - M(mxn) * [](nx0) = [](mx0) - - [](mx0) * [](0xn) = 0(mxn) -@end group -@end example -@end ifinfo - -By default, dimensions of the empty matrix are printed along with the -empty matrix symbol, @samp{[]}. The built-in variable -@code{print_empty_dimensions} controls this behavior. - -@defvr {Built-in Variable} print_empty_dimensions -If the value of @code{print_empty_dimensions} is nonzero, the -dimensions of empty matrices are printed along with the empty matrix -symbol, @samp{[]}. For example, the expression - -@example -zeros (3, 0) -@end example - -@noindent -will print - -@example -ans = [](3x0) -@end example -@end defvr - -Empty matrices may also be used in assignment statements as a convenient -way to delete rows or columns of matrices. -@xref{Assignment Ops, ,Assignment Expressions}. - -Octave will normally issue a warning if it finds an empty matrix in the -list of elements that make up another matrix. You can use the variable -@code{empty_list_elements_ok} to suppress the warning or to treat it as -an error. - -@defvr {Built-in Variable} empty_list_elements_ok -This variable controls whether Octave ignores empty matrices in a matrix -list. - -For example, if the value of @code{empty_list_elements_ok} is -nonzero, Octave will ignore the empty matrices in the expression - -@example -a = [1, [], 3, [], 5] -@end example - -@noindent -and the variable @code{a} will be assigned the value @code{[ 1, 3, 5 ]}. - -The default value is @code{"warn"}. -@end defvr - -When Octave parses a matrix expression, it examines the elements of the -list to determine whether they are all constants. If they are, it -replaces the list with a single matrix constant. - -@defvr {Built-in Variable} propagate_empty_matrices -If the value of @code{propagate_empty_matrices} is nonzero, -functions like @code{inverse} and @code{svd} will return an empty matrix -if they are given one as an argument. The default value is 1. -@end defvr - -@node Ranges, Predicates for Numeric Objects, Matrices, Numeric Data Types -@section Ranges -@cindex range expressions -@cindex expression, range - -@opindex : - -A @dfn{range} is a convenient way to write a row vector with evenly -spaced elements. A range expression is defined by the value of the first -element in the range, an optional value for the increment between -elements, and a maximum value which the elements of the range will not -exceed. The base, increment, and limit are separated by colons (the -@samp{:} character) and may contain any arithmetic expressions and -function calls. If the increment is omitted, it is assumed to be 1. -For example, the range - -@example -1 : 5 -@end example - -@noindent -defines the set of values @samp{[ 1, 2, 3, 4, 5 ]}, and the range - -@example -1 : 3 : 5 -@end example - -@noindent -defines the set of values @samp{[ 1, 4 ]}. - -Although a range constant specifies a row vector, Octave does @emph{not} -convert range constants to vectors unless it is necessary to do so. -This allows you to write a constant like @samp{1 : 10000} without using -80,000 bytes of storage on a typical 32-bit workstation. - -Note that the upper (or lower, if the increment is negative) bound on -the range is not always included in the set of values, and that ranges -defined by floating point values can produce surprising results because -Octave uses floating point arithmetic to compute the values in the -range. If it is important to include the endpoints of a range and the -number of elements is known, you should use the @code{linspace} function -instead (@pxref{Special Utility Matrices}). - -When Octave parses a range expression, it examines the elements of the -expression to determine whether they are all constants. If they are, it -replaces the range expression with a single range constant. - -@node Predicates for Numeric Objects, , Ranges, Numeric Data Types -@section Predicates for Numeric Objects - -@deftypefn {Function File} {} is_matrix (@var{a}) -Return 1 if @var{a} is a matrix. Otherwise, return 0. -@end deftypefn - -@deftypefn {Function File} {} is_vector (@var{a}) -Return 1 if @var{a} is a vector. Otherwise, return 0. -@end deftypefn - -@deftypefn {Function File} {} is_scalar (@var{a}) -Return 1 if @var{a} is a scalar. Otherwise, return 0. -@end deftypefn - -@deftypefn {Function File} {} is_square (@var{x}) -If @var{x} is a square matrix, then return the dimension of @var{x}. -Otherwise, return 0. -@end deftypefn - -@deftypefn {Function File} {} is_symmetric (@var{x}, @var{tol}) -If @var{x} is symmetric within the tolerance specified by @var{tol}, -then return the dimension of @var{x}. Otherwise, return 0. If -@var{tol} is omitted, use a tolerance equal to the machine precision. -@end deftypefn diff --git a/doc/interpreter/numbers.txi b/doc/interpreter/numbers.txi new file mode 100644 --- /dev/null +++ b/doc/interpreter/numbers.txi @@ -0,0 +1,571 @@ +@c Copyright (C) 1996, 1997 John W. Eaton +@c This is part of the Octave manual. +@c For copying conditions, see the file gpl.texi. + +@node Numeric Data Types, Strings, Data Types, Top +@chapter Numeric Data Types +@cindex numeric constant +@cindex numeric value + +A @dfn{numeric constant} may be a scalar, a vector, or a matrix, and it +may contain complex values. + +The simplest form of a numeric constant, a scalar, is a single number +that can be an integer, a decimal fraction, a number in scientific +(exponential) notation, or a complex number. Note that all numeric +constants are represented within Octave in double-precision floating +point format (complex constants are stored as pairs of double-precision +floating point values). Here are some examples of real-valued numeric +constants, which all have the same value: + +@example +@group +105 +1.05e+2 +1050e-1 +@end group +@end example + +To specify complex constants, you can write an expression of the form + +@example +@group +3 + 4i +3.0 + 4.0i +0.3e1 + 40e-1i +@end group +@end example + +all of which are equivalent. The letter @samp{i} in the previous example +stands for the pure imaginary constant, defined as +@iftex +@tex + $\sqrt{-1}$. +@end tex +@end iftex +@ifinfo + @code{sqrt (-1)}. +@end ifinfo + +For Octave to recognize a value as the imaginary part of a complex +constant, a space must not appear between the number and the @samp{i}. +If it does, Octave will print an error message, like this: + +@example +@group +octave:13> 3 + 4 i + +parse error: + + 3 + 4 i + ^ +@end group +@end example + +You may also use @samp{j}, @samp{I}, or @samp{J} in place of the +@samp{i} above. All four forms are equivalent. + +@menu +* Matrices:: +* Ranges:: +* Predicates for Numeric Objects:: +@end menu + +@node Matrices, Ranges, Numeric Data Types, Numeric Data Types +@section Matrices +@cindex matrices + +@opindex [ +@opindex ] +@opindex ; +@opindex , + +It is easy to define a matrix of values in Octave. The size of the +matrix is determined automatically, so it is not necessary to explicitly +state the dimensions. The expression + +@example +a = [1, 2; 3, 4] +@end example + +@noindent +results in the matrix +@iftex +@tex +$$ a = \left[ \matrix{ 1 & 2 \cr 3 & 4 } \right] $$ +@end tex +@end iftex +@ifinfo + +@example +@group + + / \ + | 1 2 | + a = | | + | 3 4 | + \ / + +@end group +@end example +@end ifinfo + +Elements of a matrix may be arbitrary expressions, provided that the +dimensions all make sense when combining the various pieces. For +example, given the above matrix, the expression + +@example +[ a, a ] +@end example + +@noindent +produces the matrix + +@example +@group +ans = + + 1 2 1 2 + 3 4 3 4 +@end group +@end example + +@noindent +but the expression + +@example +[ a, 1 ] +@end example + +@noindent +produces the error + +@example +error: number of rows must match near line 13, column 6 +@end example + +@noindent +(assuming that this expression was entered as the first thing on line +13, of course). + +Inside the square brackets that delimit a matrix expression, Octave +looks at the surrounding context to determine whether spaces and newline +characters should be converted into element and row separators, or +simply ignored, so commands like + +@example +[ linspace (1, 2) ] +@end example + +@noindent +and + +@example +@group +a = [ 1 2 + 3 4 ] +@end group +@end example + +@noindent +will work. However, some possible sources of confusion remain. For +example, in the expression + +@example +[ 1 - 1 ] +@end example + +@noindent +the @samp{-} is treated as a binary operator and the result is the +scalar 0, but in the expression + +@example +[ 1 -1 ] +@end example + +@noindent +the @samp{-} is treated as a unary operator and the result is the +vector @code{[ 1, -1 ]}. + +Given @code{a = 1}, the expression + +@example +[ 1 a' ] +@end example + +@noindent +results in the single quote character @samp{'} being treated as a +transpose operator and the result is the vector @code{[ 1, 1 ]}, but the +expression + +@example +[ 1 a ' ] +@end example + +@noindent +produces the error message + +@example +error: unterminated string constant +@end example + +@noindent +because to not do so would make it impossible to correctly parse the +valid expression + +@example +[ a 'foo' ] +@end example + +For clarity, it is probably best to always use commas and semicolons to +separate matrix elements and rows. It is possible to enforce this style +by setting the built-in variable @code{whitespace_in_literal_matrix} to +@code{"ignore"}. + +@defvr {Built-in Variable} whitespace_in_literal_matrix +This variable allows some control over how Octave decides to convert +spaces to commas and semicolons in matrix expressions like +@code{[m (1)]} or + +@example +[ 1, 2, + 3, 4 ] +@end example + +If the value of @code{whitespace_in_literal_matrix} is @code{"ignore"}, +Octave will never insert a comma or a semicolon in a literal matrix +list. For example, the expression @code{[1 2]} will result in an error +instead of being treated the same as @code{[1, 2]}, and the expression + +@example +[ 1, 2, + 3, 4 ] +@end example + +@noindent +will result in the vector @code{[ 1, 2, 3, 4 ]} instead of a matrix. + +If the value of @code{whitespace_in_literal_matrix} is @code{"traditional"}, +Octave will convert spaces to a comma between identifiers and @samp{(}. For +example, given the matrix + +@example +m = [3 2] +@end example + +@noindent +the expression + +@example +[m (1)] +@end example + +@noindent +will be parsed as + +@example +[m, (1)] +@end example + +@noindent +and will result in + +@example +[3 2 1] +@end example + +@noindent +and the expression + +@example +[ 1, 2, + 3, 4 ] +@end example + +@noindent +will result in a matrix because the newline character is converted to a +semicolon (row separator) even though there is a comma at the end of the +first line (trailing commas or semicolons are ignored). This is +apparently how @sc{Matlab} behaves. + +Any other value for @code{whitespace_in_literal_matrix} results in behavior +that is the same as traditional, except that Octave does not +convert spaces to a comma between identifiers and @samp{(}. For +example, the expression + +@example +[m (1)] +@end example + +will produce @samp{3}. This is the way Octave has always behaved. +@end defvr + +When you type a matrix or the name of a variable whose value is a +matrix, Octave responds by printing the matrix in with neatly aligned +rows and columns. If the rows of the matrix are too large to fit on the +screen, Octave splits the matrix and displays a header before each +section to indicate which columns are being displayed. You can use the +following variables to control the format of the output. + +@defvr {Built-in Variable} output_max_field_width +This variable specifies the maximum width of a numeric output field. +The default value is 10. +@end defvr + +@defvr {Built-in Variable} output_precision +This variable specifies the minimum number of significant figures to +display for numeric output. The default value is 5. +@end defvr + +It is possible to achieve a wide range of output styles by using +different values of @code{output_precision} and +@code{output_max_field_width}. Reasonable combinations can be set using +the @code{format} function. @xref{Basic Input and Output}. + +@defvr {Built-in Variable} split_long_rows +For large matrices, Octave may not be able to display all the columns of +a given row on one line of your screen. This can result in missing +information or output that is nearly impossible to decipher, depending +on whether your terminal truncates or wraps long lines. + +If the value of @code{split_long_rows} is nonzero, Octave will display +the matrix in a series of smaller pieces, each of which can fit within +the limits of your terminal width. Each set of rows is labeled so that +you can easily see which columns are currently being displayed. +For example: + +@smallexample +@group +octave:13> rand (2,10) +ans = + + Columns 1 through 6: + + 0.75883 0.93290 0.40064 0.43818 0.94958 0.16467 + 0.75697 0.51942 0.40031 0.61784 0.92309 0.40201 + + Columns 7 through 10: + + 0.90174 0.11854 0.72313 0.73326 + 0.44672 0.94303 0.56564 0.82150 +@end group +@end smallexample + +@noindent +The default value of @code{split_long_rows} is nonzero. +@end defvr + +Octave automatically switches to scientific notation when values become +very large or very small. This guarantees that you will see several +significant figures for every value in a matrix. If you would prefer to +see all values in a matrix printed in a fixed point format, you can set +the built-in variable @code{fixed_point_format} to a nonzero value. But +doing so is not recommended, because it can produce output that can +easily be misinterpreted. + +@defvr {Built-in Variable} fixed_point_format +If the value of this variable is nonzero, Octave will scale all values +in a matrix so that the largest may be written with one leading digit. +The scaling factor is printed on the first line of output. For example, + +@example +@group +octave:1> logspace (1, 7, 5)' +ans = + + 1.0e+07 * + + 0.00000 + 0.00003 + 0.00100 + 0.03162 + 1.00000 +@end group +@end example + +@noindent +Notice that first value appears to be zero when it is actually 1. For +this reason, you should be careful when setting +@code{fixed_point_format} to a nonzero value. + +The default value of @code{fixed_point_format} is 0. +@end defvr + +@menu +* Empty Matrices:: +@end menu + +@node Empty Matrices, , Matrices, Matrices +@subsection Empty Matrices + +A matrix may have one or both dimensions zero, and operations on empty +matrices are handled as described by Carl de Boor in @cite{An Empty +Exercise}, SIGNUM, Volume 25, pages 2--6, 1990 and C. N. Nett and W. M. +Haddad, in @cite{A System-Theoretic Appropriate Realization of the Empty +Matrix Concept}, IEEE Transactions on Automatic Control, Volume 38, +Number 5, May 1993. +@iftex +@tex +Briefly, given a scalar $s$, an $m\times n$ matrix $M_{m\times n}$, +and an $m\times n$ empty matrix $[\,]_{m\times n}$ (with either one or +both dimensions equal to zero), the following are true: +$$ +\eqalign{% +s \cdot [\,]_{m\times n} = [\,]_{m\times n} \cdot s &= [\,]_{m\times n}\cr +[\,]_{m\times n} + [\,]_{m\times n} &= [\,]_{m\times n}\cr +[\,]_{0\times m} \cdot M_{m\times n} &= [\,]_{0\times n}\cr +M_{m\times n} \cdot [\,]_{n\times 0} &= [\,]_{m\times 0}\cr +[\,]_{m\times 0} \cdot [\,]_{0\times n} &= 0_{m\times n}} +$$ +@end tex +@end iftex +@ifinfo +Briefly, given a scalar @var{s}, an @var{m} by +@var{n} matrix @code{M(mxn)}, and an @var{m} by @var{n} empty matrix +@code{[](mxn)} (with either one or both dimensions equal to zero), the +following are true: + +@example +@group +s * [](mxn) = [](mxn) * s = [](mxn) + + [](mxn) + [](mxn) = [](mxn) + + [](0xm) * M(mxn) = [](0xn) + + M(mxn) * [](nx0) = [](mx0) + + [](mx0) * [](0xn) = 0(mxn) +@end group +@end example +@end ifinfo + +By default, dimensions of the empty matrix are printed along with the +empty matrix symbol, @samp{[]}. The built-in variable +@code{print_empty_dimensions} controls this behavior. + +@defvr {Built-in Variable} print_empty_dimensions +If the value of @code{print_empty_dimensions} is nonzero, the +dimensions of empty matrices are printed along with the empty matrix +symbol, @samp{[]}. For example, the expression + +@example +zeros (3, 0) +@end example + +@noindent +will print + +@example +ans = [](3x0) +@end example +@end defvr + +Empty matrices may also be used in assignment statements as a convenient +way to delete rows or columns of matrices. +@xref{Assignment Ops, ,Assignment Expressions}. + +Octave will normally issue a warning if it finds an empty matrix in the +list of elements that make up another matrix. You can use the variable +@code{empty_list_elements_ok} to suppress the warning or to treat it as +an error. + +@defvr {Built-in Variable} empty_list_elements_ok +This variable controls whether Octave ignores empty matrices in a matrix +list. + +For example, if the value of @code{empty_list_elements_ok} is +nonzero, Octave will ignore the empty matrices in the expression + +@example +a = [1, [], 3, [], 5] +@end example + +@noindent +and the variable @code{a} will be assigned the value @code{[ 1, 3, 5 ]}. + +The default value is @code{"warn"}. +@end defvr + +When Octave parses a matrix expression, it examines the elements of the +list to determine whether they are all constants. If they are, it +replaces the list with a single matrix constant. + +@defvr {Built-in Variable} propagate_empty_matrices +If the value of @code{propagate_empty_matrices} is nonzero, +functions like @code{inverse} and @code{svd} will return an empty matrix +if they are given one as an argument. The default value is 1. +@end defvr + +@node Ranges, Predicates for Numeric Objects, Matrices, Numeric Data Types +@section Ranges +@cindex range expressions +@cindex expression, range + +@opindex : + +A @dfn{range} is a convenient way to write a row vector with evenly +spaced elements. A range expression is defined by the value of the first +element in the range, an optional value for the increment between +elements, and a maximum value which the elements of the range will not +exceed. The base, increment, and limit are separated by colons (the +@samp{:} character) and may contain any arithmetic expressions and +function calls. If the increment is omitted, it is assumed to be 1. +For example, the range + +@example +1 : 5 +@end example + +@noindent +defines the set of values @samp{[ 1, 2, 3, 4, 5 ]}, and the range + +@example +1 : 3 : 5 +@end example + +@noindent +defines the set of values @samp{[ 1, 4 ]}. + +Although a range constant specifies a row vector, Octave does @emph{not} +convert range constants to vectors unless it is necessary to do so. +This allows you to write a constant like @samp{1 : 10000} without using +80,000 bytes of storage on a typical 32-bit workstation. + +Note that the upper (or lower, if the increment is negative) bound on +the range is not always included in the set of values, and that ranges +defined by floating point values can produce surprising results because +Octave uses floating point arithmetic to compute the values in the +range. If it is important to include the endpoints of a range and the +number of elements is known, you should use the @code{linspace} function +instead (@pxref{Special Utility Matrices}). + +When Octave parses a range expression, it examines the elements of the +expression to determine whether they are all constants. If they are, it +replaces the range expression with a single range constant. + +@node Predicates for Numeric Objects, , Ranges, Numeric Data Types +@section Predicates for Numeric Objects + +@deftypefn {Function File} {} is_matrix (@var{a}) +Return 1 if @var{a} is a matrix. Otherwise, return 0. +@end deftypefn + +@deftypefn {Function File} {} is_vector (@var{a}) +Return 1 if @var{a} is a vector. Otherwise, return 0. +@end deftypefn + +@deftypefn {Function File} {} is_scalar (@var{a}) +Return 1 if @var{a} is a scalar. Otherwise, return 0. +@end deftypefn + +@deftypefn {Function File} {} is_square (@var{x}) +If @var{x} is a square matrix, then return the dimension of @var{x}. +Otherwise, return 0. +@end deftypefn + +@deftypefn {Function File} {} is_symmetric (@var{x}, @var{tol}) +If @var{x} is symmetric within the tolerance specified by @var{tol}, +then return the dimension of @var{x}. Otherwise, return 0. If +@var{tol} is omitted, use a tolerance equal to the machine precision. +@end deftypefn diff --git a/doc/interpreter/octave.texi b/doc/interpreter/octave.texi deleted file mode 100644 --- a/doc/interpreter/octave.texi +++ /dev/null @@ -1,482 +0,0 @@ -% Copyright (C) 1996, 1997 John W. Eaton -% This is part of the Octave manual. -% For copying conditions, see the file gpl.texi. - -\input texinfo -@setfilename octave.info - -@ifinfo -@format -START-INFO-DIR-ENTRY -* Octave: (octave). Interactive language for numerical computations. -END-INFO-DIR-ENTRY -@end format -@end ifinfo - -@c Settings for printing on 8-1/2 by 11 inch paper: -@c ----------------------------------------------- - -@setchapternewpage odd - -@c Settings for small book format: -@c ------------------------------ - -@ignore -@smallbook -@setchapternewpage odd -@finalout -@iftex -@cropmarks -@end iftex -@end ignore - -@defindex op - -@c Things like the Octave version number are defined in conf.texi. -@c This file doesn't include a chapter, so it must not be included -@c if you want to run the Emacs function texinfo-multiple-files-update. - -@include conf.texi - -@settitle GNU Octave - -@ifinfo - -Copyright (C) 1996, 1997 John W. Eaton. - -Permission is granted to make and distribute verbatim copies of -this manual provided the copyright notice and this permission notice -are preserved on all copies. - -@ignore -Permission is granted to process this file through Tex and print the -results, provided the printed document carries copying permission -notice identical to this one except for the removal of this paragraph -(this paragraph not being relevant to the printed manual). - -@end ignore -Permission is granted to copy and distribute modified versions of -this manual under the conditions for verbatim copying, provided that -the entire resulting derived work is distributed under the terms of -a permission notice identical to this one. - -Permission is granted to copy and distribute translations of this -manual into another language, under the above conditions for -modified versions. -@end ifinfo - -@titlepage -@title GNU Octave -@subtitle A high-level interactive language for numerical computations -@subtitle Edition 3 for Octave version @value{VERSION} -@subtitle February 1997 -@author John W. Eaton -@page -@vskip 0pt plus 1filll -Copyright @copyright{} 1996, 1997 John W. Eaton. - -This is the third edition of the Octave documentation, and is consistent -with version @value{VERSION} of Octave. - -Permission is granted to make and distribute verbatim copies of -this manual provided the copyright notice and this permission notice -are preserved on all copies. - -Permission is granted to copy and distribute modified versions of this -manual under the conditions for verbatim copying, provided that the entire -resulting derived work is distributed under the terms of a permission -notice identical to this one. - -Permission is granted to copy and distribute translations of this manual -into another language, under the same conditions as for modified versions. - -Portions of this document have been adapted from the @code{gawk}, -@code{readline}, @code{gcc}, and C library manuals, published by the Free -Software Foundation, 59 Temple Place---Suite 330, Boston, MA -02111--1307, USA. -@end titlepage - -@ifinfo -@node Top, Preface, (dir), (dir) -@top - -This manual documents how to run, install and port GNU Octave, as well -as its new features and incompatibilities, and how to report bugs. -It corresponds to GNU Octave version @value{VERSION}. -@end ifinfo - -@menu -* Preface:: -* Introduction:: A brief introduction to Octave. -* Getting Started:: -* Data Types:: -* Numeric Data Types:: -* Strings:: -* Data Structures:: -* Variables:: -* Expressions:: Expressions. -* Evaluation:: -* Statements:: Looping and program flow control. -* Functions and Scripts:: -* Error Handling:: -* Input and Output:: -* Plotting:: -* Matrix Manipulation:: -* Arithmetic:: -* Linear Algebra:: -* Nonlinear Equations:: -* Quadrature:: -* Differential Equations:: -* Optimization:: -* Statistics:: -* Sets:: -* Polynomial Manipulations:: -* Control Theory:: -* Signal Processing:: -* Image Processing:: -* Audio Processing:: -* System Utilities:: -* Tips:: -* Trouble:: If you have trouble installing Octave. -* Installation:: How to configure, compile and install Octave. -* Emacs:: -* Grammar:: -* Copying:: The GNU General Public License. -* Concept Index:: An item for each concept. -* Variable Index:: An item for each documented variable. -* Function Index:: An item for each documented function. -* Operator Index:: An item for each documented operator. - - - --- The Detailed Node Listing --- - -Preface - -* Acknowledgements:: -* How You Can Contribute to Octave:: -* Distribution:: - -A Brief Introduction to Octave - -* Running Octave:: -* Simple Examples:: -* Conventions:: - -Conventions - -* Fonts:: -* Evaluation Notation:: -* Printing Notation:: -* Error Messages:: -* Format of Descriptions:: - -Format of Descriptions - -* A Sample Function Description:: -* A Sample Command Description:: -* A Sample Variable Description:: - -Getting Started - -* Invoking Octave:: -* Quitting Octave:: -* Getting Help:: -* Command Line Editing:: -* Errors:: -* Executable Octave Programs:: -* Comments:: - -Invoking Octave - -* Command Line Options:: -* Startup Files:: - -Command Line Editing - -* Cursor Motion:: -* Killing and Yanking:: -* Commands For Text:: -* Commands For Completion:: -* Commands For History:: -* Customizing the Prompt:: -* Diary and Echo Commands:: - -Data Types - -* Built-in Data Types:: -* User-defined Data Types:: -* Object Sizes:: - -Built-in Data Types - -* Numeric Objects:: -* String Objects:: -* Data Structure Objects:: - -Numeric Data Types - -* Matrices:: -* Ranges:: -* Predicates for Numeric Objects:: - -Matrices - -* Empty Matrices:: - -Strings - -* Creating Strings:: -* Searching and Replacing:: -* String Conversions:: -* Character Class Functions:: - -Variables - -* Global Variables:: -* Status of Variables:: -* Summary of Built-in Variables:: -* Defaults from the Environment:: - -Expressions - -* Index Expressions:: -* Calling Functions:: -* Arithmetic Ops:: -* Comparison Ops:: -* Boolean Expressions:: -* Assignment Ops:: -* Increment Ops:: -* Operator Precedence:: - -Calling Functions - -* Call by Value:: -* Recursion:: - -Boolean Expressions - -* Element-by-element Boolean Operators:: -* Short-circuit Boolean Operators:: - -Statements - -* The if Statement:: -* The switch Statement:: -* The while Statement:: -* The for Statement:: -* The break Statement:: -* The continue Statement:: -* The unwind_protect Statement:: -* The try Statement:: -* Continuation Lines:: - -The @code{for} Statement - -* Looping Over Structure Elements:: - -Functions and Script Files - -* Defining Functions:: -* Multiple Return Values:: -* Variable-length Argument Lists:: -* Variable-length Return Lists:: -* Returning From a Function:: -* Function Files:: -* Script Files:: -* Dynamically Linked Functions:: -* Organization of Functions:: - -Input and Output - -* Basic Input and Output:: -* C-Style I/O Functions:: - -Basic Input and Output - -* Terminal Output:: -* Terminal Input:: -* Simple File I/O:: - -C-Style I/O Functions - -* Opening and Closing Files:: -* Simple Output:: -* Line-Oriented Input:: -* Formatted Output:: -* Output Conversion for Matrices:: -* Output Conversion Syntax:: -* Table of Output Conversions:: -* Integer Conversions:: -* Floating-Point Conversions:: Other Output Conversions:: -* Other Output Conversions:: -* Formatted Input:: -* Input Conversion Syntax:: -* Table of Input Conversions:: -* Numeric Input Conversions:: -* String Input Conversions:: -* Binary I/O:: -* Temporary Files:: -* EOF and Errors:: -* File Positioning:: - -Plotting - -* Two-Dimensional Plotting:: -* Specialized Two-Dimensional Plots:: -* Three-Dimensional Plotting:: -* Plot Annotations:: -* Multiple Plots on One Page:: - -Matrix Manipulation - -* Finding Elements and Checking Conditions:: -* Rearranging Matrices:: -* Special Utility Matrices:: -* Famous Matrices:: - -Arithmetic - -* Utility Functions:: -* Complex Arithmetic:: -* Trigonometry:: -* Sums and Products:: -* Special Functions:: -* Mathematical Constants:: - -Linear Algebra - -* Basic Matrix Functions:: -* Matrix Factorizations:: -* Functions of a Matrix:: - -Quadrature - -* Functions of One Variable:: -* Orthogonal Collocation:: - -Differential Equations - -* Ordinary Differential Equations:: -* Differential-Algebraic Equations:: - -Optimization - -* Quadratic Programming:: -* Nonlinear Programming:: -* Linear Least Squares:: - -System Utilities - -* Timing Utilities:: -* Filesystem Utilities:: -* Controlling Subprocesses:: -* Process ID Information:: -* Environment Variables:: -* Current Working Directory:: -* Password Database Functions:: -* Group Database Functions:: -* System Information:: - -Tips and Standards - -* Style Tips:: Writing clean and robust programs. -* Coding Tips:: Making code run faster. -* Documentation Tips:: Writing readable documentation strings. -* Comment Tips:: Conventions for writing comments. -* Function Headers:: Standard headers for functions. - -Known Causes of Trouble with Octave - -* Actual Bugs:: Bugs we will fix later. -* Reporting Bugs:: -* Bug Criteria:: -* Bug Lists:: -* Bug Reporting:: -* Sending Patches:: -* Service:: - -Reporting Bugs - -* Bug Criteria:: -* Where: Bug Lists. Where to send your bug report. -* Reporting: Bug Reporting. How to report a bug effectively. -* Patches: Sending Patches. How to send a patch for Octave. - -Installing Octave - -* Installation Problems:: -* Binary Distributions:: - -Binary Distributions - -* Installing Octave from a Binary Distribution:: -* Creating a Binary Distribution:: - -Emacs Octave Support - -* Installing EOS:: -* Using Octave Mode:: -* Running Octave From Within Emacs:: -* Using the Emacs Info Reader for Octave:: - -Grammar - -* Keywords:: -@end menu - -@include preface.texi -@include intro.texi -@include basics.texi -@include data.texi -@include numbers.texi -@include strings.texi -@include struct.texi -@include var.texi -@include expr.texi -@include eval.texi -@include stmt.texi -@include func.texi -@include errors.texi -@include io.texi -@include plot.texi -@include matrix.texi -@include arith.texi -@include linalg.texi -@include nonlin.texi -@include quad.texi -@include diffeq.texi -@include optim.texi -@include stats.texi -@include set.texi -@include poly.texi -@include control.texi -@include signal.texi -@include image.texi -@include audio.texi -@include system.texi - -@c maybe add again later, if anyone every writes any really interesting -@c fun stuff for Octave. -@c -@c @include amuse.texi - -@c Appendices start here. Installation and bugs have to go before the -@c readline and Info appendices because we want to have separate indices -@c for them, and there appears to be no way to go back to the original -@c set of indices once a redirection has taken place. - -@include tips.texi -@include bugs.texi -@include install.texi -@include emacs.texi -@include grammar.texi -@include gpl.texi - -@include cp-idx.texi -@include vr-idx.texi -@include fn-idx.texi -@include op-idx.texi - -@contents - -@bye diff --git a/doc/interpreter/octave.txi b/doc/interpreter/octave.txi new file mode 100644 --- /dev/null +++ b/doc/interpreter/octave.txi @@ -0,0 +1,482 @@ +% Copyright (C) 1996, 1997 John W. Eaton +% This is part of the Octave manual. +% For copying conditions, see the file gpl.texi. + +\input texinfo +@setfilename octave.info + +@ifinfo +@format +START-INFO-DIR-ENTRY +* Octave: (octave). Interactive language for numerical computations. +END-INFO-DIR-ENTRY +@end format +@end ifinfo + +@c Settings for printing on 8-1/2 by 11 inch paper: +@c ----------------------------------------------- + +@setchapternewpage odd + +@c Settings for small book format: +@c ------------------------------ + +@ignore +@smallbook +@setchapternewpage odd +@finalout +@iftex +@cropmarks +@end iftex +@end ignore + +@defindex op + +@c Things like the Octave version number are defined in conf.texi. +@c This file doesn't include a chapter, so it must not be included +@c if you want to run the Emacs function texinfo-multiple-files-update. + +@include conf.texi + +@settitle GNU Octave + +@ifinfo + +Copyright (C) 1996, 1997 John W. Eaton. + +Permission is granted to make and distribute verbatim copies of +this manual provided the copyright notice and this permission notice +are preserved on all copies. + +@ignore +Permission is granted to process this file through Tex and print the +results, provided the printed document carries copying permission +notice identical to this one except for the removal of this paragraph +(this paragraph not being relevant to the printed manual). + +@end ignore +Permission is granted to copy and distribute modified versions of +this manual under the conditions for verbatim copying, provided that +the entire resulting derived work is distributed under the terms of +a permission notice identical to this one. + +Permission is granted to copy and distribute translations of this +manual into another language, under the above conditions for +modified versions. +@end ifinfo + +@titlepage +@title GNU Octave +@subtitle A high-level interactive language for numerical computations +@subtitle Edition 3 for Octave version @value{VERSION} +@subtitle February 1997 +@author John W. Eaton +@page +@vskip 0pt plus 1filll +Copyright @copyright{} 1996, 1997 John W. Eaton. + +This is the third edition of the Octave documentation, and is consistent +with version @value{VERSION} of Octave. + +Permission is granted to make and distribute verbatim copies of +this manual provided the copyright notice and this permission notice +are preserved on all copies. + +Permission is granted to copy and distribute modified versions of this +manual under the conditions for verbatim copying, provided that the entire +resulting derived work is distributed under the terms of a permission +notice identical to this one. + +Permission is granted to copy and distribute translations of this manual +into another language, under the same conditions as for modified versions. + +Portions of this document have been adapted from the @code{gawk}, +@code{readline}, @code{gcc}, and C library manuals, published by the Free +Software Foundation, 59 Temple Place---Suite 330, Boston, MA +02111--1307, USA. +@end titlepage + +@ifinfo +@node Top, Preface, (dir), (dir) +@top + +This manual documents how to run, install and port GNU Octave, as well +as its new features and incompatibilities, and how to report bugs. +It corresponds to GNU Octave version @value{VERSION}. +@end ifinfo + +@menu +* Preface:: +* Introduction:: A brief introduction to Octave. +* Getting Started:: +* Data Types:: +* Numeric Data Types:: +* Strings:: +* Data Structures:: +* Variables:: +* Expressions:: Expressions. +* Evaluation:: +* Statements:: Looping and program flow control. +* Functions and Scripts:: +* Error Handling:: +* Input and Output:: +* Plotting:: +* Matrix Manipulation:: +* Arithmetic:: +* Linear Algebra:: +* Nonlinear Equations:: +* Quadrature:: +* Differential Equations:: +* Optimization:: +* Statistics:: +* Sets:: +* Polynomial Manipulations:: +* Control Theory:: +* Signal Processing:: +* Image Processing:: +* Audio Processing:: +* System Utilities:: +* Tips:: +* Trouble:: If you have trouble installing Octave. +* Installation:: How to configure, compile and install Octave. +* Emacs:: +* Grammar:: +* Copying:: The GNU General Public License. +* Concept Index:: An item for each concept. +* Variable Index:: An item for each documented variable. +* Function Index:: An item for each documented function. +* Operator Index:: An item for each documented operator. + + + --- The Detailed Node Listing --- + +Preface + +* Acknowledgements:: +* How You Can Contribute to Octave:: +* Distribution:: + +A Brief Introduction to Octave + +* Running Octave:: +* Simple Examples:: +* Conventions:: + +Conventions + +* Fonts:: +* Evaluation Notation:: +* Printing Notation:: +* Error Messages:: +* Format of Descriptions:: + +Format of Descriptions + +* A Sample Function Description:: +* A Sample Command Description:: +* A Sample Variable Description:: + +Getting Started + +* Invoking Octave:: +* Quitting Octave:: +* Getting Help:: +* Command Line Editing:: +* Errors:: +* Executable Octave Programs:: +* Comments:: + +Invoking Octave + +* Command Line Options:: +* Startup Files:: + +Command Line Editing + +* Cursor Motion:: +* Killing and Yanking:: +* Commands For Text:: +* Commands For Completion:: +* Commands For History:: +* Customizing the Prompt:: +* Diary and Echo Commands:: + +Data Types + +* Built-in Data Types:: +* User-defined Data Types:: +* Object Sizes:: + +Built-in Data Types + +* Numeric Objects:: +* String Objects:: +* Data Structure Objects:: + +Numeric Data Types + +* Matrices:: +* Ranges:: +* Predicates for Numeric Objects:: + +Matrices + +* Empty Matrices:: + +Strings + +* Creating Strings:: +* Searching and Replacing:: +* String Conversions:: +* Character Class Functions:: + +Variables + +* Global Variables:: +* Status of Variables:: +* Summary of Built-in Variables:: +* Defaults from the Environment:: + +Expressions + +* Index Expressions:: +* Calling Functions:: +* Arithmetic Ops:: +* Comparison Ops:: +* Boolean Expressions:: +* Assignment Ops:: +* Increment Ops:: +* Operator Precedence:: + +Calling Functions + +* Call by Value:: +* Recursion:: + +Boolean Expressions + +* Element-by-element Boolean Operators:: +* Short-circuit Boolean Operators:: + +Statements + +* The if Statement:: +* The switch Statement:: +* The while Statement:: +* The for Statement:: +* The break Statement:: +* The continue Statement:: +* The unwind_protect Statement:: +* The try Statement:: +* Continuation Lines:: + +The @code{for} Statement + +* Looping Over Structure Elements:: + +Functions and Script Files + +* Defining Functions:: +* Multiple Return Values:: +* Variable-length Argument Lists:: +* Variable-length Return Lists:: +* Returning From a Function:: +* Function Files:: +* Script Files:: +* Dynamically Linked Functions:: +* Organization of Functions:: + +Input and Output + +* Basic Input and Output:: +* C-Style I/O Functions:: + +Basic Input and Output + +* Terminal Output:: +* Terminal Input:: +* Simple File I/O:: + +C-Style I/O Functions + +* Opening and Closing Files:: +* Simple Output:: +* Line-Oriented Input:: +* Formatted Output:: +* Output Conversion for Matrices:: +* Output Conversion Syntax:: +* Table of Output Conversions:: +* Integer Conversions:: +* Floating-Point Conversions:: Other Output Conversions:: +* Other Output Conversions:: +* Formatted Input:: +* Input Conversion Syntax:: +* Table of Input Conversions:: +* Numeric Input Conversions:: +* String Input Conversions:: +* Binary I/O:: +* Temporary Files:: +* EOF and Errors:: +* File Positioning:: + +Plotting + +* Two-Dimensional Plotting:: +* Specialized Two-Dimensional Plots:: +* Three-Dimensional Plotting:: +* Plot Annotations:: +* Multiple Plots on One Page:: + +Matrix Manipulation + +* Finding Elements and Checking Conditions:: +* Rearranging Matrices:: +* Special Utility Matrices:: +* Famous Matrices:: + +Arithmetic + +* Utility Functions:: +* Complex Arithmetic:: +* Trigonometry:: +* Sums and Products:: +* Special Functions:: +* Mathematical Constants:: + +Linear Algebra + +* Basic Matrix Functions:: +* Matrix Factorizations:: +* Functions of a Matrix:: + +Quadrature + +* Functions of One Variable:: +* Orthogonal Collocation:: + +Differential Equations + +* Ordinary Differential Equations:: +* Differential-Algebraic Equations:: + +Optimization + +* Quadratic Programming:: +* Nonlinear Programming:: +* Linear Least Squares:: + +System Utilities + +* Timing Utilities:: +* Filesystem Utilities:: +* Controlling Subprocesses:: +* Process ID Information:: +* Environment Variables:: +* Current Working Directory:: +* Password Database Functions:: +* Group Database Functions:: +* System Information:: + +Tips and Standards + +* Style Tips:: Writing clean and robust programs. +* Coding Tips:: Making code run faster. +* Documentation Tips:: Writing readable documentation strings. +* Comment Tips:: Conventions for writing comments. +* Function Headers:: Standard headers for functions. + +Known Causes of Trouble with Octave + +* Actual Bugs:: Bugs we will fix later. +* Reporting Bugs:: +* Bug Criteria:: +* Bug Lists:: +* Bug Reporting:: +* Sending Patches:: +* Service:: + +Reporting Bugs + +* Bug Criteria:: +* Where: Bug Lists. Where to send your bug report. +* Reporting: Bug Reporting. How to report a bug effectively. +* Patches: Sending Patches. How to send a patch for Octave. + +Installing Octave + +* Installation Problems:: +* Binary Distributions:: + +Binary Distributions + +* Installing Octave from a Binary Distribution:: +* Creating a Binary Distribution:: + +Emacs Octave Support + +* Installing EOS:: +* Using Octave Mode:: +* Running Octave From Within Emacs:: +* Using the Emacs Info Reader for Octave:: + +Grammar + +* Keywords:: +@end menu + +@include preface.texi +@include intro.texi +@include basics.texi +@include data.texi +@include numbers.texi +@include strings.texi +@include struct.texi +@include var.texi +@include expr.texi +@include eval.texi +@include stmt.texi +@include func.texi +@include errors.texi +@include io.texi +@include plot.texi +@include matrix.texi +@include arith.texi +@include linalg.texi +@include nonlin.texi +@include quad.texi +@include diffeq.texi +@include optim.texi +@include stats.texi +@include set.texi +@include poly.texi +@include control.texi +@include signal.texi +@include image.texi +@include audio.texi +@include system.texi + +@c maybe add again later, if anyone every writes any really interesting +@c fun stuff for Octave. +@c +@c @include amuse.texi + +@c Appendices start here. Installation and bugs have to go before the +@c readline and Info appendices because we want to have separate indices +@c for them, and there appears to be no way to go back to the original +@c set of indices once a redirection has taken place. + +@include tips.texi +@include bugs.texi +@include install.texi +@include emacs.texi +@include grammar.texi +@include gpl.texi + +@include cp-idx.texi +@include vr-idx.texi +@include fn-idx.texi +@include op-idx.texi + +@contents + +@bye diff --git a/doc/interpreter/op-idx.texi b/doc/interpreter/op-idx.texi deleted file mode 100644 --- a/doc/interpreter/op-idx.texi +++ /dev/null @@ -1,8 +0,0 @@ -@c Copyright (C) 1996, 1997 John W. Eaton -@c This is part of the Octave manual. -@c For copying conditions, see the file gpl.texi. - -@node Operator Index, , Function Index, Top -@unnumbered Operator Index - -@printindex op diff --git a/doc/interpreter/op-idx.txi b/doc/interpreter/op-idx.txi new file mode 100644 --- /dev/null +++ b/doc/interpreter/op-idx.txi @@ -0,0 +1,8 @@ +@c Copyright (C) 1996, 1997 John W. Eaton +@c This is part of the Octave manual. +@c For copying conditions, see the file gpl.texi. + +@node Operator Index, , Function Index, Top +@unnumbered Operator Index + +@printindex op diff --git a/doc/interpreter/optim.texi b/doc/interpreter/optim.texi deleted file mode 100644 --- a/doc/interpreter/optim.texi +++ /dev/null @@ -1,128 +0,0 @@ -@c Copyright (C) 1996, 1997 John W. Eaton -@c This is part of the Octave manual. -@c For copying conditions, see the file gpl.texi. - -@node Optimization, Statistics, Differential Equations, Top -@chapter Optimization - -@menu -* Quadratic Programming:: -* Nonlinear Programming:: -* Linear Least Squares:: -@end menu - -@c @cindex linear programming -@cindex quadratic programming -@cindex nonlinear programming -@cindex optimization -@cindex LP -@cindex QP -@cindex NLP - -@node Quadratic Programming, Nonlinear Programming, Optimization, Optimization -@section Quadratic Programming - -@node Nonlinear Programming, Linear Least Squares, Quadratic Programming, Optimization -@section Nonlinear Programming - -@node Linear Least Squares, , Nonlinear Programming, Optimization -@section Linear Least Squares - -@deftypefn {Function File} {[@var{beta}, @var{v}, @var{r}] =} gls (@var{y}, @var{x}, @var{o}) -Generalized least squares estimation for the multivariate model -@iftex -@tex -$y = x b + e$ -with $\bar{e} = 0$ and cov(vec($e$)) = $(s^2)o$, -@end tex -@end iftex -@ifinfo -@code{@var{y} = @var{x} * @var{b} + @var{e}} with @code{mean (@var{e}) = -0} and @code{cov (vec (@var{e})) = (@var{s}^2)*@var{o}}, -@end ifinfo - where -@iftex -@tex -$y$ is a $t \times p$ matrix, $x$ is a $t \times k$ matrix, $b$ is a $k -\times p$ matrix, $e$ is a $t \times p$ matrix, and $o$ is a $tp \times -tp$ matrix. -@end tex -@end iftex -@ifinfo -@var{Y} is a @var{T} by @var{p} matrix, @var{X} is a @var{T} by @var{k} -matrix, @var{B} is a @var{k} by @var{p} matrix, @var{E} is a @var{T} by -@var{p} matrix, and @var{O} is a @var{T}@var{p} by @var{T}@var{p} -matrix. -@end ifinfo - -@noindent -Each row of Y and X is an observation and each column a variable. - -The return values @var{beta}, @var{v}, and @var{r} are defined as -follows. - -@table @var -@item beta -The GLS estimator for @var{b}. - -@item v -The GLS estimator for @code{@var{s}^2}. - -@item r -The matrix of GLS residuals, @code{@var{r} = @var{y} - @var{x} * -@var{beta}}. -@end table -@end deftypefn - -@deftypefn {Function File} {[@var{beta}, @var{sigma}, @var{r}] =} ols (@var{y}, @var{x}) -Ordinary least squares estimation for the multivariate model -@iftex -@tex -$y = x b + e$ -with -$\bar{e} = 0$, and cov(vec($e$)) = kron ($s, I$) -@end tex -@end iftex -@ifinfo -@code{@var{y} = @var{x}*@var{b} + @var{e}} with -@code{mean (@var{e}) = 0} and @code{cov (vec (@var{e})) = kron (@var{s}, -@var{I})}. -@end ifinfo - where -@iftex -@tex -$y$ is a $t \times p$ matrix, $x$ is a $t \times k$ matrix, -$b$ is a $k \times p$ matrix, and $e$ is a $t \times p$ matrix. -@end tex -@end iftex -@ifinfo -@var{y} is a @var{t} by @var{p} matrix, @var{X} is a @var{t} by @var{k} -matrix, @var{B} is a @var{k} by @var{p} matrix, and @var{e} is a @var{t} -by @var{p} matrix. -@end ifinfo - -Each row of @var{y} and @var{x} is an observation and each column a -variable. - -The return values @var{beta}, @var{sigma}, and @var{r} are defined as -follows. - -@table @var -@item beta -The OLS estimator for @var{b}, @code{@var{beta} = pinv (@var{x}) * -@var{y}}, where @code{pinv (@var{x})} denotes the pseudoinverse of -@var{x}. - -@item sigma -The OLS estimator for the matrix @var{s}, - -@example -@group -@var{sigma} = (@var{y}-@var{x}*@var{beta})' * (@var{y}-@var{x}*@var{beta}) / (@var{t}-rank(@var{x})) -@end group -@end example - -@item r -The matrix of OLS residuals, @code{@var{r} = @var{y} - @var{x} * @var{beta}}. -@end table -@end deftypefn diff --git a/doc/interpreter/optim.txi b/doc/interpreter/optim.txi new file mode 100644 --- /dev/null +++ b/doc/interpreter/optim.txi @@ -0,0 +1,128 @@ +@c Copyright (C) 1996, 1997 John W. Eaton +@c This is part of the Octave manual. +@c For copying conditions, see the file gpl.texi. + +@node Optimization, Statistics, Differential Equations, Top +@chapter Optimization + +@menu +* Quadratic Programming:: +* Nonlinear Programming:: +* Linear Least Squares:: +@end menu + +@c @cindex linear programming +@cindex quadratic programming +@cindex nonlinear programming +@cindex optimization +@cindex LP +@cindex QP +@cindex NLP + +@node Quadratic Programming, Nonlinear Programming, Optimization, Optimization +@section Quadratic Programming + +@node Nonlinear Programming, Linear Least Squares, Quadratic Programming, Optimization +@section Nonlinear Programming + +@node Linear Least Squares, , Nonlinear Programming, Optimization +@section Linear Least Squares + +@deftypefn {Function File} {[@var{beta}, @var{v}, @var{r}] =} gls (@var{y}, @var{x}, @var{o}) +Generalized least squares estimation for the multivariate model +@iftex +@tex +$y = x b + e$ +with $\bar{e} = 0$ and cov(vec($e$)) = $(s^2)o$, +@end tex +@end iftex +@ifinfo +@code{@var{y} = @var{x} * @var{b} + @var{e}} with @code{mean (@var{e}) = +0} and @code{cov (vec (@var{e})) = (@var{s}^2)*@var{o}}, +@end ifinfo + where +@iftex +@tex +$y$ is a $t \times p$ matrix, $x$ is a $t \times k$ matrix, $b$ is a $k +\times p$ matrix, $e$ is a $t \times p$ matrix, and $o$ is a $tp \times +tp$ matrix. +@end tex +@end iftex +@ifinfo +@var{Y} is a @var{T} by @var{p} matrix, @var{X} is a @var{T} by @var{k} +matrix, @var{B} is a @var{k} by @var{p} matrix, @var{E} is a @var{T} by +@var{p} matrix, and @var{O} is a @var{T}@var{p} by @var{T}@var{p} +matrix. +@end ifinfo + +@noindent +Each row of Y and X is an observation and each column a variable. + +The return values @var{beta}, @var{v}, and @var{r} are defined as +follows. + +@table @var +@item beta +The GLS estimator for @var{b}. + +@item v +The GLS estimator for @code{@var{s}^2}. + +@item r +The matrix of GLS residuals, @code{@var{r} = @var{y} - @var{x} * +@var{beta}}. +@end table +@end deftypefn + +@deftypefn {Function File} {[@var{beta}, @var{sigma}, @var{r}] =} ols (@var{y}, @var{x}) +Ordinary least squares estimation for the multivariate model +@iftex +@tex +$y = x b + e$ +with +$\bar{e} = 0$, and cov(vec($e$)) = kron ($s, I$) +@end tex +@end iftex +@ifinfo +@code{@var{y} = @var{x}*@var{b} + @var{e}} with +@code{mean (@var{e}) = 0} and @code{cov (vec (@var{e})) = kron (@var{s}, +@var{I})}. +@end ifinfo + where +@iftex +@tex +$y$ is a $t \times p$ matrix, $x$ is a $t \times k$ matrix, +$b$ is a $k \times p$ matrix, and $e$ is a $t \times p$ matrix. +@end tex +@end iftex +@ifinfo +@var{y} is a @var{t} by @var{p} matrix, @var{X} is a @var{t} by @var{k} +matrix, @var{B} is a @var{k} by @var{p} matrix, and @var{e} is a @var{t} +by @var{p} matrix. +@end ifinfo + +Each row of @var{y} and @var{x} is an observation and each column a +variable. + +The return values @var{beta}, @var{sigma}, and @var{r} are defined as +follows. + +@table @var +@item beta +The OLS estimator for @var{b}, @code{@var{beta} = pinv (@var{x}) * +@var{y}}, where @code{pinv (@var{x})} denotes the pseudoinverse of +@var{x}. + +@item sigma +The OLS estimator for the matrix @var{s}, + +@example +@group +@var{sigma} = (@var{y}-@var{x}*@var{beta})' * (@var{y}-@var{x}*@var{beta}) / (@var{t}-rank(@var{x})) +@end group +@end example + +@item r +The matrix of OLS residuals, @code{@var{r} = @var{y} - @var{x} * @var{beta}}. +@end table +@end deftypefn diff --git a/doc/interpreter/plot.texi b/doc/interpreter/plot.texi deleted file mode 100644 --- a/doc/interpreter/plot.texi +++ /dev/null @@ -1,747 +0,0 @@ -@c Copyright (C) 1996, 1997 John W. Eaton -@c This is part of the Octave manual. -@c For copying conditions, see the file gpl.texi. - -@node Plotting, Matrix Manipulation, Input and Output, Top -@chapter Plotting - -All of Octave's plotting functions use @code{gnuplot} to handle the -actual graphics. There are two low-level functions, @code{gplot} and -@code{gsplot}, that behave almost exactly like the corresponding -@code{gnuplot} functions @code{plot} and @code{splot}. A number of -other higher level plotting functions, patterned after the graphics -functions found in @sc{Matlab} version 3.5, are also available. -These higher level functions are all implemented in terms of the two -low-level plotting functions. - -@menu -* Two-Dimensional Plotting:: -* Specialized Two-Dimensional Plots:: -* Three-Dimensional Plotting:: -* Plot Annotations:: -* Multiple Plots on One Page:: -@end menu - -@node Two-Dimensional Plotting, Specialized Two-Dimensional Plots, Plotting, Plotting -@section Two-Dimensional Plotting - -@deffn {Command} gplot @var{ranges} @var{expression} @var{using} @var{title} @var{style} -Generate a 2-dimensional plot. - -The @var{ranges}, @var{using}, @var{title}, and @var{style} arguments -are optional, and the @var{using}, @var{title} and @var{style} -qualifiers may appear in any order after the expression. You may plot -multiple expressions with a single command by separating them with -commas. Each expression may have its own set of qualifiers. - -The optional item @var{ranges} has the syntax - -@example -[ x_lo : x_up ] [ y_lo : y_up ] -@end example - -@noindent -and may be used to specify the ranges for the axes of the plot, -independent of the actual range of the data. The range for the y axes -and any of the individual limits may be omitted. A range @code{[:]} -indicates that the default limits should be used. This normally means -that a range just large enough to include all the data points will be -used. - -The expression to be plotted must not contain any literal matrices -(e.g. @code{[ 1, 2; 3, 4 ]}) since it is nearly impossible to -distinguish a plot range from a matrix of data. - -See the help for @code{gnuplot} for a description of the syntax for the -optional items. - -By default, the @code{gplot} command plots the second column of a matrix -versus the first. If the matrix only has one column, it is taken as a -vector of y-coordinates and the x-coordinate is taken as the element -index, starting with zero. For example, - -@example -gplot rand (100,1) with linespoints -@end example - -@noindent -will plot 100 random values and connect them with lines. When -@code{gplot} is used to plot a column vector, the indices of the -elements are taken as x values. - - If there are more than two columns, you can -choose which columns to plot with the @var{using} qualifier. For -example, given the data - -@example -x = (-10:0.1:10)'; -data = [x, sin(x), cos(x)]; -@end example - -@noindent -the command - -@example -gplot [-11:11] [-1.1:1.1] \ - data with lines, data using 1:3 with impulses -@end example - -@noindent -will plot two lines. The first line is generated by the command -@code{data with lines}, and is a graph of the sine function over the -range @minus{}10 to 10. The data is taken from the first two columns of -the matrix because columns to plot were not specified with the -@var{using} qualifier. - -The clause @code{using 1:3} in the second part of this plot command -specifies that the first and third columns of the matrix @code{data} -should be taken as the values to plot. - -In this example, the ranges have been explicitly specified to be a bit -larger than the actual range of the data so that the curves do not touch -the border of the plot. -@end deffn - -@deffn {Command} gset options -@deffnx {Command} gshow options -@deffnx {Command} replot options -In addition to the basic plotting commands, the whole range of -@code{gset} and @code{gshow} commands from @code{gnuplot} are available, -as is @code{replot}. - -@findex set -@findex show -Note that in Octave 2.0, the @code{set} and @code{show} commands were -renamed to @code{gset} and @code{gshow} in order to allow for -compatibility with the @sc{Matlab} graphics and GUI commands in a future -version of Octave. (For now, the old @code{set} and @code{show} -commands do work, but they print an annoying warning message to try to -get people to switch to using @code{gset} and @code{gshow}.) - -The @code{gset} and @code{gshow} commands allow you to set and show -@code{gnuplot} parameters. For more information about the @code{gset} -and @code{gshow} commands, see the documentation for @code{set} and -@code{show} in the @code{gnuplot} user's guide (also available on line -if you run @code{gnuplot} directly, instead of running it from Octave). - -The @code{replot} command allows you to force the plot to be -redisplayed. This is useful if you have changed something about the -plot, such as the title or axis labels. The @code{replot} command also -accepts the same arguments as @code{gplot} or @code{gsplot} (except for -data ranges) so you can add additional lines to existing plots. - -For example, - -@example -gset term tek40 -gset output "/dev/plotter" -gset title "sine with lines and cosine with impulses" -replot "sin (x) w l" -@end example - -will change the terminal type for plotting, add a title to the current -plot, add a graph of -@iftex -@tex -$\sin(x)$ -@end tex -@end iftex -@ifinfo -sin (x) -@end ifinfo -to the plot, and force the new plot to be -sent to the plot device. This last step is normally required in order -to update the plot. This default is reasonable for slow terminals or -hardcopy output devices because even when you are adding additional -lines with a replot command, gnuplot always redraws the entire plot, and -you probably don't want to have a completely new plot generated every -time something as minor as an axis label changes. - -@findex shg -The command @code{shg} is equivalent to executing @code{replot} without -any arguments. -@end deffn - -@defvr {Built-in Variable} automatic_replot -You can tell Octave to redisplay the plot each time anything about it -changes by setting the value of the builtin variable -@code{automatic_replot} to a nonzero value. Since this is fairly -inefficient, the default value is 0. -@end defvr - -Note that NaN values in the plot data are automatically omitted, and -Inf values are converted to a very large value before calling gnuplot. - -@c XXX FIXME XXX -- add info about what to do to get plots on remote X -@c terminals. People often forget how to properly set DISPLAY and run -@c xhost. - -@c XXX FIXME XXX -- add info about getting paper copies of plots. - -The @sc{Matlab}-style two-dimensional plotting commands are: - -@cindex plotting -@cindex graphics - -@deftypefn {Function File} {} plot (@var{args}) -This function produces two-dimensional plots. Many different -combinations of arguments are possible. The simplest form is - -@example -plot (@var{y}) -@end example - -@noindent -where the argument is taken as the set of @var{y} coordinates and the -@var{x} coordinates are taken to be the indices of the elements, -starting with 1. - -If more than one argument is given, they are interpreted as - -@example -plot (@var{x}, @var{y}, @var{fmt} ...) -@end example - -@noindent -where @var{y} and @var{fmt} are optional, and any number of argument -sets may appear. The @var{x} and @var{y} values are -interpreted as follows: - -@itemize @bullet -@item -If a single data argument is supplied, it is taken as the set of @var{y} -coordinates and the @var{x} coordinates are taken to be the indices of -the elements, starting with 1. - -@item -If the first argument is a vector and the second is a matrix, the -the vector is plotted versus the columns (or rows) of the matrix. -(using whichever combination matches, with columns tried first.) - -@item -If the first argument is a matrix and the second is a vector, the -the columns (or rows) of the matrix are plotted versus the vector. -(using whichever combination matches, with columns tried first.) - -@item -If both arguments are vectors, the elements of @var{y} are plotted versus -the elements of @var{x}. - -@item -If both arguments are matrices, the columns of @var{y} are plotted -versus the columns of @var{x}. In this case, both matrices must have -the same number of rows and columns and no attempt is made to transpose -the arguments to make the number of rows match. - -If both arguments are scalars, a single point is plotted. -@end itemize - -The @var{fmt} argument, if present is interpreted as follows. If -@var{fmt} is missing, the default gnuplot line style is assumed. - -@table @samp -@item - -Set lines plot style (default). - -@item . -Set dots plot style. - -@item @@ -Set points plot style. - -@item -@@ -Set linespoints plot style. - -@item ^ -Set impulses plot style. - -@item L -Set steps plot style. - -@item # -Set boxes plot style. - -@item ~ -Set errorbars plot style. - -@item #~ -Set boxerrorbars plot style. - -@item @var{n} -Interpreted as the plot color if @var{n} is an integer in the range 1 to -6. - -@item @var{nm} -If @var{nm} is a two digit integer and @var{m} is an integer in the -range 1 to 6, @var{m} is interpreted as the point style. This is only -valid in combination with the @code{@@} or @code{-@@} specifiers. - -@item @var{c} -If @var{c} is one of @code{"r"}, @code{"g"}, @code{"b"}, @code{"m"}, -@code{"c"}, or @code{"w"}, it is interpreted as the plot color (red, -green, blue, magenta, cyan, or white). - -@item + -@itemx * -@itemx o -@itemx x -Used in combination with the points or linespoints styles, set the point -style. -@end table - -The color line styles have the following meanings on terminals that -support color. - -@example -Number Gnuplot colors (lines)points style - 1 red * - 2 green + - 3 blue o - 4 magenta x - 5 cyan house - 6 brown there exists -@end example - -Here are some plot examples: - -@example -plot (x, y, "@@12", x, y2, x, y3, "4", x, y4, "+") -@end example - -This command will plot @code{y} with points of type 2 (displayed as -@samp{+}) and color 1 (red), @code{y2} with lines, @code{y3} with lines of -color 4 (magenta) and @code{y4} with points displayed as @samp{+}. - -@example -plot (b, "*") -@end example - -This command will plot the data in the variable @code{b} will be plotted -with points displayed as @samp{*}. -@end deftypefn - -@deftypefn {Function File} {} hold @var{args} -Tell Octave to `hold' the current data on the plot when executing -subsequent plotting commands. This allows you to execute a series of -plot commands and have all the lines end up on the same figure. The -default is for each new plot command to clear the plot device first. -For example, the command - -@example -hold on -@end example - -@noindent -turns the hold state on. An argument of @code{off} turns the hold state -off, and @code{hold} with no arguments toggles the current hold state. -@end deftypefn - -@deftypefn {Function File} {} ishold -Return 1 if the next line will be added to the current plot, or 0 if -the plot device will be cleared before drawing the next line. -@end deftypefn - -@deftypefn {Function File} {} clearplot -@deftypefnx {Function File} {} clg -Clear the plot window and any titles or axis labels. The name -@code{clg} is aliased to @code{clearplot} for compatibility with @sc{Matlab}. - -The commands @kbd{gplot clear}, @kbd{gsplot clear}, and @kbd{replot -clear} are equivalent to @code{clearplot}. (Previously, commands like -@kbd{gplot clear} would evaluate @code{clear} as an ordinary expression -and clear all the visible variables.) -@end deftypefn - -@deftypefn {Function File} {} closeplot -Close stream to the @code{gnuplot} subprocess. If you are using X11, -this will close the plot window. -@end deftypefn - -@deftypefn {Function File} {} purge_tmp_files -Delete the temporary files created by the plotting commands. - -Octave creates temporary data files for @code{gnuplot} and then sends -commands to @code{gnuplot} through a pipe. Octave will delete the -temporary files on exit, but if you are doing a lot of plotting you may -want to clean up in the middle of a session. - -A future version of Octave will eliminate the need to use temporary -files to hold the plot data. -@end deftypefn - -@deftypefn {Function File} {} axis (@var{limits}) -Sets the axis limits for plots. - -The argument @var{limits} should be a 2, 4, or 6 element vector. The -first and second elements specify the lower and upper limits for the x -axis. The third and fourth specify the limits for the y axis, and the -fifth and sixth specify the limits for the z axis. - -With no arguments, @code{axis} turns autoscaling on. - -If your plot is already drawn, then you need to use @code{replot} before -the new axis limits will take effect. You can get this to happen -automatically by setting the built-in variable @code{automatic_replot} -to a nonzero value. -@end deftypefn - -@node Specialized Two-Dimensional Plots, Three-Dimensional Plotting, Two-Dimensional Plotting, Plotting -@section Specialized Two-Dimensional Plots - -@deftypefn {Function File} {} bar (@var{x}, @var{y}) -Given two vectors of x-y data, @code{bar} produces a bar graph. - -If only one argument is given, it is taken as a vector of y-values -and the x coordinates are taken to be the indices of the elements. - -If two output arguments are specified, the data are generated but -not plotted. For example, - -@example -bar (x, y); -@end example - -@noindent -and - -@example -[xb, yb] = bar (x, y); -plot (xb, yb); -@end example - -@noindent -are equivalent. -@end deftypefn - -@deftypefn {Function File} {} contour (@var{z}, @var{n}, @var{x}, @var{y}) -Make a contour plot of the three-dimensional surface described by -@var{z}. Someone needs to improve @code{gnuplot}'s contour routines -before this will be very useful. -@end deftypefn - -@deftypefn {Function File} {} hist (@var{y}, @var{x}) -Produce histogram counts or plots. - -With one vector input argument, plot a histogram of the values with -10 bins. The range of the histogram bins is determined by the range -of the data. - -Given a second scalar argument, use that as the number of bins. - -Given a second vector argument, use that as the centers of the bins, -with the width of the bins determined from the adjacent values in -the vector. - -Extreme values are lumped in the first and last bins. - -With two output arguments, produce the values @var{nn} and @var{xx} such -that @code{bar (@var{xx}, @var{nn})} will plot the histogram. -@end deftypefn - -@deftypefn {Function File} {} loglog (@var{args}) -Make a two-dimensional plot using log scales for both axes. See the -description of @code{plot} above for a description of the arguments that -@code{loglog} will accept. -@end deftypefn - -@deftypefn {Function File} {} polar (@var{theta}, @var{rho}) -Make a two-dimensional plot given polar the coordinates @var{theta} and -@var{rho}. -@end deftypefn - -@deftypefn {Function File} {} semilogx (@var{args}) -Make a two-dimensional plot using a log scale for the @var{x} axis. See -the description of @code{plot} above for a description of the arguments -that @code{semilogx} will accept. -@end deftypefn - -@deftypefn {Function File} {} semilogy (@var{args}) -Make a two-dimensional plot using a log scale for the @var{y} axis. See -the description of @code{plot} above for a description of the arguments -that @code{semilogy} will accept. -@end deftypefn - -@deftypefn {Function File} {} stairs (@var{x}, @var{y}) -Given two vectors of x-y data, bar produces a `stairstep' plot. - -If only one argument is given, it is taken as a vector of y-values -and the x coordinates are taken to be the indices of the elements. - -If two output arguments are specified, the data are generated but -not plotted. For example, - -@example -stairs (x, y); -@end example - -@noindent -and - -@example -[xs, ys] = stairs (x, y); -plot (xs, ys); -@end example - -@noindent -are equivalent. -@end deftypefn - -@node Three-Dimensional Plotting, Plot Annotations, Specialized Two-Dimensional Plots, Plotting -@section Three-Dimensional Plotting - -@deffn {Command} gsplot @var{ranges} @var{expression} @var{using} @var{title} @var{style} -Generate a 3-dimensional plot. - -The @var{ranges}, @var{using}, @var{title}, and @var{style} arguments -are optional, and the @var{using}, @var{title} and @var{style} -qualifiers may appear in any order after the expression. You may plot -multiple expressions with a single command by separating them with -commas. Each expression may have its own set of qualifiers. - -The optional item @var{ranges} has the syntax - -@example -[ x_lo : x_up ] [ y_lo : y_up ] [ z_lo : z_up ] -@end example - -@noindent -and may be used to specify the ranges for the axes of the plot, -independent of the actual range of the data. The range for the y and z -axes and any of the individual limits may be omitted. A range -@code{[:]} indicates that the default limits should be used. This -normally means that a range just large enough to include all the data -points will be used. - -The expression to be plotted must not contain any literal matrices (e.g. -@code{[ 1, 2; 3, 4 ]}) since it is nearly impossible to distinguish a -plot range from a matrix of data. - -See the help for @code{gnuplot} for a description of the syntax for the -optional items. - -By default, the @code{gsplot} command plots each column of the -expression as the z value, using the row index as the x value, and the -column index as the y value. The indices are counted from zero, not -one. For example, - -@example -gsplot rand (5, 2) -@end example - -@noindent -will plot a random surface, with the x and y values taken from the row -and column indices of the matrix. - -If parametric plotting mode is set (using the command -@kbd{gset parametric}, then @code{gsplot} takes the columns of the -matrix three at a time as the x, y and z values that define a line in -three space. Any extra columns are ignored, and the x and y values are -expected to be sorted. For example, with @code{parametric} set, it -makes sense to plot a matrix like -@iftex -@tex -$$ -\left[\matrix{ -1 & 1 & 3 & 2 & 1 & 6 & 3 & 1 & 9 \cr -1 & 2 & 2 & 2 & 2 & 5 & 3 & 2 & 8 \cr -1 & 3 & 1 & 2 & 3 & 4 & 3 & 3 & 7}\right] -$$ -@end tex -@end iftex -@ifinfo - -@example -1 1 3 2 1 6 3 1 9 -1 2 2 2 2 5 3 2 8 -1 3 1 2 3 4 3 3 7 -@end example -@end ifinfo - -@noindent -but not @code{rand (5, 30)}. -@end deffn - -The @sc{Matlab}-style three-dimensional plotting commands are: - -@deftypefn {Function File} {} mesh (@var{x}, @var{y}, @var{z}) -Plot a mesh given matrices @code{x}, and @var{y} from @code{meshdom} and -a matrix @var{z} corresponding to the @var{x} and @var{y} coordinates of -the mesh. -@end deftypefn - -@deftypefn {Function File} {} meshdom (@var{x}, @var{y}) -Given vectors of @var{x} and @var{y} coordinates, return two matrices -corresponding to the @var{x} and @var{y} coordinates of the mesh. - -See the file @file{sombrero.m} for an example of using @code{mesh} and -@code{meshdom}. -@end deftypefn - -@defvr {Built-in Variable} gnuplot_binary -The name of the program invoked by the plot command. The default value -is @code{"gnuplot"}. @xref{Installation}. -@end defvr - -@defvr {Built-in Variable} gnuplot_has_frames -If the value of this variable is nonzero, Octave assumes that your copy -of gnuplot has support for multiple frames that is included in recent -3.6beta releases. It's initial value is determined by configure, but it -can be changed in your startup script or at the command line in case -configure got it wrong, or if you upgrade your gnuplot installation. -@end defvr - -@deftypefn {Function File} {} figure (@var{n}) -Set the current plot window to plot window @var{n}. This function -currently requires X11 and a version of gnuplot that supports multiple -frames. -@end deftypefn - -@defvr {Built-in Variable} gnuplot_has_multiplot -If the value of this variable is nonzero, Octave assumes that your copy -of gnuplot has the multiplot support that is included in recent -3.6beta releases. It's initial value is determined by configure, but it -can be changed in your startup script or at the command line in case -configure got it wrong, or if you upgrade your gnuplot installation. -@end defvr - -@node Plot Annotations, Multiple Plots on One Page, Three-Dimensional Plotting, Plotting -@section Plot Annotations - -@deftypefn {Function File} {} grid -For two-dimensional plotting, force the display of a grid on the plot. -@end deftypefn - -@deftypefn {Function File} {} title (@var{string}) -Specify a title for the plot. If you already have a plot displayed, use -the command @code{replot} to redisplay it with the new title. -@end deftypefn - -@deftypefn {Function File} {} xlabel (@var{string}) -@deftypefnx {Function File} {} ylabel (@var{string}) -@deftypefnx {Function File} {} zlabel (@var{string}) -Specify x, y, and z axis labels for the plot. If you already have a plot -displayed, use the command @code{replot} to redisplay it with the new -labels. -@end deftypefn - -@node Multiple Plots on One Page, , Plot Annotations, Plotting -@section Multiple Plots on One Page - -The following functions all require a version of @code{gnuplot} that -supports the multiplot feature. - -@deftypefn {Function File} {} mplot (@var{x}, @var{y}) -@deftypefnx {Function File} {} mplot (@var{x}, @var{y}, @var{fmt}) -@deftypefnx {Function File} {} mplot (@var{x1}, @var{y1}, @var{x2}, @var{y2}) -This is a modified version of the @code{plot} function that works with -the multiplot version of @code{gnuplot} to plot multiple plots per page. -This plot version automatically advances to the next subplot position -after each set of arguments are processed. - -See the description of the @var{plot} function for the various options. -@end deftypefn - -@deftypefn {Function File} {} multiplot (@var{xn}, @var{yn}) -Sets and resets multiplot mode. - -If the arguments are non-zero, @code{multiplot} will set up multiplot -mode with @var{xn}, @var{yn} subplots along the @var{x} and @var{y} -axes. If both arguments are zero, @code{multiplot} closes multiplot -mode. -@end deftypefn - -@deftypefn {Function File} {} oneplot () -If in multiplot mode, switches to single plot mode. -@end deftypefn - -@deftypefn {Function File} {} plot_border (...) -Multiple arguments allowed to specify the sides on which the border -is shown. Allowed arguments include: - -@table @code -@item "blank" -No borders displayed. - -@item "all" -All borders displayed - -@item "north" -North Border - -@item "south" -South Border - -@item "east" -East Border - -@item "west" -West Border -@end table - -@noindent -The arguments may be abbreviated to single characters. Without any -arguments, @code{plot_border} turns borders off. -@end deftypefn - -@deftypefn {Function File} {} subplot (@var{rows}, @var{cols}, @var{index}) -@deftypefnx {Function File} {} subplot (@var{rcn}) -Sets @code{gnuplot} in multiplot mode and plots in location -given by index (there are @var{cols} by @var{rows} subwindows). - -Input: - -@table @var -@item rows -Number of rows in subplot grid. - -@item columns -Number of columns in subplot grid. - -@item index -Index of subplot where to make the next plot. -@end table - -If only one argument is supplied, then it must be a three digit value -specifying the location in digits 1 (rows) and 2 (columns) and the plot -index in digit 3. - -The plot index runs row-wise. First all the columns in a row are filled -and then the next row is filled. - -For example, a plot with 4 by 2 grid will have plot indices running as -follows: -@iftex -@tex -\vskip 10pt -\hfil\vbox{\offinterlineskip\hrule -\halign{\vrule#&&\qquad\hfil#\hfil\qquad\vrule\cr -height13pt&1&2&3&4\cr height12pt&&&&\cr\noalign{\hrule} -height13pt&5&6&7&8\cr height12pt&&&&\cr\noalign{\hrule}}} -\hfil -\vskip 10pt -@end tex -@end iftex -@ifinfo -@display -@group -+-----+-----+-----+-----+ -| 1 | 2 | 3 | 4 | -+-----+-----+-----+-----+ -| 5 | 6 | 7 | 8 | -+-----+-----+-----+-----+ -@end group -@end display -@end ifinfo -@end deftypefn - -@deftypefn {Function File} {} subwindow (@var{xn}, @var{yn}) -Sets the subwindow position in multiplot mode for the next plot. The -multiplot mode has to be previously initialized using the -@code{multiplot} function, otherwise this command just becomes an alias -to @code{multiplot} -@end deftypefn - -@deftypefn {Function File} {} top_title (@var{string}) -@deftypefnx {Function File} {} bottom_title (@var{string}) -Makes a title with text @var{string} at the top (bottom) of the plot. -@end deftypefn diff --git a/doc/interpreter/plot.txi b/doc/interpreter/plot.txi new file mode 100644 --- /dev/null +++ b/doc/interpreter/plot.txi @@ -0,0 +1,747 @@ +@c Copyright (C) 1996, 1997 John W. Eaton +@c This is part of the Octave manual. +@c For copying conditions, see the file gpl.texi. + +@node Plotting, Matrix Manipulation, Input and Output, Top +@chapter Plotting + +All of Octave's plotting functions use @code{gnuplot} to handle the +actual graphics. There are two low-level functions, @code{gplot} and +@code{gsplot}, that behave almost exactly like the corresponding +@code{gnuplot} functions @code{plot} and @code{splot}. A number of +other higher level plotting functions, patterned after the graphics +functions found in @sc{Matlab} version 3.5, are also available. +These higher level functions are all implemented in terms of the two +low-level plotting functions. + +@menu +* Two-Dimensional Plotting:: +* Specialized Two-Dimensional Plots:: +* Three-Dimensional Plotting:: +* Plot Annotations:: +* Multiple Plots on One Page:: +@end menu + +@node Two-Dimensional Plotting, Specialized Two-Dimensional Plots, Plotting, Plotting +@section Two-Dimensional Plotting + +@deffn {Command} gplot @var{ranges} @var{expression} @var{using} @var{title} @var{style} +Generate a 2-dimensional plot. + +The @var{ranges}, @var{using}, @var{title}, and @var{style} arguments +are optional, and the @var{using}, @var{title} and @var{style} +qualifiers may appear in any order after the expression. You may plot +multiple expressions with a single command by separating them with +commas. Each expression may have its own set of qualifiers. + +The optional item @var{ranges} has the syntax + +@example +[ x_lo : x_up ] [ y_lo : y_up ] +@end example + +@noindent +and may be used to specify the ranges for the axes of the plot, +independent of the actual range of the data. The range for the y axes +and any of the individual limits may be omitted. A range @code{[:]} +indicates that the default limits should be used. This normally means +that a range just large enough to include all the data points will be +used. + +The expression to be plotted must not contain any literal matrices +(e.g. @code{[ 1, 2; 3, 4 ]}) since it is nearly impossible to +distinguish a plot range from a matrix of data. + +See the help for @code{gnuplot} for a description of the syntax for the +optional items. + +By default, the @code{gplot} command plots the second column of a matrix +versus the first. If the matrix only has one column, it is taken as a +vector of y-coordinates and the x-coordinate is taken as the element +index, starting with zero. For example, + +@example +gplot rand (100,1) with linespoints +@end example + +@noindent +will plot 100 random values and connect them with lines. When +@code{gplot} is used to plot a column vector, the indices of the +elements are taken as x values. + + If there are more than two columns, you can +choose which columns to plot with the @var{using} qualifier. For +example, given the data + +@example +x = (-10:0.1:10)'; +data = [x, sin(x), cos(x)]; +@end example + +@noindent +the command + +@example +gplot [-11:11] [-1.1:1.1] \ + data with lines, data using 1:3 with impulses +@end example + +@noindent +will plot two lines. The first line is generated by the command +@code{data with lines}, and is a graph of the sine function over the +range @minus{}10 to 10. The data is taken from the first two columns of +the matrix because columns to plot were not specified with the +@var{using} qualifier. + +The clause @code{using 1:3} in the second part of this plot command +specifies that the first and third columns of the matrix @code{data} +should be taken as the values to plot. + +In this example, the ranges have been explicitly specified to be a bit +larger than the actual range of the data so that the curves do not touch +the border of the plot. +@end deffn + +@deffn {Command} gset options +@deffnx {Command} gshow options +@deffnx {Command} replot options +In addition to the basic plotting commands, the whole range of +@code{gset} and @code{gshow} commands from @code{gnuplot} are available, +as is @code{replot}. + +@findex set +@findex show +Note that in Octave 2.0, the @code{set} and @code{show} commands were +renamed to @code{gset} and @code{gshow} in order to allow for +compatibility with the @sc{Matlab} graphics and GUI commands in a future +version of Octave. (For now, the old @code{set} and @code{show} +commands do work, but they print an annoying warning message to try to +get people to switch to using @code{gset} and @code{gshow}.) + +The @code{gset} and @code{gshow} commands allow you to set and show +@code{gnuplot} parameters. For more information about the @code{gset} +and @code{gshow} commands, see the documentation for @code{set} and +@code{show} in the @code{gnuplot} user's guide (also available on line +if you run @code{gnuplot} directly, instead of running it from Octave). + +The @code{replot} command allows you to force the plot to be +redisplayed. This is useful if you have changed something about the +plot, such as the title or axis labels. The @code{replot} command also +accepts the same arguments as @code{gplot} or @code{gsplot} (except for +data ranges) so you can add additional lines to existing plots. + +For example, + +@example +gset term tek40 +gset output "/dev/plotter" +gset title "sine with lines and cosine with impulses" +replot "sin (x) w l" +@end example + +will change the terminal type for plotting, add a title to the current +plot, add a graph of +@iftex +@tex +$\sin(x)$ +@end tex +@end iftex +@ifinfo +sin (x) +@end ifinfo +to the plot, and force the new plot to be +sent to the plot device. This last step is normally required in order +to update the plot. This default is reasonable for slow terminals or +hardcopy output devices because even when you are adding additional +lines with a replot command, gnuplot always redraws the entire plot, and +you probably don't want to have a completely new plot generated every +time something as minor as an axis label changes. + +@findex shg +The command @code{shg} is equivalent to executing @code{replot} without +any arguments. +@end deffn + +@defvr {Built-in Variable} automatic_replot +You can tell Octave to redisplay the plot each time anything about it +changes by setting the value of the builtin variable +@code{automatic_replot} to a nonzero value. Since this is fairly +inefficient, the default value is 0. +@end defvr + +Note that NaN values in the plot data are automatically omitted, and +Inf values are converted to a very large value before calling gnuplot. + +@c XXX FIXME XXX -- add info about what to do to get plots on remote X +@c terminals. People often forget how to properly set DISPLAY and run +@c xhost. + +@c XXX FIXME XXX -- add info about getting paper copies of plots. + +The @sc{Matlab}-style two-dimensional plotting commands are: + +@cindex plotting +@cindex graphics + +@deftypefn {Function File} {} plot (@var{args}) +This function produces two-dimensional plots. Many different +combinations of arguments are possible. The simplest form is + +@example +plot (@var{y}) +@end example + +@noindent +where the argument is taken as the set of @var{y} coordinates and the +@var{x} coordinates are taken to be the indices of the elements, +starting with 1. + +If more than one argument is given, they are interpreted as + +@example +plot (@var{x}, @var{y}, @var{fmt} ...) +@end example + +@noindent +where @var{y} and @var{fmt} are optional, and any number of argument +sets may appear. The @var{x} and @var{y} values are +interpreted as follows: + +@itemize @bullet +@item +If a single data argument is supplied, it is taken as the set of @var{y} +coordinates and the @var{x} coordinates are taken to be the indices of +the elements, starting with 1. + +@item +If the first argument is a vector and the second is a matrix, the +the vector is plotted versus the columns (or rows) of the matrix. +(using whichever combination matches, with columns tried first.) + +@item +If the first argument is a matrix and the second is a vector, the +the columns (or rows) of the matrix are plotted versus the vector. +(using whichever combination matches, with columns tried first.) + +@item +If both arguments are vectors, the elements of @var{y} are plotted versus +the elements of @var{x}. + +@item +If both arguments are matrices, the columns of @var{y} are plotted +versus the columns of @var{x}. In this case, both matrices must have +the same number of rows and columns and no attempt is made to transpose +the arguments to make the number of rows match. + +If both arguments are scalars, a single point is plotted. +@end itemize + +The @var{fmt} argument, if present is interpreted as follows. If +@var{fmt} is missing, the default gnuplot line style is assumed. + +@table @samp +@item - +Set lines plot style (default). + +@item . +Set dots plot style. + +@item @@ +Set points plot style. + +@item -@@ +Set linespoints plot style. + +@item ^ +Set impulses plot style. + +@item L +Set steps plot style. + +@item # +Set boxes plot style. + +@item ~ +Set errorbars plot style. + +@item #~ +Set boxerrorbars plot style. + +@item @var{n} +Interpreted as the plot color if @var{n} is an integer in the range 1 to +6. + +@item @var{nm} +If @var{nm} is a two digit integer and @var{m} is an integer in the +range 1 to 6, @var{m} is interpreted as the point style. This is only +valid in combination with the @code{@@} or @code{-@@} specifiers. + +@item @var{c} +If @var{c} is one of @code{"r"}, @code{"g"}, @code{"b"}, @code{"m"}, +@code{"c"}, or @code{"w"}, it is interpreted as the plot color (red, +green, blue, magenta, cyan, or white). + +@item + +@itemx * +@itemx o +@itemx x +Used in combination with the points or linespoints styles, set the point +style. +@end table + +The color line styles have the following meanings on terminals that +support color. + +@example +Number Gnuplot colors (lines)points style + 1 red * + 2 green + + 3 blue o + 4 magenta x + 5 cyan house + 6 brown there exists +@end example + +Here are some plot examples: + +@example +plot (x, y, "@@12", x, y2, x, y3, "4", x, y4, "+") +@end example + +This command will plot @code{y} with points of type 2 (displayed as +@samp{+}) and color 1 (red), @code{y2} with lines, @code{y3} with lines of +color 4 (magenta) and @code{y4} with points displayed as @samp{+}. + +@example +plot (b, "*") +@end example + +This command will plot the data in the variable @code{b} will be plotted +with points displayed as @samp{*}. +@end deftypefn + +@deftypefn {Function File} {} hold @var{args} +Tell Octave to `hold' the current data on the plot when executing +subsequent plotting commands. This allows you to execute a series of +plot commands and have all the lines end up on the same figure. The +default is for each new plot command to clear the plot device first. +For example, the command + +@example +hold on +@end example + +@noindent +turns the hold state on. An argument of @code{off} turns the hold state +off, and @code{hold} with no arguments toggles the current hold state. +@end deftypefn + +@deftypefn {Function File} {} ishold +Return 1 if the next line will be added to the current plot, or 0 if +the plot device will be cleared before drawing the next line. +@end deftypefn + +@deftypefn {Function File} {} clearplot +@deftypefnx {Function File} {} clg +Clear the plot window and any titles or axis labels. The name +@code{clg} is aliased to @code{clearplot} for compatibility with @sc{Matlab}. + +The commands @kbd{gplot clear}, @kbd{gsplot clear}, and @kbd{replot +clear} are equivalent to @code{clearplot}. (Previously, commands like +@kbd{gplot clear} would evaluate @code{clear} as an ordinary expression +and clear all the visible variables.) +@end deftypefn + +@deftypefn {Function File} {} closeplot +Close stream to the @code{gnuplot} subprocess. If you are using X11, +this will close the plot window. +@end deftypefn + +@deftypefn {Function File} {} purge_tmp_files +Delete the temporary files created by the plotting commands. + +Octave creates temporary data files for @code{gnuplot} and then sends +commands to @code{gnuplot} through a pipe. Octave will delete the +temporary files on exit, but if you are doing a lot of plotting you may +want to clean up in the middle of a session. + +A future version of Octave will eliminate the need to use temporary +files to hold the plot data. +@end deftypefn + +@deftypefn {Function File} {} axis (@var{limits}) +Sets the axis limits for plots. + +The argument @var{limits} should be a 2, 4, or 6 element vector. The +first and second elements specify the lower and upper limits for the x +axis. The third and fourth specify the limits for the y axis, and the +fifth and sixth specify the limits for the z axis. + +With no arguments, @code{axis} turns autoscaling on. + +If your plot is already drawn, then you need to use @code{replot} before +the new axis limits will take effect. You can get this to happen +automatically by setting the built-in variable @code{automatic_replot} +to a nonzero value. +@end deftypefn + +@node Specialized Two-Dimensional Plots, Three-Dimensional Plotting, Two-Dimensional Plotting, Plotting +@section Specialized Two-Dimensional Plots + +@deftypefn {Function File} {} bar (@var{x}, @var{y}) +Given two vectors of x-y data, @code{bar} produces a bar graph. + +If only one argument is given, it is taken as a vector of y-values +and the x coordinates are taken to be the indices of the elements. + +If two output arguments are specified, the data are generated but +not plotted. For example, + +@example +bar (x, y); +@end example + +@noindent +and + +@example +[xb, yb] = bar (x, y); +plot (xb, yb); +@end example + +@noindent +are equivalent. +@end deftypefn + +@deftypefn {Function File} {} contour (@var{z}, @var{n}, @var{x}, @var{y}) +Make a contour plot of the three-dimensional surface described by +@var{z}. Someone needs to improve @code{gnuplot}'s contour routines +before this will be very useful. +@end deftypefn + +@deftypefn {Function File} {} hist (@var{y}, @var{x}) +Produce histogram counts or plots. + +With one vector input argument, plot a histogram of the values with +10 bins. The range of the histogram bins is determined by the range +of the data. + +Given a second scalar argument, use that as the number of bins. + +Given a second vector argument, use that as the centers of the bins, +with the width of the bins determined from the adjacent values in +the vector. + +Extreme values are lumped in the first and last bins. + +With two output arguments, produce the values @var{nn} and @var{xx} such +that @code{bar (@var{xx}, @var{nn})} will plot the histogram. +@end deftypefn + +@deftypefn {Function File} {} loglog (@var{args}) +Make a two-dimensional plot using log scales for both axes. See the +description of @code{plot} above for a description of the arguments that +@code{loglog} will accept. +@end deftypefn + +@deftypefn {Function File} {} polar (@var{theta}, @var{rho}) +Make a two-dimensional plot given polar the coordinates @var{theta} and +@var{rho}. +@end deftypefn + +@deftypefn {Function File} {} semilogx (@var{args}) +Make a two-dimensional plot using a log scale for the @var{x} axis. See +the description of @code{plot} above for a description of the arguments +that @code{semilogx} will accept. +@end deftypefn + +@deftypefn {Function File} {} semilogy (@var{args}) +Make a two-dimensional plot using a log scale for the @var{y} axis. See +the description of @code{plot} above for a description of the arguments +that @code{semilogy} will accept. +@end deftypefn + +@deftypefn {Function File} {} stairs (@var{x}, @var{y}) +Given two vectors of x-y data, bar produces a `stairstep' plot. + +If only one argument is given, it is taken as a vector of y-values +and the x coordinates are taken to be the indices of the elements. + +If two output arguments are specified, the data are generated but +not plotted. For example, + +@example +stairs (x, y); +@end example + +@noindent +and + +@example +[xs, ys] = stairs (x, y); +plot (xs, ys); +@end example + +@noindent +are equivalent. +@end deftypefn + +@node Three-Dimensional Plotting, Plot Annotations, Specialized Two-Dimensional Plots, Plotting +@section Three-Dimensional Plotting + +@deffn {Command} gsplot @var{ranges} @var{expression} @var{using} @var{title} @var{style} +Generate a 3-dimensional plot. + +The @var{ranges}, @var{using}, @var{title}, and @var{style} arguments +are optional, and the @var{using}, @var{title} and @var{style} +qualifiers may appear in any order after the expression. You may plot +multiple expressions with a single command by separating them with +commas. Each expression may have its own set of qualifiers. + +The optional item @var{ranges} has the syntax + +@example +[ x_lo : x_up ] [ y_lo : y_up ] [ z_lo : z_up ] +@end example + +@noindent +and may be used to specify the ranges for the axes of the plot, +independent of the actual range of the data. The range for the y and z +axes and any of the individual limits may be omitted. A range +@code{[:]} indicates that the default limits should be used. This +normally means that a range just large enough to include all the data +points will be used. + +The expression to be plotted must not contain any literal matrices (e.g. +@code{[ 1, 2; 3, 4 ]}) since it is nearly impossible to distinguish a +plot range from a matrix of data. + +See the help for @code{gnuplot} for a description of the syntax for the +optional items. + +By default, the @code{gsplot} command plots each column of the +expression as the z value, using the row index as the x value, and the +column index as the y value. The indices are counted from zero, not +one. For example, + +@example +gsplot rand (5, 2) +@end example + +@noindent +will plot a random surface, with the x and y values taken from the row +and column indices of the matrix. + +If parametric plotting mode is set (using the command +@kbd{gset parametric}, then @code{gsplot} takes the columns of the +matrix three at a time as the x, y and z values that define a line in +three space. Any extra columns are ignored, and the x and y values are +expected to be sorted. For example, with @code{parametric} set, it +makes sense to plot a matrix like +@iftex +@tex +$$ +\left[\matrix{ +1 & 1 & 3 & 2 & 1 & 6 & 3 & 1 & 9 \cr +1 & 2 & 2 & 2 & 2 & 5 & 3 & 2 & 8 \cr +1 & 3 & 1 & 2 & 3 & 4 & 3 & 3 & 7}\right] +$$ +@end tex +@end iftex +@ifinfo + +@example +1 1 3 2 1 6 3 1 9 +1 2 2 2 2 5 3 2 8 +1 3 1 2 3 4 3 3 7 +@end example +@end ifinfo + +@noindent +but not @code{rand (5, 30)}. +@end deffn + +The @sc{Matlab}-style three-dimensional plotting commands are: + +@deftypefn {Function File} {} mesh (@var{x}, @var{y}, @var{z}) +Plot a mesh given matrices @code{x}, and @var{y} from @code{meshdom} and +a matrix @var{z} corresponding to the @var{x} and @var{y} coordinates of +the mesh. +@end deftypefn + +@deftypefn {Function File} {} meshdom (@var{x}, @var{y}) +Given vectors of @var{x} and @var{y} coordinates, return two matrices +corresponding to the @var{x} and @var{y} coordinates of the mesh. + +See the file @file{sombrero.m} for an example of using @code{mesh} and +@code{meshdom}. +@end deftypefn + +@defvr {Built-in Variable} gnuplot_binary +The name of the program invoked by the plot command. The default value +is @code{"gnuplot"}. @xref{Installation}. +@end defvr + +@defvr {Built-in Variable} gnuplot_has_frames +If the value of this variable is nonzero, Octave assumes that your copy +of gnuplot has support for multiple frames that is included in recent +3.6beta releases. It's initial value is determined by configure, but it +can be changed in your startup script or at the command line in case +configure got it wrong, or if you upgrade your gnuplot installation. +@end defvr + +@deftypefn {Function File} {} figure (@var{n}) +Set the current plot window to plot window @var{n}. This function +currently requires X11 and a version of gnuplot that supports multiple +frames. +@end deftypefn + +@defvr {Built-in Variable} gnuplot_has_multiplot +If the value of this variable is nonzero, Octave assumes that your copy +of gnuplot has the multiplot support that is included in recent +3.6beta releases. It's initial value is determined by configure, but it +can be changed in your startup script or at the command line in case +configure got it wrong, or if you upgrade your gnuplot installation. +@end defvr + +@node Plot Annotations, Multiple Plots on One Page, Three-Dimensional Plotting, Plotting +@section Plot Annotations + +@deftypefn {Function File} {} grid +For two-dimensional plotting, force the display of a grid on the plot. +@end deftypefn + +@deftypefn {Function File} {} title (@var{string}) +Specify a title for the plot. If you already have a plot displayed, use +the command @code{replot} to redisplay it with the new title. +@end deftypefn + +@deftypefn {Function File} {} xlabel (@var{string}) +@deftypefnx {Function File} {} ylabel (@var{string}) +@deftypefnx {Function File} {} zlabel (@var{string}) +Specify x, y, and z axis labels for the plot. If you already have a plot +displayed, use the command @code{replot} to redisplay it with the new +labels. +@end deftypefn + +@node Multiple Plots on One Page, , Plot Annotations, Plotting +@section Multiple Plots on One Page + +The following functions all require a version of @code{gnuplot} that +supports the multiplot feature. + +@deftypefn {Function File} {} mplot (@var{x}, @var{y}) +@deftypefnx {Function File} {} mplot (@var{x}, @var{y}, @var{fmt}) +@deftypefnx {Function File} {} mplot (@var{x1}, @var{y1}, @var{x2}, @var{y2}) +This is a modified version of the @code{plot} function that works with +the multiplot version of @code{gnuplot} to plot multiple plots per page. +This plot version automatically advances to the next subplot position +after each set of arguments are processed. + +See the description of the @var{plot} function for the various options. +@end deftypefn + +@deftypefn {Function File} {} multiplot (@var{xn}, @var{yn}) +Sets and resets multiplot mode. + +If the arguments are non-zero, @code{multiplot} will set up multiplot +mode with @var{xn}, @var{yn} subplots along the @var{x} and @var{y} +axes. If both arguments are zero, @code{multiplot} closes multiplot +mode. +@end deftypefn + +@deftypefn {Function File} {} oneplot () +If in multiplot mode, switches to single plot mode. +@end deftypefn + +@deftypefn {Function File} {} plot_border (...) +Multiple arguments allowed to specify the sides on which the border +is shown. Allowed arguments include: + +@table @code +@item "blank" +No borders displayed. + +@item "all" +All borders displayed + +@item "north" +North Border + +@item "south" +South Border + +@item "east" +East Border + +@item "west" +West Border +@end table + +@noindent +The arguments may be abbreviated to single characters. Without any +arguments, @code{plot_border} turns borders off. +@end deftypefn + +@deftypefn {Function File} {} subplot (@var{rows}, @var{cols}, @var{index}) +@deftypefnx {Function File} {} subplot (@var{rcn}) +Sets @code{gnuplot} in multiplot mode and plots in location +given by index (there are @var{cols} by @var{rows} subwindows). + +Input: + +@table @var +@item rows +Number of rows in subplot grid. + +@item columns +Number of columns in subplot grid. + +@item index +Index of subplot where to make the next plot. +@end table + +If only one argument is supplied, then it must be a three digit value +specifying the location in digits 1 (rows) and 2 (columns) and the plot +index in digit 3. + +The plot index runs row-wise. First all the columns in a row are filled +and then the next row is filled. + +For example, a plot with 4 by 2 grid will have plot indices running as +follows: +@iftex +@tex +\vskip 10pt +\hfil\vbox{\offinterlineskip\hrule +\halign{\vrule#&&\qquad\hfil#\hfil\qquad\vrule\cr +height13pt&1&2&3&4\cr height12pt&&&&\cr\noalign{\hrule} +height13pt&5&6&7&8\cr height12pt&&&&\cr\noalign{\hrule}}} +\hfil +\vskip 10pt +@end tex +@end iftex +@ifinfo +@display +@group ++-----+-----+-----+-----+ +| 1 | 2 | 3 | 4 | ++-----+-----+-----+-----+ +| 5 | 6 | 7 | 8 | ++-----+-----+-----+-----+ +@end group +@end display +@end ifinfo +@end deftypefn + +@deftypefn {Function File} {} subwindow (@var{xn}, @var{yn}) +Sets the subwindow position in multiplot mode for the next plot. The +multiplot mode has to be previously initialized using the +@code{multiplot} function, otherwise this command just becomes an alias +to @code{multiplot} +@end deftypefn + +@deftypefn {Function File} {} top_title (@var{string}) +@deftypefnx {Function File} {} bottom_title (@var{string}) +Makes a title with text @var{string} at the top (bottom) of the plot. +@end deftypefn diff --git a/doc/interpreter/poly.texi b/doc/interpreter/poly.texi deleted file mode 100644 --- a/doc/interpreter/poly.texi +++ /dev/null @@ -1,259 +0,0 @@ -@c Copyright (C) 1996, 1997 John W. Eaton -@c This is part of the Octave manual. -@c For copying conditions, see the file gpl.texi. - -@node Polynomial Manipulations, Control Theory, Sets, Top -@chapter Polynomial Manipulations - -In Octave, a polynomial is represented by its coefficients (arranged -in descending order). For example, a vector -@iftex -@end iftex -@ifinfo - $c$ -@end ifinfo -of length -@iftex -@tex - $N+1$ -@end tex -@ifinfo - @var{N+1} -@end ifinfo - corresponds to the following polynomial of order -@iftex -@tex - $N$ -$$ - p (x) = c_1 x^N + ... + c_N x + c_{N+1}. -$$ -@end tex -@end iftex -@ifinfo - @var{N} - -@example -p(x) = @var{c}(1) x^@var{N} + ... + @var{c}(@var{N}) x + @var{c}(@var{N}+1). -@end example -@end ifinfo - -@deftypefn {Function File} {} compan (@var{c}) -Compute the companion matrix corresponding to polynomial coefficient -vector @var{c}. - -The companion matrix is -@iftex -@tex -$$ -A = \left[\matrix{ - -c_2/c_1 & -c_3/c_1 & \cdots & -c_N/c_1 & -c_{N+1}/c_1\cr - 1 & 0 & \cdots & 0 & 0 \cr - 0 & 1 & \cdots & 0 & 0 \cr - \vdots & \vdots & \ddots & \vdots & \vdots \cr - 0 & 0 & \cdots & 1 & 0}\right]. -$$ -@end tex -@end iftex -@ifinfo - -@smallexample - _ _ - | -c(2)/c(1) -c(3)/c(1) ... -c(N)/c(1) -c(N+1)/c(1) | - | 1 0 ... 0 0 | - | 0 1 ... 0 0 | -A = | . . . . . | - | . . . . . | - | . . . . . | - |_ 0 0 ... 1 0 _| -@end smallexample -@end ifinfo - -The eigenvalues of the companion matrix are equal to the roots of the -polynomial. -@end deftypefn - -@deftypefn {Function File} {} conv (@var{a}, @var{b}) -Convolve two vectors. - -@code{y = conv (a, b)} returns a vector of length equal to -@code{length (a) + length (b) - 1}. -If @var{a} and @var{b} are polynomial coefficient vectors, @code{conv} -returns the coefficients of the product polynomial. -@end deftypefn - -@deftypefn {Function File} {} deconv (@var{y}, @var{a}) -Deconvolve two vectors. - -@code{[b, r] = deconv (y, a)} solves for @var{b} and @var{r} such that -@code{y = conv (a, b) + r}. - -If @var{y} and @var{a} are polynomial coefficient vectors, @var{b} will -contain the coefficients of the polynomial quotient and @var{r} will be -a remander polynomial of lowest order. -@end deftypefn - -@deftypefn {Function File} {} poly (@var{a}) -If @var{a} is a square @var{N}-by-@var{N} matrix, @code{poly (@var{a})} -is the row vector of the coefficients of @code{det (z * eye (N) - a)}, -the characteristic polynomial of @var{a}. If @var{x} is a vector, -@code{poly (@var{x})} is a vector of coefficients of the polynomial -whose roots are the elements of @var{x}. -@end deftypefn - -@deftypefn {Function File} {} polyderiv (@var{c}) -Return the coefficients of the derivative of the polynomial whose -coefficients are given by vector @var{c}. -@end deftypefn - -@deftypefn {Function File} {[@var{p}, @var{yf}] =} polyfit (@var{x}, @var{y}, @var{n}) -Return the coefficients of a polynomial @var{p}(@var{x}) of degree -@var{n} that minimizes -@iftex -@tex -$$ -\sum_{i=1}^N (p(x_i) - y_i)^2 -$$ -@end tex -@end iftex -@ifinfo -@code{sumsq (p(x(i)) - y(i))}, -@end ifinfo - to best fit the data in the least squares sense. -@end deftypefn - -If two output arguments are requested, the second contains the values of -the polynomial for each value of @var{x}. - -@deftypefn {Function File} {} polyinteg (@var{c}) -Return the coefficients of the integral of the polynomial whose -coefficients are represented by the vector @var{c}. - -The constant of integration is set to zero. -@end deftypefn - -@deftypefn {Function File} {} polyreduce (@var{c}) -Reduces a polynomial coefficient vector to a minimum number of terms by -stripping off any leading zeros. -@end deftypefn - -@deftypefn {Function File} {} polyval (@var{c}, @var{x}) -Evaluate a polynomial. - -@code{polyval (@var{c}, @var{x})} will evaluate the polynomial at the -specified value of @var{x}. - -If @var{x} is a vector or matrix, the polynomial is evaluated at each of -the elements of @var{x}. -@end deftypefn - -@deftypefn {Function File} {} polyvalm (@var{c}, @var{x}) -Evaluate a polynomial in the matrix sense. - -@code{polyvalm (@var{c}, @var{x})} will evaluate the polynomial in the -matrix sense, i.e. matrix multiplication is used instead of element by -element multiplication as is used in polyval. - -The argument @var{x} must be a square matrix. -@end deftypefn - -@deftypefn {Function File} {} residue (@var{b}, @var{a}, @var{tol}) -If @var{b} and @var{a} are vectors of polynomial coefficients, then -residue calculates the partial fraction expansion corresponding to the -ratio of the two polynomials. -@cindex partial fraction expansion - -The function @code{residue} returns @var{r}, @var{p}, @var{k}, and -@var{e}, where the vector @var{r} contains the residue terms, @var{p} -contains the pole values, @var{k} contains the coefficients of a direct -polynomial term (if it exists) and @var{e} is a vector containing the -powers of the denominators in the partial fraction terms. - -Assuming @var{b} and @var{a} represent polynomials -@iftex -@tex -$P(s)$ and $Q(s)$ -@end tex -@end iftex -@ifinfo - P (s) and Q(s) -@end ifinfo - we have: -@iftex -@tex -$$ -{P(s)\over Q(s)} = \sum_{m=1}^M {r_m\over (s-p_m)^e_m} - + \sum_{i=1}^N k_i s^{N-i}. -$$ -@end tex -@end iftex -@ifinfo - -@example - P(s) M r(m) N - ---- = SUM ------------- + SUM k(i)*s^(N-i) - Q(s) m=1 (s-p(m))^e(m) i=1 -@end example -@end ifinfo - -@noindent -where @var{M} is the number of poles (the length of the @var{r}, -@var{p}, and @var{e} vectors) and @var{N} is the length of the @var{k} -vector. - -The argument @var{tol} is optional, and if not specified, a default -value of 0.001 is assumed. The tolerance value is used to determine -whether poles with small imaginary components are declared real. It is -also used to determine if two poles are distinct. If the ratio of the -imaginary part of a pole to the real part is less than @var{tol}, the -imaginary part is discarded. If two poles are farther apart than -@var{tol} they are distinct. For example, - -@example -@group - b = [1, 1, 1]; - a = [1, -5, 8, -4]; - [r, p, k, e] = residue (b, a); - @result{} r = [-2, 7, 3] - @result{} p = [2, 2, 1] - @result{} k = [](0x0) - @result{} e = [1, 2, 1] -@end group -@end example - -@noindent -which implies the following partial fraction expansion -@iftex -@tex -$$ -{s^2+s+1\over s^3-5s^2+8s-4} = {-2\over s-2} + {7\over (s-2)^2} + {3\over s-1} -$$ -@end tex -@end iftex -@ifinfo - -@example - s^2 + s + 1 -2 7 3 - ------------------- = ----- + ------- + ----- - s^3 - 5s^2 + 8s - 4 (s-2) (s-2)^2 (s-1) -@end example -@end ifinfo -@end deftypefn - -@deftypefn {Function File} {} roots (@var{v}) - -For a vector @var{v} with @var{N} components, return -the roots of the polynomial -@iftex -@tex -$$ -v_1 z^{N-1} + \cdots + v_{N-1} z + v_N. -$$ -@end tex -@end iftex -@ifinfo - -@example -v(1) * z^(N-1) + ... + v(N-1) * z + v(N). -@end example -@end ifinfo -@end deftypefn diff --git a/doc/interpreter/poly.txi b/doc/interpreter/poly.txi new file mode 100644 --- /dev/null +++ b/doc/interpreter/poly.txi @@ -0,0 +1,259 @@ +@c Copyright (C) 1996, 1997 John W. Eaton +@c This is part of the Octave manual. +@c For copying conditions, see the file gpl.texi. + +@node Polynomial Manipulations, Control Theory, Sets, Top +@chapter Polynomial Manipulations + +In Octave, a polynomial is represented by its coefficients (arranged +in descending order). For example, a vector +@iftex +@end iftex +@ifinfo + $c$ +@end ifinfo +of length +@iftex +@tex + $N+1$ +@end tex +@ifinfo + @var{N+1} +@end ifinfo + corresponds to the following polynomial of order +@iftex +@tex + $N$ +$$ + p (x) = c_1 x^N + ... + c_N x + c_{N+1}. +$$ +@end tex +@end iftex +@ifinfo + @var{N} + +@example +p(x) = @var{c}(1) x^@var{N} + ... + @var{c}(@var{N}) x + @var{c}(@var{N}+1). +@end example +@end ifinfo + +@deftypefn {Function File} {} compan (@var{c}) +Compute the companion matrix corresponding to polynomial coefficient +vector @var{c}. + +The companion matrix is +@iftex +@tex +$$ +A = \left[\matrix{ + -c_2/c_1 & -c_3/c_1 & \cdots & -c_N/c_1 & -c_{N+1}/c_1\cr + 1 & 0 & \cdots & 0 & 0 \cr + 0 & 1 & \cdots & 0 & 0 \cr + \vdots & \vdots & \ddots & \vdots & \vdots \cr + 0 & 0 & \cdots & 1 & 0}\right]. +$$ +@end tex +@end iftex +@ifinfo + +@smallexample + _ _ + | -c(2)/c(1) -c(3)/c(1) ... -c(N)/c(1) -c(N+1)/c(1) | + | 1 0 ... 0 0 | + | 0 1 ... 0 0 | +A = | . . . . . | + | . . . . . | + | . . . . . | + |_ 0 0 ... 1 0 _| +@end smallexample +@end ifinfo + +The eigenvalues of the companion matrix are equal to the roots of the +polynomial. +@end deftypefn + +@deftypefn {Function File} {} conv (@var{a}, @var{b}) +Convolve two vectors. + +@code{y = conv (a, b)} returns a vector of length equal to +@code{length (a) + length (b) - 1}. +If @var{a} and @var{b} are polynomial coefficient vectors, @code{conv} +returns the coefficients of the product polynomial. +@end deftypefn + +@deftypefn {Function File} {} deconv (@var{y}, @var{a}) +Deconvolve two vectors. + +@code{[b, r] = deconv (y, a)} solves for @var{b} and @var{r} such that +@code{y = conv (a, b) + r}. + +If @var{y} and @var{a} are polynomial coefficient vectors, @var{b} will +contain the coefficients of the polynomial quotient and @var{r} will be +a remander polynomial of lowest order. +@end deftypefn + +@deftypefn {Function File} {} poly (@var{a}) +If @var{a} is a square @var{N}-by-@var{N} matrix, @code{poly (@var{a})} +is the row vector of the coefficients of @code{det (z * eye (N) - a)}, +the characteristic polynomial of @var{a}. If @var{x} is a vector, +@code{poly (@var{x})} is a vector of coefficients of the polynomial +whose roots are the elements of @var{x}. +@end deftypefn + +@deftypefn {Function File} {} polyderiv (@var{c}) +Return the coefficients of the derivative of the polynomial whose +coefficients are given by vector @var{c}. +@end deftypefn + +@deftypefn {Function File} {[@var{p}, @var{yf}] =} polyfit (@var{x}, @var{y}, @var{n}) +Return the coefficients of a polynomial @var{p}(@var{x}) of degree +@var{n} that minimizes +@iftex +@tex +$$ +\sum_{i=1}^N (p(x_i) - y_i)^2 +$$ +@end tex +@end iftex +@ifinfo +@code{sumsq (p(x(i)) - y(i))}, +@end ifinfo + to best fit the data in the least squares sense. +@end deftypefn + +If two output arguments are requested, the second contains the values of +the polynomial for each value of @var{x}. + +@deftypefn {Function File} {} polyinteg (@var{c}) +Return the coefficients of the integral of the polynomial whose +coefficients are represented by the vector @var{c}. + +The constant of integration is set to zero. +@end deftypefn + +@deftypefn {Function File} {} polyreduce (@var{c}) +Reduces a polynomial coefficient vector to a minimum number of terms by +stripping off any leading zeros. +@end deftypefn + +@deftypefn {Function File} {} polyval (@var{c}, @var{x}) +Evaluate a polynomial. + +@code{polyval (@var{c}, @var{x})} will evaluate the polynomial at the +specified value of @var{x}. + +If @var{x} is a vector or matrix, the polynomial is evaluated at each of +the elements of @var{x}. +@end deftypefn + +@deftypefn {Function File} {} polyvalm (@var{c}, @var{x}) +Evaluate a polynomial in the matrix sense. + +@code{polyvalm (@var{c}, @var{x})} will evaluate the polynomial in the +matrix sense, i.e. matrix multiplication is used instead of element by +element multiplication as is used in polyval. + +The argument @var{x} must be a square matrix. +@end deftypefn + +@deftypefn {Function File} {} residue (@var{b}, @var{a}, @var{tol}) +If @var{b} and @var{a} are vectors of polynomial coefficients, then +residue calculates the partial fraction expansion corresponding to the +ratio of the two polynomials. +@cindex partial fraction expansion + +The function @code{residue} returns @var{r}, @var{p}, @var{k}, and +@var{e}, where the vector @var{r} contains the residue terms, @var{p} +contains the pole values, @var{k} contains the coefficients of a direct +polynomial term (if it exists) and @var{e} is a vector containing the +powers of the denominators in the partial fraction terms. + +Assuming @var{b} and @var{a} represent polynomials +@iftex +@tex +$P(s)$ and $Q(s)$ +@end tex +@end iftex +@ifinfo + P (s) and Q(s) +@end ifinfo + we have: +@iftex +@tex +$$ +{P(s)\over Q(s)} = \sum_{m=1}^M {r_m\over (s-p_m)^e_m} + + \sum_{i=1}^N k_i s^{N-i}. +$$ +@end tex +@end iftex +@ifinfo + +@example + P(s) M r(m) N + ---- = SUM ------------- + SUM k(i)*s^(N-i) + Q(s) m=1 (s-p(m))^e(m) i=1 +@end example +@end ifinfo + +@noindent +where @var{M} is the number of poles (the length of the @var{r}, +@var{p}, and @var{e} vectors) and @var{N} is the length of the @var{k} +vector. + +The argument @var{tol} is optional, and if not specified, a default +value of 0.001 is assumed. The tolerance value is used to determine +whether poles with small imaginary components are declared real. It is +also used to determine if two poles are distinct. If the ratio of the +imaginary part of a pole to the real part is less than @var{tol}, the +imaginary part is discarded. If two poles are farther apart than +@var{tol} they are distinct. For example, + +@example +@group + b = [1, 1, 1]; + a = [1, -5, 8, -4]; + [r, p, k, e] = residue (b, a); + @result{} r = [-2, 7, 3] + @result{} p = [2, 2, 1] + @result{} k = [](0x0) + @result{} e = [1, 2, 1] +@end group +@end example + +@noindent +which implies the following partial fraction expansion +@iftex +@tex +$$ +{s^2+s+1\over s^3-5s^2+8s-4} = {-2\over s-2} + {7\over (s-2)^2} + {3\over s-1} +$$ +@end tex +@end iftex +@ifinfo + +@example + s^2 + s + 1 -2 7 3 + ------------------- = ----- + ------- + ----- + s^3 - 5s^2 + 8s - 4 (s-2) (s-2)^2 (s-1) +@end example +@end ifinfo +@end deftypefn + +@deftypefn {Function File} {} roots (@var{v}) + +For a vector @var{v} with @var{N} components, return +the roots of the polynomial +@iftex +@tex +$$ +v_1 z^{N-1} + \cdots + v_{N-1} z + v_N. +$$ +@end tex +@end iftex +@ifinfo + +@example +v(1) * z^(N-1) + ... + v(N-1) * z + v(N). +@end example +@end ifinfo +@end deftypefn diff --git a/doc/interpreter/preface.texi b/doc/interpreter/preface.texi deleted file mode 100644 --- a/doc/interpreter/preface.texi +++ /dev/null @@ -1,245 +0,0 @@ -@c Copyright (C) 1996, 1997 John W. Eaton -@c This is part of the Octave manual. -@c For copying conditions, see the file gpl.texi. - -@node Preface, Introduction, Top, Top -@unnumbered Preface -@cindex contributors -@cindex history - -Octave was originally intended to be companion software for an -undergraduate-level textbook on chemical reactor design being written by -James B. Rawlings of the University of Wisconsin-Madison and John -G. Ekerdt of the University of Texas. - -Clearly, Octave is now much more than just another `courseware' package -with limited utility beyond the classroom. Although our initial goals -were somewhat vague, we knew that we wanted to create something that -would enable students to solve realistic problems, and that they could -use for many things other than chemical reactor design problems. - -There are those who would say that we should be teaching the students -Fortran instead, because that is the computer language of engineering, -but every time we have tried that, the students have spent far too much -time trying to figure out why their Fortran code crashes and not enough -time learning about chemical engineering. With Octave, most students -pick up the basics quickly, and are using it confidently in just a few -hours. - -Although it was originally intended to be used to teach reactor design, -it has been used in several other undergraduate and graduate -courses in the Chemical Engineering Department at the University of -Texas, and the math department at the University of Texas has been using -it for teaching differential equations and linear algebra as well. If -you find it useful, please let us know. We are always interested to -find out how Octave is being used in other places. - -Virtually everyone thinks that the name Octave has something to do with -music, but it is actually the name of a former professor of mine who -wrote a famous textbook on chemical reaction engineering, and who was -also well known for his ability to do quick `back of the envelope' -calculations. We hope that this software will make it possible for many -people to do more ambitious computations just as easily. - -Everyone is encouraged to share this software with others under the -terms of the GNU General Public License (@pxref{Copying}) as described -at the beginning of this manual. You are also encouraged to help make -Octave more useful by writing and contributing additional functions for -it, and by reporting any problems you may have. - -@menu -* Acknowledgements:: -* How You Can Contribute to Octave:: -* Distribution:: -@end menu - -@node Acknowledgements, How You Can Contribute to Octave, Preface, Preface -@unnumberedsec Acknowledgements -@cindex acknowledgements - -Many people have already contributed to Octave's development. In -addition to John W. Eaton, the following people have helped write parts -of Octave or helped out in various other ways. - -@c Once lp_solve has been added, don't forget to include the lp_solve -@c author, and Kantor, for providing an example. - -@itemize @bullet -@item -Thomas Baier @email{baier@@ci.tuwien.ac.at} wrote the original versions -of @code{popen}, @code{pclose}, @code{execute}, @code{sync_system}, and -@code{async_system}. - -@item -Karl Berry @email{karl@@cs.umb.edu} wrote the @code{kpathsea} library -that allows Octave to recursively search directory paths for function -and script files. - -@item -Georg Beyerle @email{gbeyerle@@awi-potsdam.de} contributed code to save -values in @sc{Matlab}'s @file{.mat}-file format, and has provided many -useful bug reports and suggestions. - -@item -John Campbell @email{jcc@@bevo.che.wisc.edu} wrote most of the file and -C-style input and output functions. - -@item -Brian Fox @email{bfox@@gnu.org} wrote the @code{readline} library -used for command history editing, and the portion of this manual that -documents it. - -@item -Klaus Gebhardt @email{gebhardt@@crunch.ikp.physik.th-darmstadt.de} -ported Octave to OS/2. - -@item -A. Scottedward Hodel @email{A.S.Hodel@@eng.auburn.edu} contributed a number -of functions including @code{expm}, @code{qzval}, @code{qzhess}, -@code{syl}, @code{lyap}, and @code{balance}. - -@item -Kurt Hornik @email{Kurt.Hornik@@ci.tuwien.ac.at} provided the -@code{corrcoef}, @code{cov}, @code{fftconv}, @code{fftfilt}, @code{gcd}, -@code{lcd}, @code{kurtosis}, @code{null}, @code{orth}, @code{poly}, -@code{polyfit}, @code{roots}, and @code{skewness} functions, supplied -documentation for these and numerous other functions, rewrote the Emacs -mode for editing Octave code and provided its documentation, and has -helped tremendously with testing. He has also been a constant source of -new ideas for improving Octave. - -@item -Phil Johnson @email{johnsonp@@nicco.sscnet.ucla.edu} has helped to make -Linux releases available. - -@item -Friedrich Leisch @email{leisch@@ci.tuwien.ac.at} provided the -@code{mahalanobis} function. - -@item -Ken Neighbors @email{wkn@@leland.stanford.edu} has provided many useful -bug reports and comments on @sc{Matlab} compatibility. - -@item -Rick Niles @email{niles@@axp745.gsfc.nasa.gov} rewrote Octave's plotting -functions to add line styles and the ability to specify an unlimited -number of lines in a single call. He also continues to track down odd -incompatibilities and bugs. - -@item -Mark Odegard @email{meo@@sugarland.unocal.com} provided the initial -implementation of @code{fread}, @code{fwrite}, @code{feof}, and -@code{ferror}. - -@item -Tony Richardson @email{arichard@@stark.cc.oh.us} wrote Octave's -image processing functions as well as most of the original polynomial -functions. - -@item -R. Bruce Tenison @email{Bruce.Tenison@@eng.auburn.edu} wrote the -@code{hess} and @code{schur} functions. - -@item -Teresa Twaroch @email{twaroch@@ci.tuwien.ac.at} provided the functions -@code{gls} and @code{ols}. - -@item -Andreas Weingessel @email{Andreas.Weingessel@@ci.tuwien.ac.at} wrote the -audio functions @code{lin2mu}, @code{loadaudio}, @code{mu2lin}, -@code{playaudio}, @code{record}, @code{saveaudio}, and @code{setaudio}. - -@item -Fook Fah Yap @email{ffy@@eng.cam.ac.uk} provided the @code{fft} and -@code{ifft} functions and valuable bug reports for early versions. -@end itemize - -Special thanks to the following people and organizations for -supporting the development of Octave: - -@itemize @bullet -@item -Digital Equipment Corporation, for an equipment grant as part of their -External Research Program. - -@item -Sun Microsystems, Inc., for an Academic Equipment grant. - -@item -International Business Machines, Inc., for providing equipment as part -of a grant to the University of Texas College of Engineering. - -@item -Texaco Chemical Company, for providing funding to continue the -development of this software. - -@item -The University of Texas College of Engineering, for providing a -Challenge for Excellence Research Supplement, and for providing an -Academic Development Funds grant. - -@item -The State of Texas, for providing funding through the Texas -Advanced Technology Program under Grant No. 003658-078. - -@item -Noel Bell, Senior Engineer, Texaco Chemical Company, Austin Texas. - -@item -James B. Rawlings, Professor, University of Wisconsin-Madison, -Department of Chemical Engineering. - -@item -Richard Stallman, for writing GNU. -@end itemize - -This project would not have been possible without the GNU software used -in and used to produce Octave. - -@node How You Can Contribute to Octave, Distribution, Acknowledgements, Preface -@unnumberedsec How You Can Contribute to Octave -@cindex contributing to Octave -@cindex funding Octave development - -There are a number of ways that you can contribute to help make Octave a -better system. Perhaps the most important way to contribute is to write -high-quality code for solving new problems, and to make your code freely -available for others to use. - -If you find Octave useful, consider providing additional funding to -continue its development. Even a modest amount of additional funding -could make a significant difference in the amount of time that is -available for development and support. - -If you cannot provide funding or contribute code, you can still help -make Octave better and more reliable by reporting any bugs you find and -by offering suggestions for ways to improve Octave. @xref{Trouble}, for -tips on how to write useful bug reports. - -@node Distribution, , How You Can Contribute to Octave, Preface -@unnumberedsec Distribution -@cindex distribution of Octave - -Octave is @dfn{free} software. This means that everyone is free to -use it and free to redistribute it on certain conditions. Octave is not -in the public domain. It is copyrighted and there are restrictions on -its distribution, but the restrictions are designed to ensure that -others will have the same freedom to use and redistribute Octave that -you have. The precise conditions can be found in the GNU General Public -License that comes with Octave and that also appears in @ref{Copying}. - -Octave is available on CD-ROM with various collections of other free -software, and from the Free Software Foundation. Ordering a copy of -Octave from the Free Software Foundation helps to fund the development -of more free software. For more information, write to - -@quotation -Free Software Foundation@* -59 Temple Place---Suite 330@* -Boston, MA 02111--1307@* -USA -@end quotation - -Octave is also available on the Internet from -@url{ftp://ftp.che.wisc.edu/pub/octave}, and additional information is -available from @url{http://www.che.wisc.edu/octave}. diff --git a/doc/interpreter/preface.txi b/doc/interpreter/preface.txi new file mode 100644 --- /dev/null +++ b/doc/interpreter/preface.txi @@ -0,0 +1,245 @@ +@c Copyright (C) 1996, 1997 John W. Eaton +@c This is part of the Octave manual. +@c For copying conditions, see the file gpl.texi. + +@node Preface, Introduction, Top, Top +@unnumbered Preface +@cindex contributors +@cindex history + +Octave was originally intended to be companion software for an +undergraduate-level textbook on chemical reactor design being written by +James B. Rawlings of the University of Wisconsin-Madison and John +G. Ekerdt of the University of Texas. + +Clearly, Octave is now much more than just another `courseware' package +with limited utility beyond the classroom. Although our initial goals +were somewhat vague, we knew that we wanted to create something that +would enable students to solve realistic problems, and that they could +use for many things other than chemical reactor design problems. + +There are those who would say that we should be teaching the students +Fortran instead, because that is the computer language of engineering, +but every time we have tried that, the students have spent far too much +time trying to figure out why their Fortran code crashes and not enough +time learning about chemical engineering. With Octave, most students +pick up the basics quickly, and are using it confidently in just a few +hours. + +Although it was originally intended to be used to teach reactor design, +it has been used in several other undergraduate and graduate +courses in the Chemical Engineering Department at the University of +Texas, and the math department at the University of Texas has been using +it for teaching differential equations and linear algebra as well. If +you find it useful, please let us know. We are always interested to +find out how Octave is being used in other places. + +Virtually everyone thinks that the name Octave has something to do with +music, but it is actually the name of a former professor of mine who +wrote a famous textbook on chemical reaction engineering, and who was +also well known for his ability to do quick `back of the envelope' +calculations. We hope that this software will make it possible for many +people to do more ambitious computations just as easily. + +Everyone is encouraged to share this software with others under the +terms of the GNU General Public License (@pxref{Copying}) as described +at the beginning of this manual. You are also encouraged to help make +Octave more useful by writing and contributing additional functions for +it, and by reporting any problems you may have. + +@menu +* Acknowledgements:: +* How You Can Contribute to Octave:: +* Distribution:: +@end menu + +@node Acknowledgements, How You Can Contribute to Octave, Preface, Preface +@unnumberedsec Acknowledgements +@cindex acknowledgements + +Many people have already contributed to Octave's development. In +addition to John W. Eaton, the following people have helped write parts +of Octave or helped out in various other ways. + +@c Once lp_solve has been added, don't forget to include the lp_solve +@c author, and Kantor, for providing an example. + +@itemize @bullet +@item +Thomas Baier @email{baier@@ci.tuwien.ac.at} wrote the original versions +of @code{popen}, @code{pclose}, @code{execute}, @code{sync_system}, and +@code{async_system}. + +@item +Karl Berry @email{karl@@cs.umb.edu} wrote the @code{kpathsea} library +that allows Octave to recursively search directory paths for function +and script files. + +@item +Georg Beyerle @email{gbeyerle@@awi-potsdam.de} contributed code to save +values in @sc{Matlab}'s @file{.mat}-file format, and has provided many +useful bug reports and suggestions. + +@item +John Campbell @email{jcc@@bevo.che.wisc.edu} wrote most of the file and +C-style input and output functions. + +@item +Brian Fox @email{bfox@@gnu.org} wrote the @code{readline} library +used for command history editing, and the portion of this manual that +documents it. + +@item +Klaus Gebhardt @email{gebhardt@@crunch.ikp.physik.th-darmstadt.de} +ported Octave to OS/2. + +@item +A. Scottedward Hodel @email{A.S.Hodel@@eng.auburn.edu} contributed a number +of functions including @code{expm}, @code{qzval}, @code{qzhess}, +@code{syl}, @code{lyap}, and @code{balance}. + +@item +Kurt Hornik @email{Kurt.Hornik@@ci.tuwien.ac.at} provided the +@code{corrcoef}, @code{cov}, @code{fftconv}, @code{fftfilt}, @code{gcd}, +@code{lcd}, @code{kurtosis}, @code{null}, @code{orth}, @code{poly}, +@code{polyfit}, @code{roots}, and @code{skewness} functions, supplied +documentation for these and numerous other functions, rewrote the Emacs +mode for editing Octave code and provided its documentation, and has +helped tremendously with testing. He has also been a constant source of +new ideas for improving Octave. + +@item +Phil Johnson @email{johnsonp@@nicco.sscnet.ucla.edu} has helped to make +Linux releases available. + +@item +Friedrich Leisch @email{leisch@@ci.tuwien.ac.at} provided the +@code{mahalanobis} function. + +@item +Ken Neighbors @email{wkn@@leland.stanford.edu} has provided many useful +bug reports and comments on @sc{Matlab} compatibility. + +@item +Rick Niles @email{niles@@axp745.gsfc.nasa.gov} rewrote Octave's plotting +functions to add line styles and the ability to specify an unlimited +number of lines in a single call. He also continues to track down odd +incompatibilities and bugs. + +@item +Mark Odegard @email{meo@@sugarland.unocal.com} provided the initial +implementation of @code{fread}, @code{fwrite}, @code{feof}, and +@code{ferror}. + +@item +Tony Richardson @email{arichard@@stark.cc.oh.us} wrote Octave's +image processing functions as well as most of the original polynomial +functions. + +@item +R. Bruce Tenison @email{Bruce.Tenison@@eng.auburn.edu} wrote the +@code{hess} and @code{schur} functions. + +@item +Teresa Twaroch @email{twaroch@@ci.tuwien.ac.at} provided the functions +@code{gls} and @code{ols}. + +@item +Andreas Weingessel @email{Andreas.Weingessel@@ci.tuwien.ac.at} wrote the +audio functions @code{lin2mu}, @code{loadaudio}, @code{mu2lin}, +@code{playaudio}, @code{record}, @code{saveaudio}, and @code{setaudio}. + +@item +Fook Fah Yap @email{ffy@@eng.cam.ac.uk} provided the @code{fft} and +@code{ifft} functions and valuable bug reports for early versions. +@end itemize + +Special thanks to the following people and organizations for +supporting the development of Octave: + +@itemize @bullet +@item +Digital Equipment Corporation, for an equipment grant as part of their +External Research Program. + +@item +Sun Microsystems, Inc., for an Academic Equipment grant. + +@item +International Business Machines, Inc., for providing equipment as part +of a grant to the University of Texas College of Engineering. + +@item +Texaco Chemical Company, for providing funding to continue the +development of this software. + +@item +The University of Texas College of Engineering, for providing a +Challenge for Excellence Research Supplement, and for providing an +Academic Development Funds grant. + +@item +The State of Texas, for providing funding through the Texas +Advanced Technology Program under Grant No. 003658-078. + +@item +Noel Bell, Senior Engineer, Texaco Chemical Company, Austin Texas. + +@item +James B. Rawlings, Professor, University of Wisconsin-Madison, +Department of Chemical Engineering. + +@item +Richard Stallman, for writing GNU. +@end itemize + +This project would not have been possible without the GNU software used +in and used to produce Octave. + +@node How You Can Contribute to Octave, Distribution, Acknowledgements, Preface +@unnumberedsec How You Can Contribute to Octave +@cindex contributing to Octave +@cindex funding Octave development + +There are a number of ways that you can contribute to help make Octave a +better system. Perhaps the most important way to contribute is to write +high-quality code for solving new problems, and to make your code freely +available for others to use. + +If you find Octave useful, consider providing additional funding to +continue its development. Even a modest amount of additional funding +could make a significant difference in the amount of time that is +available for development and support. + +If you cannot provide funding or contribute code, you can still help +make Octave better and more reliable by reporting any bugs you find and +by offering suggestions for ways to improve Octave. @xref{Trouble}, for +tips on how to write useful bug reports. + +@node Distribution, , How You Can Contribute to Octave, Preface +@unnumberedsec Distribution +@cindex distribution of Octave + +Octave is @dfn{free} software. This means that everyone is free to +use it and free to redistribute it on certain conditions. Octave is not +in the public domain. It is copyrighted and there are restrictions on +its distribution, but the restrictions are designed to ensure that +others will have the same freedom to use and redistribute Octave that +you have. The precise conditions can be found in the GNU General Public +License that comes with Octave and that also appears in @ref{Copying}. + +Octave is available on CD-ROM with various collections of other free +software, and from the Free Software Foundation. Ordering a copy of +Octave from the Free Software Foundation helps to fund the development +of more free software. For more information, write to + +@quotation +Free Software Foundation@* +59 Temple Place---Suite 330@* +Boston, MA 02111--1307@* +USA +@end quotation + +Octave is also available on the Internet from +@url{ftp://ftp.che.wisc.edu/pub/octave}, and additional information is +available from @url{http://www.che.wisc.edu/octave}. diff --git a/doc/interpreter/quad.texi b/doc/interpreter/quad.texi deleted file mode 100644 --- a/doc/interpreter/quad.texi +++ /dev/null @@ -1,160 +0,0 @@ -@c Copyright (C) 1996, 1997 John W. Eaton -@c This is part of the Octave manual. -@c For copying conditions, see the file gpl.texi. - -@node Quadrature, Differential Equations, Nonlinear Equations, Top -@chapter Quadrature - -@menu -* Functions of One Variable:: -* Orthogonal Collocation:: -@end menu - -@node Functions of One Variable, Orthogonal Collocation, Quadrature, Quadrature -@section Functions of One Variable - -@deftypefn {Loadable Function} {[@var{v}, @var{ier}, @var{nfun}, @var{err}] =} quad (@var{f}, @var{a}, @var{b}, @var{tol}, @var{sing}) -Integrate a nonlinear function of one variable using Quadpack. -The first argument is the name of the function to call to compute the -value of the integrand. It must have the form - -@example -y = f (x) -@end example - -@noindent -where @var{y} and @var{x} are scalars. - -The second and third arguments are limits of integration. Either or -both may be infinite. - -The optional argument @var{tol} is a vector that specifies the desired -accuracy of the result. The first element of the vector is the desired -absolute tolerance, and the second element is the desired relative -tolerance. To choose a relative test only, set the absolute -tolerance to zero. To choose an absolute test only, set the relative -tolerance to zero. - -The optional argument @var{sing} is a vector of values at which the -integrand is known to be singular. - -The result of the integration is returned in @var{v} and @var{ier} -contains an integer error code (0 indicates a successful integration). -The value of @var{nfun} indicates how many function evaluations were -required, and @var{err} contains an estimate of the error in the -solution. -@end deftypefn - -@deftypefn {Loadable Function} {} quad_options (@var{opt}, @var{val}) -When called with two arguments, this function allows you set options -parameters for the function @code{quad}. Given one argument, -@code{quad_options} returns the value of the corresponding option. If -no arguments are supplied, the names of all the available options and -their current values are displayed. -@end deftypefn - -Here is an example of using @code{quad} to integrate the function -@iftex -@tex -$$ - f(x) = x \sin (1/x) \sqrt {|1 - x|} -$$ -from $x = 0$ to $x = 3$. -@end tex -@end iftex -@ifinfo - -@example - @var{f}(@var{x}) = @var{x} * sin (1/@var{x}) * sqrt (abs (1 - @var{x})) -@end example - -@noindent -from @var{x} = 0 to @var{x} = 3. -@end ifinfo - -This is a fairly difficult integration (plot the function over the range -of integration to see why). - -The first step is to define the function: - -@example -@group -function y = f (x) - y = x .* sin (1 ./ x) .* sqrt (abs (1 - x)); -endfunction -@end group -@end example - -Note the use of the `dot' forms of the operators. This is not necessary -for the call to @code{quad}, but it makes it much easier to generate a -set of points for plotting (because it makes it possible to call the -function with a vector argument to produce a vector result). - -Then we simply call quad: - -@example -@group -[v, ier, nfun, err] = quad ("f", 0, 3) - @result{} 1.9819 - @result{} 1 - @result{} 5061 - @result{} 1.1522e-07 -@end group -@end example - -Although @code{quad} returns a nonzero value for @var{ier}, the result -is reasonably accurate (to see why, examine what happens to the result -if you move the lower bound to 0.1, then 0.01, then 0.001, etc.). - -@node Orthogonal Collocation, , Functions of One Variable, Quadrature -@section Orthogonal Collocation - -@deftypefn {Loadable Function} {[@var{r}, @var{A}, @var{B}, @var{q}] =} colloc (@var{n}, "left", "right") -Compute derivative and integral weight matrices for orthogonal -collocation using the subroutines given in J. Villadsen and -M. L. Michelsen, @cite{Solution of Differential Equation Models by -Polynomial Approximation}. -@end deftypefn - -Here is an example of using @code{colloc} to generate weight matrices -for solving the second order differential equation -@iftex -@tex -$u^\prime - \alpha u^{\prime\prime} = 0$ with the boundary conditions -$u(0) = 0$ and $u(1) = 1$. -@end tex -@end iftex -@ifinfo -@var{u}' - @var{alpha} * @var{u}'' = 0 with the boundary conditions -@var{u}(0) = 0 and @var{u}(1) = 1. -@end ifinfo - -First, we can generate the weight matrices for @var{n} points (including -the endpoints of the interval), and incorporate the boundary conditions -in the right hand side (for a specific value of -@iftex -@tex -$\alpha$). -@end tex -@end iftex -@ifinfo -@var{alpha}). -@end ifinfo - -@example -@group -n = 7; -alpha = 0.1; -[r, a, b] = colloc (n-2, "left", "right"); -at = a(2:n-1,2:n-1); -bt = b(2:n-1,2:n-1); -rhs = alpha * b(2:n-1,n) - a(2:n-1,n); -@end group -@end example - -Then the solution at the roots @var{r} is - -@example -u = [ 0; (at - alpha * bt) \ rhs; 1] - @result{} [ 0.00; 0.004; 0.01 0.00; 0.12; 0.62; 1.00 ] -@end example diff --git a/doc/interpreter/quad.txi b/doc/interpreter/quad.txi new file mode 100644 --- /dev/null +++ b/doc/interpreter/quad.txi @@ -0,0 +1,160 @@ +@c Copyright (C) 1996, 1997 John W. Eaton +@c This is part of the Octave manual. +@c For copying conditions, see the file gpl.texi. + +@node Quadrature, Differential Equations, Nonlinear Equations, Top +@chapter Quadrature + +@menu +* Functions of One Variable:: +* Orthogonal Collocation:: +@end menu + +@node Functions of One Variable, Orthogonal Collocation, Quadrature, Quadrature +@section Functions of One Variable + +@deftypefn {Loadable Function} {[@var{v}, @var{ier}, @var{nfun}, @var{err}] =} quad (@var{f}, @var{a}, @var{b}, @var{tol}, @var{sing}) +Integrate a nonlinear function of one variable using Quadpack. +The first argument is the name of the function to call to compute the +value of the integrand. It must have the form + +@example +y = f (x) +@end example + +@noindent +where @var{y} and @var{x} are scalars. + +The second and third arguments are limits of integration. Either or +both may be infinite. + +The optional argument @var{tol} is a vector that specifies the desired +accuracy of the result. The first element of the vector is the desired +absolute tolerance, and the second element is the desired relative +tolerance. To choose a relative test only, set the absolute +tolerance to zero. To choose an absolute test only, set the relative +tolerance to zero. + +The optional argument @var{sing} is a vector of values at which the +integrand is known to be singular. + +The result of the integration is returned in @var{v} and @var{ier} +contains an integer error code (0 indicates a successful integration). +The value of @var{nfun} indicates how many function evaluations were +required, and @var{err} contains an estimate of the error in the +solution. +@end deftypefn + +@deftypefn {Loadable Function} {} quad_options (@var{opt}, @var{val}) +When called with two arguments, this function allows you set options +parameters for the function @code{quad}. Given one argument, +@code{quad_options} returns the value of the corresponding option. If +no arguments are supplied, the names of all the available options and +their current values are displayed. +@end deftypefn + +Here is an example of using @code{quad} to integrate the function +@iftex +@tex +$$ + f(x) = x \sin (1/x) \sqrt {|1 - x|} +$$ +from $x = 0$ to $x = 3$. +@end tex +@end iftex +@ifinfo + +@example + @var{f}(@var{x}) = @var{x} * sin (1/@var{x}) * sqrt (abs (1 - @var{x})) +@end example + +@noindent +from @var{x} = 0 to @var{x} = 3. +@end ifinfo + +This is a fairly difficult integration (plot the function over the range +of integration to see why). + +The first step is to define the function: + +@example +@group +function y = f (x) + y = x .* sin (1 ./ x) .* sqrt (abs (1 - x)); +endfunction +@end group +@end example + +Note the use of the `dot' forms of the operators. This is not necessary +for the call to @code{quad}, but it makes it much easier to generate a +set of points for plotting (because it makes it possible to call the +function with a vector argument to produce a vector result). + +Then we simply call quad: + +@example +@group +[v, ier, nfun, err] = quad ("f", 0, 3) + @result{} 1.9819 + @result{} 1 + @result{} 5061 + @result{} 1.1522e-07 +@end group +@end example + +Although @code{quad} returns a nonzero value for @var{ier}, the result +is reasonably accurate (to see why, examine what happens to the result +if you move the lower bound to 0.1, then 0.01, then 0.001, etc.). + +@node Orthogonal Collocation, , Functions of One Variable, Quadrature +@section Orthogonal Collocation + +@deftypefn {Loadable Function} {[@var{r}, @var{A}, @var{B}, @var{q}] =} colloc (@var{n}, "left", "right") +Compute derivative and integral weight matrices for orthogonal +collocation using the subroutines given in J. Villadsen and +M. L. Michelsen, @cite{Solution of Differential Equation Models by +Polynomial Approximation}. +@end deftypefn + +Here is an example of using @code{colloc} to generate weight matrices +for solving the second order differential equation +@iftex +@tex +$u^\prime - \alpha u^{\prime\prime} = 0$ with the boundary conditions +$u(0) = 0$ and $u(1) = 1$. +@end tex +@end iftex +@ifinfo +@var{u}' - @var{alpha} * @var{u}'' = 0 with the boundary conditions +@var{u}(0) = 0 and @var{u}(1) = 1. +@end ifinfo + +First, we can generate the weight matrices for @var{n} points (including +the endpoints of the interval), and incorporate the boundary conditions +in the right hand side (for a specific value of +@iftex +@tex +$\alpha$). +@end tex +@end iftex +@ifinfo +@var{alpha}). +@end ifinfo + +@example +@group +n = 7; +alpha = 0.1; +[r, a, b] = colloc (n-2, "left", "right"); +at = a(2:n-1,2:n-1); +bt = b(2:n-1,2:n-1); +rhs = alpha * b(2:n-1,n) - a(2:n-1,n); +@end group +@end example + +Then the solution at the roots @var{r} is + +@example +u = [ 0; (at - alpha * bt) \ rhs; 1] + @result{} [ 0.00; 0.004; 0.01 0.00; 0.12; 0.62; 1.00 ] +@end example diff --git a/doc/interpreter/set.texi b/doc/interpreter/set.texi deleted file mode 100644 --- a/doc/interpreter/set.texi +++ /dev/null @@ -1,57 +0,0 @@ -@c Copyright (C) 1996, 1997 John W. Eaton -@c This is part of the Octave manual. -@c For copying conditions, see the file gpl.texi. - -@node Sets, Polynomial Manipulations, Statistics, Top -@chapter Sets - -Octave has a limited set of functions for managing sets of data, where a -set is defined as a collection unique elements. - -@deftypefn {Function File} {} create_set (@var{x}) -Return a row vector containing the unique values in @var{x}, sorted in -ascending order. For example, - -@example -@group -create_set ([ 1, 2; 3, 4; 4, 2 ]) - @result{} [ 1, 2, 3, 4 ] -@end group -@end example -@end deftypefn - -@deftypefn {Function File} {} union (@var{x}, @var{y}) -Return the set of elements that are in either of the sets @var{x} and -@var{y}. For example, - -@example -@group -union ([ 1, 2, 4 ], [ 2, 3, 5 ]) - @result{} [ 1, 2, 3, 4, 5 ] -@end group -@end example -@end deftypefn - -@deftypefn {Function File} {} intersection (@var{x}, @var{y}) -Return the set of elements that are in both sets @var{x} and @var{y}. -For example, - -@example -@group -intersection ([ 1, 2, 3 ], [ 2, 3, 5 ]) - @result{} [ 2, 3 ] -@end group -@end example -@end deftypefn - -@deftypefn {Function File} {} complement (@var{x}, @var{y}) -Return the elements of set @var{y} that are not in set @var{x}. For -example, - -@example -@group -complement ([ 1, 2, 3 ], [ 2, 3, 5 ]) - @result{} 5 -@end group -@end example -@end deftypefn diff --git a/doc/interpreter/set.txi b/doc/interpreter/set.txi new file mode 100644 --- /dev/null +++ b/doc/interpreter/set.txi @@ -0,0 +1,57 @@ +@c Copyright (C) 1996, 1997 John W. Eaton +@c This is part of the Octave manual. +@c For copying conditions, see the file gpl.texi. + +@node Sets, Polynomial Manipulations, Statistics, Top +@chapter Sets + +Octave has a limited set of functions for managing sets of data, where a +set is defined as a collection unique elements. + +@deftypefn {Function File} {} create_set (@var{x}) +Return a row vector containing the unique values in @var{x}, sorted in +ascending order. For example, + +@example +@group +create_set ([ 1, 2; 3, 4; 4, 2 ]) + @result{} [ 1, 2, 3, 4 ] +@end group +@end example +@end deftypefn + +@deftypefn {Function File} {} union (@var{x}, @var{y}) +Return the set of elements that are in either of the sets @var{x} and +@var{y}. For example, + +@example +@group +union ([ 1, 2, 4 ], [ 2, 3, 5 ]) + @result{} [ 1, 2, 3, 4, 5 ] +@end group +@end example +@end deftypefn + +@deftypefn {Function File} {} intersection (@var{x}, @var{y}) +Return the set of elements that are in both sets @var{x} and @var{y}. +For example, + +@example +@group +intersection ([ 1, 2, 3 ], [ 2, 3, 5 ]) + @result{} [ 2, 3 ] +@end group +@end example +@end deftypefn + +@deftypefn {Function File} {} complement (@var{x}, @var{y}) +Return the elements of set @var{y} that are not in set @var{x}. For +example, + +@example +@group +complement ([ 1, 2, 3 ], [ 2, 3, 5 ]) + @result{} 5 +@end group +@end example +@end deftypefn diff --git a/doc/interpreter/signal.texi b/doc/interpreter/signal.texi deleted file mode 100644 --- a/doc/interpreter/signal.texi +++ /dev/null @@ -1,223 +0,0 @@ -@c Copyright (C) 1996, 1997 John W. Eaton -@c This is part of the Octave manual. -@c For copying conditions, see the file gpl.texi. - -@node Signal Processing, Image Processing, Control Theory, Top -@chapter Signal Processing - -I hope that someday Octave will include more signal processing -functions. If you would like to help improve Octave in this area, -please contact @email{bug-octave@@bevo.che.wisc.edu}. - -@deftypefn {Function File} {} detrend (@var{x}, @var{p}) -If @var{x} is a vector, @code{detrend (@var{x}, @var{p})} removes the -best fit of a polynomial of order @var{p} from the data @var{x}. - -If @var{x} is a matrix, @code{detrend (@var{x}, @var{p})} does the same -for each column in @var{x}. - -The second argument is optional. If it is not specified, a value of 1 -is assumed. This corresponds to removing a linear trend. -@end deftypefn - -@deftypefn {Function} {} fft (@var{a}, @var{n}) -Compute the FFT of @var{a} using subroutines from @sc{Fftpack}. If @var{a} -is a matrix, @code{fft} computes the FFT for each column of @var{a}. - -If called with two arguments, @var{n} is expected to be an integer -specifying the number of elements of @var{a} to use. If @var{a} is a -matrix, @var{n} specifies the number of rows of @var{a} to use. If -@var{n} is larger than the size of @var{a}, @var{a} is resized and -padded with zeros. -@end deftypefn - -@deftypefn {Loadable Function} {} ifft (@var{a}, @var{n}) -Compute the inverse FFT of @var{a} using subroutines from @sc{Fftpack}. If -@var{a} is a matrix, @code{fft} computes the inverse FFT for each column -of @var{a}. - -If called with two arguments, @var{n} is expected to be an integer -specifying the number of elements of @var{a} to use. If @var{a} is a -matrix, @var{n} specifies the number of rows of @var{a} to use. If -@var{n} is larger than the size of @var{a}, @var{a} is resized and -padded with zeros. -@end deftypefn - -@deftypefn {Loadable Function} {} fft2 (@var{a}, @var{n}, @var{m}) -Compute the two dimensional FFT of @var{a}. - -The optional arguments @var{n} and @var{m} may be used specify the -number of rows and columns of @var{a} to use. If either of these is -larger than the size of @var{a}, @var{a} is resized and padded with -zeros. -@end deftypefn - -@deftypefn {Loadable Function} {} ifft2 (@var{a}, @var{n}, @var{m}) -Compute the two dimensional inverse FFT of @var{a}. - -The optional arguments @var{n} and @var{m} may be used specify the -number of rows and columns of @var{a} to use. If either of these is -larger than the size of @var{a}, @var{a} is resized and padded with -zeros. -@end deftypefn - -@deftypefn {Built-in Function} {} fftconv (@var{a}, @var{b}, @var{n}) -Return the convolution of the vectors @var{a} and @var{b}, as a vector -with length equal to the @code{length (a) + length (b) - 1}. If @var{a} -and @var{b} are the coefficient vectors of two polynomials, the returned -value is the coefficient vector of the product polynomial. - -The computation uses the FFT by calling the function @code{fftfilt}. If -the optional argument @var{n} is specified, an N-point FFT is used. -@end deftypefn - -@deftypefn {Function File} {} fftfilt (@var{b}, @var{x}, @var{n}) - -With two arguments, @code{fftfilt} filters @var{x} with the FIR filter -@var{b} using the FFT. - -Given the optional third argument, @var{n}, @code{fftfilt} uses the -overlap-add method to filter @var{x} with @var{b} using an N-point FFT. -@end deftypefn - -@deftypefn {Loadable Function} {y =} filter (@var{b}, @var{a}, @var{x}) -Return the solution to the following linear, time-invariant difference -equation: -@iftex -@tex -$$ -\sum_{k=0}^N a_{k+1} y_{n-k} = \sum_{k=0}^M b_{k+1} x_{n-k}, \qquad - 1 \le n \le P -$$ -@end tex -@end iftex -@ifinfo - -@smallexample - N M - SUM a(k+1) y(n-k) = SUM b(k+1) x(n-k) for 1<=n<=length(x) - k=0 k=0 -@end smallexample -@end ifinfo - -@noindent -where -@ifinfo - N=length(a)-1 and M=length(b)-1. -@end ifinfo -@iftex -@tex - $a \in \Re^{N-1}$, $b \in \Re^{M-1}$, and $x \in \Re^P$. -@end tex -@end iftex -An equivalent form of this equation is: -@iftex -@tex -$$ -y_n = -\sum_{k=1}^N c_{k+1} y_{n-k} + \sum_{k=0}^M d_{k+1} x_{n-k}, \qquad - 1 \le n \le P -$$ -@end tex -@end iftex -@ifinfo - -@smallexample - N M - y(n) = - SUM c(k+1) y(n-k) + SUM d(k+1) x(n-k) for 1<=n<=length(x) - k=1 k=0 -@end smallexample -@end ifinfo - -@noindent -where -@ifinfo - c = a/a(1) and d = b/a(1). -@end ifinfo -@iftex -@tex -$c = a/a_1$ and $d = b/a_1$. -@end tex -@end iftex - -In terms of the z-transform, y is the result of passing the discrete- -time signal x through a system characterized by the following rational -system function: -@iftex -@tex -$$ -H(z) = {\displaystyle\sum_{k=0}^M d_{k+1} z^{-k} - \over 1 + \displaystyle\sum_{k+1}^N c_{k+1} z^{-k}} -$$ -@end tex -@end iftex -@ifinfo - -@example - M - SUM d(k+1) z^(-k) - k=0 - H(z) = ---------------------- - N - 1 + SUM c(k+1) z(-k) - k=1 -@end example -@end ifinfo -@end deftypefn - -@deftypefn {Loadable Function} {[@var{y}, @var{sf}] =} filter (@var{b}, @var{a}, @var{x}, @var{si}) -This is the same as the @code{filter} function described above, except -that @var{si} is taken as the initial state of the system and the final -state is returned as @var{sf}. The state vector is a column vector -whose length is equal to the length of the longest coefficient vector -minus one. If @var{si} is not set, the initial state vector is set to -all zeros. -@end deftypefn - -@deftypefn {Function File} {[@var{h}, @var{w}] =} freqz (@var{b}, @var{a}, @var{n}, "whole") -Return the complex frequency response @var{h} of the rational IIR filter -whose numerator and denominator coefficients are @var{b} and @var{a}, -respectively. The response is evaluated at @var{n} angular frequencies -between 0 and -@ifinfo - 2*pi. -@end ifinfo -@iftex -@tex - $2\pi$. -@end tex -@end iftex - -@noindent -The output value @var{w} is a vector of the frequencies. - -If the fourth argument is omitted, the response is evaluated at -frequencies between 0 and -@ifinfo - pi. -@end ifinfo -@iftex -@tex - $\pi$. -@end tex -@end iftex - -If @var{n} is omitted, a value of 512 is assumed. - -If @var{a} is omitted, the denominator is assumed to be 1 (this -corresponds to a simple FIR filter). - -For fastest computation, @var{n} should factor into a small number of -small primes. -@end deftypefn - -@deftypefn {Function File} {} sinc (@var{x}) -Return -@iftex -@tex -$ \sin (\pi x)/(\pi x)$. -@end tex -@end iftex -@ifinfo - sin(pi*x)/(pi*x). -@end ifinfo -@end deftypefn diff --git a/doc/interpreter/signal.txi b/doc/interpreter/signal.txi new file mode 100644 --- /dev/null +++ b/doc/interpreter/signal.txi @@ -0,0 +1,223 @@ +@c Copyright (C) 1996, 1997 John W. Eaton +@c This is part of the Octave manual. +@c For copying conditions, see the file gpl.texi. + +@node Signal Processing, Image Processing, Control Theory, Top +@chapter Signal Processing + +I hope that someday Octave will include more signal processing +functions. If you would like to help improve Octave in this area, +please contact @email{bug-octave@@bevo.che.wisc.edu}. + +@deftypefn {Function File} {} detrend (@var{x}, @var{p}) +If @var{x} is a vector, @code{detrend (@var{x}, @var{p})} removes the +best fit of a polynomial of order @var{p} from the data @var{x}. + +If @var{x} is a matrix, @code{detrend (@var{x}, @var{p})} does the same +for each column in @var{x}. + +The second argument is optional. If it is not specified, a value of 1 +is assumed. This corresponds to removing a linear trend. +@end deftypefn + +@deftypefn {Function} {} fft (@var{a}, @var{n}) +Compute the FFT of @var{a} using subroutines from @sc{Fftpack}. If @var{a} +is a matrix, @code{fft} computes the FFT for each column of @var{a}. + +If called with two arguments, @var{n} is expected to be an integer +specifying the number of elements of @var{a} to use. If @var{a} is a +matrix, @var{n} specifies the number of rows of @var{a} to use. If +@var{n} is larger than the size of @var{a}, @var{a} is resized and +padded with zeros. +@end deftypefn + +@deftypefn {Loadable Function} {} ifft (@var{a}, @var{n}) +Compute the inverse FFT of @var{a} using subroutines from @sc{Fftpack}. If +@var{a} is a matrix, @code{fft} computes the inverse FFT for each column +of @var{a}. + +If called with two arguments, @var{n} is expected to be an integer +specifying the number of elements of @var{a} to use. If @var{a} is a +matrix, @var{n} specifies the number of rows of @var{a} to use. If +@var{n} is larger than the size of @var{a}, @var{a} is resized and +padded with zeros. +@end deftypefn + +@deftypefn {Loadable Function} {} fft2 (@var{a}, @var{n}, @var{m}) +Compute the two dimensional FFT of @var{a}. + +The optional arguments @var{n} and @var{m} may be used specify the +number of rows and columns of @var{a} to use. If either of these is +larger than the size of @var{a}, @var{a} is resized and padded with +zeros. +@end deftypefn + +@deftypefn {Loadable Function} {} ifft2 (@var{a}, @var{n}, @var{m}) +Compute the two dimensional inverse FFT of @var{a}. + +The optional arguments @var{n} and @var{m} may be used specify the +number of rows and columns of @var{a} to use. If either of these is +larger than the size of @var{a}, @var{a} is resized and padded with +zeros. +@end deftypefn + +@deftypefn {Built-in Function} {} fftconv (@var{a}, @var{b}, @var{n}) +Return the convolution of the vectors @var{a} and @var{b}, as a vector +with length equal to the @code{length (a) + length (b) - 1}. If @var{a} +and @var{b} are the coefficient vectors of two polynomials, the returned +value is the coefficient vector of the product polynomial. + +The computation uses the FFT by calling the function @code{fftfilt}. If +the optional argument @var{n} is specified, an N-point FFT is used. +@end deftypefn + +@deftypefn {Function File} {} fftfilt (@var{b}, @var{x}, @var{n}) + +With two arguments, @code{fftfilt} filters @var{x} with the FIR filter +@var{b} using the FFT. + +Given the optional third argument, @var{n}, @code{fftfilt} uses the +overlap-add method to filter @var{x} with @var{b} using an N-point FFT. +@end deftypefn + +@deftypefn {Loadable Function} {y =} filter (@var{b}, @var{a}, @var{x}) +Return the solution to the following linear, time-invariant difference +equation: +@iftex +@tex +$$ +\sum_{k=0}^N a_{k+1} y_{n-k} = \sum_{k=0}^M b_{k+1} x_{n-k}, \qquad + 1 \le n \le P +$$ +@end tex +@end iftex +@ifinfo + +@smallexample + N M + SUM a(k+1) y(n-k) = SUM b(k+1) x(n-k) for 1<=n<=length(x) + k=0 k=0 +@end smallexample +@end ifinfo + +@noindent +where +@ifinfo + N=length(a)-1 and M=length(b)-1. +@end ifinfo +@iftex +@tex + $a \in \Re^{N-1}$, $b \in \Re^{M-1}$, and $x \in \Re^P$. +@end tex +@end iftex +An equivalent form of this equation is: +@iftex +@tex +$$ +y_n = -\sum_{k=1}^N c_{k+1} y_{n-k} + \sum_{k=0}^M d_{k+1} x_{n-k}, \qquad + 1 \le n \le P +$$ +@end tex +@end iftex +@ifinfo + +@smallexample + N M + y(n) = - SUM c(k+1) y(n-k) + SUM d(k+1) x(n-k) for 1<=n<=length(x) + k=1 k=0 +@end smallexample +@end ifinfo + +@noindent +where +@ifinfo + c = a/a(1) and d = b/a(1). +@end ifinfo +@iftex +@tex +$c = a/a_1$ and $d = b/a_1$. +@end tex +@end iftex + +In terms of the z-transform, y is the result of passing the discrete- +time signal x through a system characterized by the following rational +system function: +@iftex +@tex +$$ +H(z) = {\displaystyle\sum_{k=0}^M d_{k+1} z^{-k} + \over 1 + \displaystyle\sum_{k+1}^N c_{k+1} z^{-k}} +$$ +@end tex +@end iftex +@ifinfo + +@example + M + SUM d(k+1) z^(-k) + k=0 + H(z) = ---------------------- + N + 1 + SUM c(k+1) z(-k) + k=1 +@end example +@end ifinfo +@end deftypefn + +@deftypefn {Loadable Function} {[@var{y}, @var{sf}] =} filter (@var{b}, @var{a}, @var{x}, @var{si}) +This is the same as the @code{filter} function described above, except +that @var{si} is taken as the initial state of the system and the final +state is returned as @var{sf}. The state vector is a column vector +whose length is equal to the length of the longest coefficient vector +minus one. If @var{si} is not set, the initial state vector is set to +all zeros. +@end deftypefn + +@deftypefn {Function File} {[@var{h}, @var{w}] =} freqz (@var{b}, @var{a}, @var{n}, "whole") +Return the complex frequency response @var{h} of the rational IIR filter +whose numerator and denominator coefficients are @var{b} and @var{a}, +respectively. The response is evaluated at @var{n} angular frequencies +between 0 and +@ifinfo + 2*pi. +@end ifinfo +@iftex +@tex + $2\pi$. +@end tex +@end iftex + +@noindent +The output value @var{w} is a vector of the frequencies. + +If the fourth argument is omitted, the response is evaluated at +frequencies between 0 and +@ifinfo + pi. +@end ifinfo +@iftex +@tex + $\pi$. +@end tex +@end iftex + +If @var{n} is omitted, a value of 512 is assumed. + +If @var{a} is omitted, the denominator is assumed to be 1 (this +corresponds to a simple FIR filter). + +For fastest computation, @var{n} should factor into a small number of +small primes. +@end deftypefn + +@deftypefn {Function File} {} sinc (@var{x}) +Return +@iftex +@tex +$ \sin (\pi x)/(\pi x)$. +@end tex +@end iftex +@ifinfo + sin(pi*x)/(pi*x). +@end ifinfo +@end deftypefn diff --git a/doc/interpreter/stats.texi b/doc/interpreter/stats.texi deleted file mode 100644 --- a/doc/interpreter/stats.texi +++ /dev/null @@ -1,140 +0,0 @@ -@c Copyright (C) 1996, 1997 John W. Eaton -@c This is part of the Octave manual. -@c For copying conditions, see the file gpl.texi. - -@node Statistics, Sets, Optimization, Top -@chapter Statistics - -I hope that someday Octave will include more statistics functions. If -you would like to help improve Octave in this area, please contact -@email{bug-octave@@bevo.che.wisc.edu}. - -@deftypefn {Function File} {} mean (@var{x}) -If @var{x} is a vector, compute the mean of the elements of @var{x} -@iftex -@tex -$$ {\rm mean}(x) = \bar{x} = {1\over N} \sum_{i=1}^N x_i $$ -@end tex -@end iftex -@ifinfo - -@example -mean (x) = SUM_i x(i) / N -@end example -@end ifinfo -If @var{x} is a matrix, compute the mean for each column and return them -in a row vector. -@end deftypefn - -@deftypefn {Function File} {} median (@var{x}) -If @var{x} is a vector, compute the median value of the elements of -@var{x}. -@iftex -@tex -$$ -{\rm median} (x) = - \cases{x(\lceil N/2\rceil), & $N$ odd;\cr - (x(N/2)+x(N/2+1))/2, & $N$ even.} -$$ -@end tex -@end iftex -@ifinfo - -@example -@group - x(ceil(N/2)), N odd -median(x) = - (x(N/2) + x((N/2)+1))/2, N even -@end group -@end example -@end ifinfo -If @var{x} is a matrix, compute the median value for each -column and return them in a row vector. -@end deftypefn - -@deftypefn {Function File} {} std (@var{x}) -If @var{x} is a vector, compute the standard deviation of the elements -of @var{x}. -@iftex -@tex -$$ -{\rm std} (x) = \sigma (x) = \sqrt{{\sum_{i=1}^N (x_i - \bar{x}) \over N - 1}} -$$ -@end tex -@end iftex -@ifinfo - -@example -@group -std (x) = sqrt (sumsq (x - mean (x)) / (n - 1)) -@end group -@end example -@end ifinfo -If @var{x} is a matrix, compute the standard deviation for -each column and return them in a row vector. -@end deftypefn - -@deftypefn {Function File} {} cov (@var{x}, @var{y}) -If each row of @var{x} and @var{y} is an observation and each column is -a variable, the (@var{i},@var{j})-th entry of -@code{cov (@var{x}, @var{y})} is the covariance between the @var{i}-th -variable in @var{x} and the @var{j}-th variable in @var{y}. If called -with one argument, compute @code{cov (@var{x}, @var{x})}. -@end deftypefn - -@deftypefn {Function File} {} corrcoef (@var{x}, @var{y}) -If each row of @var{x} and @var{y} is an observation and each column is -a variable, the (@var{i},@var{j})-th entry of -@code{corrcoef (@var{x}, @var{y})} is the correlation between the -@var{i}-th variable in @var{x} and the @var{j}-th variable in @var{y}. -If called with one argument, compute @code{corrcoef (@var{x}, @var{x})}. -@end deftypefn - -@deftypefn {Function File} {} kurtosis (@var{x}) -If @var{x} is a vector of length @var{N}, return the kurtosis -@iftex -@tex -$$ - {\rm kurtosis} (x) = {1\over N \sigma(x)^4} \sum_{i=1}^N (x_i-\bar{x})^4 - 3 -$$ -@end tex -@end iftex -@ifinfo - -@example -kurtosis (x) = N^(-1) std(x)^(-4) sum ((x - mean(x)).^4) - 3 -@end example -@end ifinfo - -@noindent -of @var{x}. If @var{x} is a matrix, return the row vector containing -the kurtosis of each column. -@end deftypefn - -@deftypefn {Function File} {} mahalanobis (@var{x}, @var{y}) -Return the Mahalanobis' D-square distance between the multivariate -samples @var{x} and @var{y}, which must have the same number of -components (columns), but may have a different number of observations -(rows). -@end deftypefn - -@deftypefn {Function File} {} skewness (@var{x}) -If @var{x} is a vector of length @var{N}, return the skewness -@iftex -@tex -$$ -{\rm skewness} (x) = {1\over N \sigma(x)^3} \sum_{i=1}^N (x_i-\bar{x})^3 -$$ -@end tex -@end iftex -@ifinfo - -@example -skewness (x) = N^(-1) std(x)^(-3) sum ((x - mean(x)).^3) -@end example -@end ifinfo - -@noindent -of @var{x}. If @var{x} is a matrix, return the row vector containing -the skewness of each column. -@end deftypefn diff --git a/doc/interpreter/stats.txi b/doc/interpreter/stats.txi new file mode 100644 --- /dev/null +++ b/doc/interpreter/stats.txi @@ -0,0 +1,140 @@ +@c Copyright (C) 1996, 1997 John W. Eaton +@c This is part of the Octave manual. +@c For copying conditions, see the file gpl.texi. + +@node Statistics, Sets, Optimization, Top +@chapter Statistics + +I hope that someday Octave will include more statistics functions. If +you would like to help improve Octave in this area, please contact +@email{bug-octave@@bevo.che.wisc.edu}. + +@deftypefn {Function File} {} mean (@var{x}) +If @var{x} is a vector, compute the mean of the elements of @var{x} +@iftex +@tex +$$ {\rm mean}(x) = \bar{x} = {1\over N} \sum_{i=1}^N x_i $$ +@end tex +@end iftex +@ifinfo + +@example +mean (x) = SUM_i x(i) / N +@end example +@end ifinfo +If @var{x} is a matrix, compute the mean for each column and return them +in a row vector. +@end deftypefn + +@deftypefn {Function File} {} median (@var{x}) +If @var{x} is a vector, compute the median value of the elements of +@var{x}. +@iftex +@tex +$$ +{\rm median} (x) = + \cases{x(\lceil N/2\rceil), & $N$ odd;\cr + (x(N/2)+x(N/2+1))/2, & $N$ even.} +$$ +@end tex +@end iftex +@ifinfo + +@example +@group + x(ceil(N/2)), N odd +median(x) = + (x(N/2) + x((N/2)+1))/2, N even +@end group +@end example +@end ifinfo +If @var{x} is a matrix, compute the median value for each +column and return them in a row vector. +@end deftypefn + +@deftypefn {Function File} {} std (@var{x}) +If @var{x} is a vector, compute the standard deviation of the elements +of @var{x}. +@iftex +@tex +$$ +{\rm std} (x) = \sigma (x) = \sqrt{{\sum_{i=1}^N (x_i - \bar{x}) \over N - 1}} +$$ +@end tex +@end iftex +@ifinfo + +@example +@group +std (x) = sqrt (sumsq (x - mean (x)) / (n - 1)) +@end group +@end example +@end ifinfo +If @var{x} is a matrix, compute the standard deviation for +each column and return them in a row vector. +@end deftypefn + +@deftypefn {Function File} {} cov (@var{x}, @var{y}) +If each row of @var{x} and @var{y} is an observation and each column is +a variable, the (@var{i},@var{j})-th entry of +@code{cov (@var{x}, @var{y})} is the covariance between the @var{i}-th +variable in @var{x} and the @var{j}-th variable in @var{y}. If called +with one argument, compute @code{cov (@var{x}, @var{x})}. +@end deftypefn + +@deftypefn {Function File} {} corrcoef (@var{x}, @var{y}) +If each row of @var{x} and @var{y} is an observation and each column is +a variable, the (@var{i},@var{j})-th entry of +@code{corrcoef (@var{x}, @var{y})} is the correlation between the +@var{i}-th variable in @var{x} and the @var{j}-th variable in @var{y}. +If called with one argument, compute @code{corrcoef (@var{x}, @var{x})}. +@end deftypefn + +@deftypefn {Function File} {} kurtosis (@var{x}) +If @var{x} is a vector of length @var{N}, return the kurtosis +@iftex +@tex +$$ + {\rm kurtosis} (x) = {1\over N \sigma(x)^4} \sum_{i=1}^N (x_i-\bar{x})^4 - 3 +$$ +@end tex +@end iftex +@ifinfo + +@example +kurtosis (x) = N^(-1) std(x)^(-4) sum ((x - mean(x)).^4) - 3 +@end example +@end ifinfo + +@noindent +of @var{x}. If @var{x} is a matrix, return the row vector containing +the kurtosis of each column. +@end deftypefn + +@deftypefn {Function File} {} mahalanobis (@var{x}, @var{y}) +Return the Mahalanobis' D-square distance between the multivariate +samples @var{x} and @var{y}, which must have the same number of +components (columns), but may have a different number of observations +(rows). +@end deftypefn + +@deftypefn {Function File} {} skewness (@var{x}) +If @var{x} is a vector of length @var{N}, return the skewness +@iftex +@tex +$$ +{\rm skewness} (x) = {1\over N \sigma(x)^3} \sum_{i=1}^N (x_i-\bar{x})^3 +$$ +@end tex +@end iftex +@ifinfo + +@example +skewness (x) = N^(-1) std(x)^(-3) sum ((x - mean(x)).^3) +@end example +@end ifinfo + +@noindent +of @var{x}. If @var{x} is a matrix, return the row vector containing +the skewness of each column. +@end deftypefn diff --git a/doc/interpreter/stmt.texi b/doc/interpreter/stmt.texi deleted file mode 100644 --- a/doc/interpreter/stmt.texi +++ /dev/null @@ -1,802 +0,0 @@ -@c Copyright (C) 1996, 1997 John W. Eaton -@c This is part of the Octave manual. -@c For copying conditions, see the file gpl.texi. - -@node Statements, Functions and Scripts, Evaluation, Top -@chapter Statements -@cindex statements - -Statements may be a simple constant expression or a complicated list of -nested loops and conditional statements. - -@dfn{Control statements} such as @code{if}, @code{while}, and so on -control the flow of execution in Octave programs. All the control -statements start with special keywords such as @code{if} and -@code{while}, to distinguish them from simple expressions. -Many control statements contain other statements; for example, the -@code{if} statement contains another statement which may or may not be -executed. - -@cindex @code{end} statement -Each control statement has a corresponding @dfn{end} statement that -marks the end of the end of the control statement. For example, the -keyword @code{endif} marks the end of an @code{if} statement, and -@code{endwhile} marks the end of a @code{while} statement. You can use -the keyword @code{end} anywhere a more specific end keyword is expected, -but using the more specific keywords is preferred because if you use -them, Octave is able to provide better diagnostics for mismatched or -missing end tokens. - -The list of statements contained between keywords like @code{if} or -@code{while} and the corresponding end statement is called the -@dfn{body} of a control statement. - -@menu -* The if Statement:: -* The switch Statement:: -* The while Statement:: -* The for Statement:: -* The break Statement:: -* The continue Statement:: -* The unwind_protect Statement:: -* The try Statement:: -* Continuation Lines:: -@end menu - -@node The if Statement, The switch Statement, Statements, Statements -@section The @code{if} Statement -@cindex @code{if} statement -@cindex @code{else} statement -@cindex @code{elseif} statement -@cindex @code{endif} statement - -The @code{if} statement is Octave's decision-making statement. There -are three basic forms of an @code{if} statement. In its simplest form, -it looks like this: - -@example -@group -if (@var{condition}) - @var{then-body} -endif -@end group -@end example - -@noindent -@var{condition} is an expression that controls what the rest of the -statement will do. The @var{then-body} is executed only if -@var{condition} is true. - -The condition in an @code{if} statement is considered true if its value -is non-zero, and false if its value is zero. If the value of the -conditional expression in an @code{if} statement is a vector or a -matrix, it is considered true only if @emph{all} of the elements are -non-zero. - -The second form of an if statement looks like this: - -@example -@group -if (@var{condition}) - @var{then-body} -else - @var{else-body} -endif -@end group -@end example - -@noindent -If @var{condition} is true, @var{then-body} is executed; otherwise, -@var{else-body} is executed. - -Here is an example: - -@example -@group -if (rem (x, 2) == 0) - printf ("x is even\n"); -else - printf ("x is odd\n"); -endif -@end group -@end example - -In this example, if the expression @code{rem (x, 2) == 0} is true (that -is, the value of @code{x} is divisible by 2), then the first -@code{printf} statement is evaluated, otherwise the second @code{printf} -statement is evaluated. - -The third and most general form of the @code{if} statement allows -multiple decisions to be combined in a single statement. It looks like -this: - -@example -@group -if (@var{condition}) - @var{then-body} -elseif (@var{condition}) - @var{elseif-body} -else - @var{else-body} -endif -@end group -@end example - -@noindent -Any number of @code{elseif} clauses may appear. Each condition is -tested in turn, and if one is found to be true, its corresponding -@var{body} is executed. If none of the conditions are true and the -@code{else} clause is present, its body is executed. Only one -@code{else} clause may appear, and it must be the last part of the -statement. - -In the following example, if the first condition is true (that is, the -value of @code{x} is divisible by 2), then the first @code{printf} -statement is executed. If it is false, then the second condition is -tested, and if it is true (that is, the value of @code{x} is divisible -by 3), then the second @code{printf} statement is executed. Otherwise, -the third @code{printf} statement is performed. - -@example -@group -if (rem (x, 2) == 0) - printf ("x is even\n"); -elseif (rem (x, 3) == 0) - printf ("x is odd and divisible by 3\n"); -else - printf ("x is odd\n"); -endif -@end group -@end example - -Note that the @code{elseif} keyword must not be spelled @code{else if}, -as is allowed in Fortran. If it is, the space between the @code{else} -and @code{if} will tell Octave to treat this as a new @code{if} -statement within another @code{if} statement's @code{else} clause. For -example, if you write - -@example -@group -if (@var{c1}) - @var{body-1} -else if (@var{c2}) - @var{body-2} -endif -@end group -@end example - -@noindent -Octave will expect additional input to complete the first @code{if} -statement. If you are using Octave interactively, it will continue to -prompt you for additional input. If Octave is reading this input from a -file, it may complain about missing or mismatched @code{end} statements, -or, if you have not used the more specific @code{end} statements -(@code{endif}, @code{endfor}, etc.), it may simply produce incorrect -results, without producing any warning messages. - -It is much easier to see the error if we rewrite the statements above -like this, - -@example -@group -if (@var{c1}) - @var{body-1} -else - if (@var{c2}) - @var{body-2} - endif -@end group -@end example - -@noindent -using the indentation to show how Octave groups the statements. -@xref{Functions and Scripts}. - -@defvr {Built-in Variable} warn_assign_as_truth_value -If the value of @code{warn_assign_as_truth_value} is nonzero, a -warning is issued for statements like - -@example -if (s = t) - ... -@end example - -@noindent -since such statements are not common, and it is likely that the intent -was to write - -@example -if (s == t) - ... -@end example - -@noindent -instead. - -There are times when it is useful to write code that contains -assignments within the condition of a @code{while} or @code{if} -statement. For example, statements like - -@example -while (c = getc()) - ... -@end example - -@noindent -are common in C programming. - -It is possible to avoid all warnings about such statements by setting -@code{warn_assign_as_truth_value} to 0, but that may also -let real errors like - -@example -if (x = 1) # intended to test (x == 1)! - ... -@end example - -@noindent -slip by. - -In such cases, it is possible suppress errors for specific statements by -writing them with an extra set of parentheses. For example, writing the -previous example as - -@example -while ((c = getc())) - ... -@end example - -@noindent -will prevent the warning from being printed for this statement, while -allowing Octave to warn about other assignments used in conditional -contexts. - -The default value of @code{warn_assign_as_truth_value} is 1. -@end defvr - -@node The switch Statement, The while Statement, The if Statement, Statements -@section The @code{switch} Statement -@cindex @code{switch} statement -@cindex @code{case} statement -@cindex @code{otherwise} statement -@cindex @code{endswitch} statement - -The @code{switch} statement was introduced in Octave 2.0.5. It should -be considered experimental, and details of the implementation may change -slightly in future versions of Octave. If you have comments or would -like to share your experiences in trying to use this new command in real -programs, please send them to -@email{octave-maintainers@@bevo.che.wisc.edu}. (But if you think you've -found a bug, please report it to @email{bug-octave@@bevo.che.wisc.edu}. - -The general form of the @code{switch} statement is - -@example -@group -switch @var{expression} - case @var{label} - @var{command_list} - case @var{label} - @var{command_list} - @dots{} - - otherwise - @var{command_list} -endswitch -@end group -@end example - -@itemize @bullet -@item -The identifiers @code{switch}, @code{case}, @code{otherwise}, and -@code{endswitch} are now keywords. - -@item -The @var{label} may be any expression. - -@item -Duplicate @var{label} values are not detected. The @var{command_list} -corresponding to the first match will be executed. - -@item -You must have at least one @code{case @var{label} @var{command_list}} -clause. - -@item -The @code{otherwise @var{command_list}} clause is optional. - -@item -As with all other specific @code{end} keywords, @code{endswitch} may be -replaced by @code{end}, but you can get better diagnostics if you use -the specific forms. - -@item -Cases are exclusive, so they don't `fall through' as do the cases -in the switch statement of the C language. - -@item -The @var{command_list} elements are not optional. Making the list -optional would have meant requiring a separator between the label and -the command list. Otherwise, things like - -@example -@group -switch (foo) - case (1) -2 - @dots{} -@end group -@end example - -@noindent -would produce surprising results, as would - -@example -@group -switch (foo) - case (1) - case (2) - doit (); - @dots{} -@end group -@end example - -@noindent -particularly for C programmers. - -@item -The implementation is simple-minded and currently offers no real -performance improvement over an equivalent @code{if} block, even if all -the labels are integer constants. Perhaps a future variation on this -could detect all constant integer labels and improve performance by -using a jump table. -@end itemize - -@defvr {Built-in Variable} warn_variable_switch_label -If the value of this variable is nonzero, Octave will print a warning if -a switch label is not a constant or constant expression -@end defvr - -@node The while Statement, The for Statement, The switch Statement, Statements -@section The @code{while} Statement -@cindex @code{while} statement -@cindex @code{endwhile} statement -@cindex loop -@cindex body of a loop - -In programming, a @dfn{loop} means a part of a program that is (or at least can -be) executed two or more times in succession. - -The @code{while} statement is the simplest looping statement in Octave. -It repeatedly executes a statement as long as a condition is true. As -with the condition in an @code{if} statement, the condition in a -@code{while} statement is considered true if its value is non-zero, and -false if its value is zero. If the value of the conditional expression -in a @code{while} statement is a vector or a matrix, it is considered -true only if @emph{all} of the elements are non-zero. - -Octave's @code{while} statement looks like this: - -@example -@group -while (@var{condition}) - @var{body} -endwhile -@end group -@end example - -@noindent -Here @var{body} is a statement or list of statements that we call the -@dfn{body} of the loop, and @var{condition} is an expression that -controls how long the loop keeps running. - -The first thing the @code{while} statement does is test @var{condition}. -If @var{condition} is true, it executes the statement @var{body}. After -@var{body} has been executed, @var{condition} is tested again, and if it -is still true, @var{body} is executed again. This process repeats until -@var{condition} is no longer true. If @var{condition} is initially -false, the body of the loop is never executed. - -This example creates a variable @code{fib} that contains the first ten -elements of the Fibonacci sequence. - -@example -@group -fib = ones (1, 10); -i = 3; -while (i <= 10) - fib (i) = fib (i-1) + fib (i-2); - i++; -endwhile -@end group -@end example - -@noindent -Here the body of the loop contains two statements. - -The loop works like this: first, the value of @code{i} is set to 3. -Then, the @code{while} tests whether @code{i} is less than or equal to -10. This is the case when @code{i} equals 3, so the value of the -@code{i}-th element of @code{fib} is set to the sum of the previous two -values in the sequence. Then the @code{i++} increments the value of -@code{i} and the loop repeats. The loop terminates when @code{i} -reaches 11. - -A newline is not required between the condition and the -body; but using one makes the program clearer unless the body is very -simple. - -@xref{The if Statement} for a description of the variable -@code{warn_assign_as_truth_value}. - -@node The for Statement, The break Statement, The while Statement, Statements -@section The @code{for} Statement -@cindex @code{for} statement -@cindex @code{endfor} statement - -The @code{for} statement makes it more convenient to count iterations of a -loop. The general form of the @code{for} statement looks like this: - -@example -@group -for @var{var} = @var{expression} - @var{body} -endfor -@end group -@end example - -@noindent -where @var{body} stands for any statement or list of statements, -@var{expression} is any valid expression, and @var{var} may take several -forms. Usually it is a simple variable name or an indexed variable. If -the value of @var{expression} is a structure, @var{var} may also be a -list. @xref{Looping Over Structure Elements}, below. - -The assignment expression in the @code{for} statement works a bit -differently than Octave's normal assignment statement. Instead of -assigning the complete result of the expression, it assigns each column -of the expression to @var{var} in turn. If @var{expression} is a range, -a row vector, or a scalar, the value of @var{var} will be a scalar each -time the loop body is executed. If @var{var} is a column vector or a -matrix, @var{var} will be a column vector each time the loop body is -executed. - -The following example shows another way to create a vector containing -the first ten elements of the Fibonacci sequence, this time using the -@code{for} statement: - -@example -@group -fib = ones (1, 10); -for i = 3:10 - fib (i) = fib (i-1) + fib (i-2); -endfor -@end group -@end example - -@noindent -This code works by first evaluating the expression @code{3:10}, to -produce a range of values from 3 to 10 inclusive. Then the variable -@code{i} is assigned the first element of the range and the body of the -loop is executed once. When the end of the loop body is reached, the -next value in the range is assigned to the variable @code{i}, and the -loop body is executed again. This process continues until there are no -more elements to assign. - -Although it is possible to rewrite all @code{for} loops as @code{while} -loops, the Octave language has both statements because often a -@code{for} loop is both less work to type and more natural to think of. -Counting the number of iterations is very common in loops and it can be -easier to think of this counting as part of looping rather than as -something to do inside the loop. - -@menu -* Looping Over Structure Elements:: -@end menu - -@node Looping Over Structure Elements, , The for Statement, The for Statement -@subsection Looping Over Structure Elements -@cindex structure elements, looping over -@cindex looping over structure elements - -A special form of the @code{for} statement allows you to loop over all -the elements of a structure: - -@example -@group -for [ @var{val}, @var{key} ] = @var{expression} - @var{body} -endfor -@end group -@end example - -@noindent -In this form of the @code{for} statement, the value of @var{expression} -must be a structure. If it is, @var{key} and @var{val} are set to the -name of the element and the corresponding value in turn, until there are -no more elements. For example, - -@example -@group -x.a = 1 -x.b = [1, 2; 3, 4] -x.c = "string" -for [val, key] = x - key - val -endfor - - @print{} key = a - @print{} val = 1 - @print{} key = b - @print{} val = - @print{} - @print{} 1 2 - @print{} 3 4 - @print{} - @print{} key = c - @print{} val = string -@end group -@end example - -The elements are not accessed in any particular order. If you need to -cycle through the list in a particular way, you will have to use the -function @code{struct_elements} and sort the list yourself. - -The @var{key} variable may also be omitted. If it is, the brackets are -also optional. This is useful for cycling through the values of all the -structure elements when the names of the elements do not need to be -known. - -@node The break Statement, The continue Statement, The for Statement, Statements -@section The @code{break} Statement -@cindex @code{break} statement - -The @code{break} statement jumps out of the innermost @code{for} or -@code{while} loop that encloses it. The @code{break} statement may only -be used within the body of a loop. The following example finds the -smallest divisor of a given integer, and also identifies prime numbers: - -@example -@group -num = 103; -div = 2; -while (div*div <= num) - if (rem (num, div) == 0) - break; - endif - div++; -endwhile -if (rem (num, div) == 0) - printf ("Smallest divisor of %d is %d\n", num, div) -else - printf ("%d is prime\n", num); -endif -@end group -@end example - -When the remainder is zero in the first @code{while} statement, Octave -immediately @dfn{breaks out} of the loop. This means that Octave -proceeds immediately to the statement following the loop and continues -processing. (This is very different from the @code{exit} statement -which stops the entire Octave program.) - -Here is another program equivalent to the previous one. It illustrates -how the @var{condition} of a @code{while} statement could just as well -be replaced with a @code{break} inside an @code{if}: - -@example -@group -num = 103; -div = 2; -while (1) - if (rem (num, div) == 0) - printf ("Smallest divisor of %d is %d\n", num, div); - break; - endif - div++; - if (div*div > num) - printf ("%d is prime\n", num); - break; - endif -endwhile -@end group -@end example - -@node The continue Statement, The unwind_protect Statement, The break Statement, Statements -@section The @code{continue} Statement -@cindex @code{continue} statement - -The @code{continue} statement, like @code{break}, is used only inside -@code{for} or @code{while} loops. It skips over the rest of the loop -body, causing the next cycle around the loop to begin immediately. -Contrast this with @code{break}, which jumps out of the loop altogether. -Here is an example: - -@example -@group -# print elements of a vector of random -# integers that are even. - -# first, create a row vector of 10 random -# integers with values between 0 and 100: - -vec = round (rand (1, 10) * 100); - -# print what we're interested in: - -for x = vec - if (rem (x, 2) != 0) - continue; - endif - printf ("%d\n", x); -endfor -@end group -@end example - -If one of the elements of @var{vec} is an odd number, this example skips -the print statement for that element, and continues back to the first -statement in the loop. - -This is not a practical example of the @code{continue} statement, but it -should give you a clear understanding of how it works. Normally, one -would probably write the loop like this: - -@example -@group -for x = vec - if (rem (x, 2) == 0) - printf ("%d\n", x); - endif -endfor -@end group -@end example - -@node The unwind_protect Statement, The try Statement, The continue Statement, Statements -@section The @code{unwind_protect} Statement -@cindex @code{unwind_protect} statement -@cindex @code{unwind_protect_cleanup} -@cindex @code{end_unwind_protect} - -Octave supports a limited form of exception handling modelled after the -unwind-protect form of Lisp. - -The general form of an @code{unwind_protect} block looks like this: - -@example -@group -unwind_protect - @var{body} -unwind_protect_cleanup - @var{cleanup} -end_unwind_protect -@end group -@end example - -@noindent -Where @var{body} and @var{cleanup} are both optional and may contain any -Octave expressions or commands. The statements in @var{cleanup} are -guaranteed to be executed regardless of how control exits @var{body}. - -This is useful to protect temporary changes to global variables from -possible errors. For example, the following code will always restore -the original value of the built-in variable @code{do_fortran_indexing} -even if an error occurs while performing the indexing operation. - -@example -@group -save_do_fortran_indexing = do_fortran_indexing; -unwind_protect - do_fortran_indexing = 1; - elt = a (idx) -unwind_protect_cleanup - do_fortran_indexing = save_do_fortran_indexing; -end_unwind_protect -@end group -@end example - -Without @code{unwind_protect}, the value of @var{do_fortran_indexing} -would not be restored if an error occurs while performing the indexing -operation because evaluation would stop at the point of the error and -the statement to restore the value would not be executed. - -@node The try Statement, Continuation Lines, The unwind_protect Statement, Statements -@section The @code{try} Statement -@cindex @code{try} statement -@cindex @code{catch} -@cindex @code{end_try_catch} - -In addition to unwind_protect, Octave supports another limited form of -exception handling. - -The general form of a @code{try} block looks like this: - -@example -@group -try - @var{body} -catch - @var{cleanup} -end_try_catch -@end group -@end example - -Where @var{body} and @var{cleanup} are both optional and may contain any -Octave expressions or commands. The statements in @var{cleanup} are -only executed if an error occurs in @var{body}. - -No warnings or error messages are printed while @var{body} is -executing. If an error does occur during the execution of @var{body}, -@var{cleanup} can access the text of the message that would have been -printed in the builtin constant @code{__error_text__}. This is the same -as @code{eval (@var{try}, @var{catch})} (which may now also use -@code{__error_text__}) but it is more efficient since the commands do -not need to be parsed each time the @var{try} and @var{catch} statements -are evaluated. @xref{Error Handling}, for more information about the -@code{__error_text__} variable. - -Octave's @var{try} block is a very limited variation on the Lisp -condition-case form (limited because it cannot handle different classes -of errors separately). Perhaps at some point Octave can have some sort -of classification of errors and try-catch can be improved to be as -powerful as condition-case in Lisp. - -@cindex continuation lines -@cindex @code{...} continuation marker -@cindex @code{\} continuation marker - -@node Continuation Lines, , The try Statement, Statements -@section Continuation Lines - -In the Octave language, most statements end with a newline character and -you must tell Octave to ignore the newline character in order to -continue a statement from one line to the next. Lines that end with the -characters @code{...} or @code{\} are joined with the following line -before they are divided into tokens by Octave's parser. For example, -the lines - -@example -@group -x = long_variable_name ... - + longer_variable_name \ - - 42 -@end group -@end example - -@noindent -form a single statement. The backslash character on the second line -above is interpreted a continuation character, @emph{not} as a division -operator. - -For continuation lines that do not occur inside string constants, -whitespace and comments may appear between the continuation marker and -the newline character. For example, the statement - -@example -@group -x = long_variable_name ... # comment one - + longer_variable_name \ # comment two - - 42 # last comment -@end group -@end example - -@noindent -is equivalent to the one shown above. Inside string constants, the -continuation marker must appear at the end of the line just before the -newline character. - -Input that occurs inside parentheses can be continued to the next line -without having to use a continuation marker. For example, it is -possible to write statements like - -@example -@group -if (fine_dining_destination == on_a_boat - || fine_dining_destination == on_a_train) - suess (i, will, not, eat, them, sam, i, am, i, - will, not, eat, green, eggs, and, ham); -endif -@end group -@end example - -@noindent -without having to add to the clutter with continuation markers. diff --git a/doc/interpreter/stmt.txi b/doc/interpreter/stmt.txi new file mode 100644 --- /dev/null +++ b/doc/interpreter/stmt.txi @@ -0,0 +1,802 @@ +@c Copyright (C) 1996, 1997 John W. Eaton +@c This is part of the Octave manual. +@c For copying conditions, see the file gpl.texi. + +@node Statements, Functions and Scripts, Evaluation, Top +@chapter Statements +@cindex statements + +Statements may be a simple constant expression or a complicated list of +nested loops and conditional statements. + +@dfn{Control statements} such as @code{if}, @code{while}, and so on +control the flow of execution in Octave programs. All the control +statements start with special keywords such as @code{if} and +@code{while}, to distinguish them from simple expressions. +Many control statements contain other statements; for example, the +@code{if} statement contains another statement which may or may not be +executed. + +@cindex @code{end} statement +Each control statement has a corresponding @dfn{end} statement that +marks the end of the end of the control statement. For example, the +keyword @code{endif} marks the end of an @code{if} statement, and +@code{endwhile} marks the end of a @code{while} statement. You can use +the keyword @code{end} anywhere a more specific end keyword is expected, +but using the more specific keywords is preferred because if you use +them, Octave is able to provide better diagnostics for mismatched or +missing end tokens. + +The list of statements contained between keywords like @code{if} or +@code{while} and the corresponding end statement is called the +@dfn{body} of a control statement. + +@menu +* The if Statement:: +* The switch Statement:: +* The while Statement:: +* The for Statement:: +* The break Statement:: +* The continue Statement:: +* The unwind_protect Statement:: +* The try Statement:: +* Continuation Lines:: +@end menu + +@node The if Statement, The switch Statement, Statements, Statements +@section The @code{if} Statement +@cindex @code{if} statement +@cindex @code{else} statement +@cindex @code{elseif} statement +@cindex @code{endif} statement + +The @code{if} statement is Octave's decision-making statement. There +are three basic forms of an @code{if} statement. In its simplest form, +it looks like this: + +@example +@group +if (@var{condition}) + @var{then-body} +endif +@end group +@end example + +@noindent +@var{condition} is an expression that controls what the rest of the +statement will do. The @var{then-body} is executed only if +@var{condition} is true. + +The condition in an @code{if} statement is considered true if its value +is non-zero, and false if its value is zero. If the value of the +conditional expression in an @code{if} statement is a vector or a +matrix, it is considered true only if @emph{all} of the elements are +non-zero. + +The second form of an if statement looks like this: + +@example +@group +if (@var{condition}) + @var{then-body} +else + @var{else-body} +endif +@end group +@end example + +@noindent +If @var{condition} is true, @var{then-body} is executed; otherwise, +@var{else-body} is executed. + +Here is an example: + +@example +@group +if (rem (x, 2) == 0) + printf ("x is even\n"); +else + printf ("x is odd\n"); +endif +@end group +@end example + +In this example, if the expression @code{rem (x, 2) == 0} is true (that +is, the value of @code{x} is divisible by 2), then the first +@code{printf} statement is evaluated, otherwise the second @code{printf} +statement is evaluated. + +The third and most general form of the @code{if} statement allows +multiple decisions to be combined in a single statement. It looks like +this: + +@example +@group +if (@var{condition}) + @var{then-body} +elseif (@var{condition}) + @var{elseif-body} +else + @var{else-body} +endif +@end group +@end example + +@noindent +Any number of @code{elseif} clauses may appear. Each condition is +tested in turn, and if one is found to be true, its corresponding +@var{body} is executed. If none of the conditions are true and the +@code{else} clause is present, its body is executed. Only one +@code{else} clause may appear, and it must be the last part of the +statement. + +In the following example, if the first condition is true (that is, the +value of @code{x} is divisible by 2), then the first @code{printf} +statement is executed. If it is false, then the second condition is +tested, and if it is true (that is, the value of @code{x} is divisible +by 3), then the second @code{printf} statement is executed. Otherwise, +the third @code{printf} statement is performed. + +@example +@group +if (rem (x, 2) == 0) + printf ("x is even\n"); +elseif (rem (x, 3) == 0) + printf ("x is odd and divisible by 3\n"); +else + printf ("x is odd\n"); +endif +@end group +@end example + +Note that the @code{elseif} keyword must not be spelled @code{else if}, +as is allowed in Fortran. If it is, the space between the @code{else} +and @code{if} will tell Octave to treat this as a new @code{if} +statement within another @code{if} statement's @code{else} clause. For +example, if you write + +@example +@group +if (@var{c1}) + @var{body-1} +else if (@var{c2}) + @var{body-2} +endif +@end group +@end example + +@noindent +Octave will expect additional input to complete the first @code{if} +statement. If you are using Octave interactively, it will continue to +prompt you for additional input. If Octave is reading this input from a +file, it may complain about missing or mismatched @code{end} statements, +or, if you have not used the more specific @code{end} statements +(@code{endif}, @code{endfor}, etc.), it may simply produce incorrect +results, without producing any warning messages. + +It is much easier to see the error if we rewrite the statements above +like this, + +@example +@group +if (@var{c1}) + @var{body-1} +else + if (@var{c2}) + @var{body-2} + endif +@end group +@end example + +@noindent +using the indentation to show how Octave groups the statements. +@xref{Functions and Scripts}. + +@defvr {Built-in Variable} warn_assign_as_truth_value +If the value of @code{warn_assign_as_truth_value} is nonzero, a +warning is issued for statements like + +@example +if (s = t) + ... +@end example + +@noindent +since such statements are not common, and it is likely that the intent +was to write + +@example +if (s == t) + ... +@end example + +@noindent +instead. + +There are times when it is useful to write code that contains +assignments within the condition of a @code{while} or @code{if} +statement. For example, statements like + +@example +while (c = getc()) + ... +@end example + +@noindent +are common in C programming. + +It is possible to avoid all warnings about such statements by setting +@code{warn_assign_as_truth_value} to 0, but that may also +let real errors like + +@example +if (x = 1) # intended to test (x == 1)! + ... +@end example + +@noindent +slip by. + +In such cases, it is possible suppress errors for specific statements by +writing them with an extra set of parentheses. For example, writing the +previous example as + +@example +while ((c = getc())) + ... +@end example + +@noindent +will prevent the warning from being printed for this statement, while +allowing Octave to warn about other assignments used in conditional +contexts. + +The default value of @code{warn_assign_as_truth_value} is 1. +@end defvr + +@node The switch Statement, The while Statement, The if Statement, Statements +@section The @code{switch} Statement +@cindex @code{switch} statement +@cindex @code{case} statement +@cindex @code{otherwise} statement +@cindex @code{endswitch} statement + +The @code{switch} statement was introduced in Octave 2.0.5. It should +be considered experimental, and details of the implementation may change +slightly in future versions of Octave. If you have comments or would +like to share your experiences in trying to use this new command in real +programs, please send them to +@email{octave-maintainers@@bevo.che.wisc.edu}. (But if you think you've +found a bug, please report it to @email{bug-octave@@bevo.che.wisc.edu}. + +The general form of the @code{switch} statement is + +@example +@group +switch @var{expression} + case @var{label} + @var{command_list} + case @var{label} + @var{command_list} + @dots{} + + otherwise + @var{command_list} +endswitch +@end group +@end example + +@itemize @bullet +@item +The identifiers @code{switch}, @code{case}, @code{otherwise}, and +@code{endswitch} are now keywords. + +@item +The @var{label} may be any expression. + +@item +Duplicate @var{label} values are not detected. The @var{command_list} +corresponding to the first match will be executed. + +@item +You must have at least one @code{case @var{label} @var{command_list}} +clause. + +@item +The @code{otherwise @var{command_list}} clause is optional. + +@item +As with all other specific @code{end} keywords, @code{endswitch} may be +replaced by @code{end}, but you can get better diagnostics if you use +the specific forms. + +@item +Cases are exclusive, so they don't `fall through' as do the cases +in the switch statement of the C language. + +@item +The @var{command_list} elements are not optional. Making the list +optional would have meant requiring a separator between the label and +the command list. Otherwise, things like + +@example +@group +switch (foo) + case (1) -2 + @dots{} +@end group +@end example + +@noindent +would produce surprising results, as would + +@example +@group +switch (foo) + case (1) + case (2) + doit (); + @dots{} +@end group +@end example + +@noindent +particularly for C programmers. + +@item +The implementation is simple-minded and currently offers no real +performance improvement over an equivalent @code{if} block, even if all +the labels are integer constants. Perhaps a future variation on this +could detect all constant integer labels and improve performance by +using a jump table. +@end itemize + +@defvr {Built-in Variable} warn_variable_switch_label +If the value of this variable is nonzero, Octave will print a warning if +a switch label is not a constant or constant expression +@end defvr + +@node The while Statement, The for Statement, The switch Statement, Statements +@section The @code{while} Statement +@cindex @code{while} statement +@cindex @code{endwhile} statement +@cindex loop +@cindex body of a loop + +In programming, a @dfn{loop} means a part of a program that is (or at least can +be) executed two or more times in succession. + +The @code{while} statement is the simplest looping statement in Octave. +It repeatedly executes a statement as long as a condition is true. As +with the condition in an @code{if} statement, the condition in a +@code{while} statement is considered true if its value is non-zero, and +false if its value is zero. If the value of the conditional expression +in a @code{while} statement is a vector or a matrix, it is considered +true only if @emph{all} of the elements are non-zero. + +Octave's @code{while} statement looks like this: + +@example +@group +while (@var{condition}) + @var{body} +endwhile +@end group +@end example + +@noindent +Here @var{body} is a statement or list of statements that we call the +@dfn{body} of the loop, and @var{condition} is an expression that +controls how long the loop keeps running. + +The first thing the @code{while} statement does is test @var{condition}. +If @var{condition} is true, it executes the statement @var{body}. After +@var{body} has been executed, @var{condition} is tested again, and if it +is still true, @var{body} is executed again. This process repeats until +@var{condition} is no longer true. If @var{condition} is initially +false, the body of the loop is never executed. + +This example creates a variable @code{fib} that contains the first ten +elements of the Fibonacci sequence. + +@example +@group +fib = ones (1, 10); +i = 3; +while (i <= 10) + fib (i) = fib (i-1) + fib (i-2); + i++; +endwhile +@end group +@end example + +@noindent +Here the body of the loop contains two statements. + +The loop works like this: first, the value of @code{i} is set to 3. +Then, the @code{while} tests whether @code{i} is less than or equal to +10. This is the case when @code{i} equals 3, so the value of the +@code{i}-th element of @code{fib} is set to the sum of the previous two +values in the sequence. Then the @code{i++} increments the value of +@code{i} and the loop repeats. The loop terminates when @code{i} +reaches 11. + +A newline is not required between the condition and the +body; but using one makes the program clearer unless the body is very +simple. + +@xref{The if Statement} for a description of the variable +@code{warn_assign_as_truth_value}. + +@node The for Statement, The break Statement, The while Statement, Statements +@section The @code{for} Statement +@cindex @code{for} statement +@cindex @code{endfor} statement + +The @code{for} statement makes it more convenient to count iterations of a +loop. The general form of the @code{for} statement looks like this: + +@example +@group +for @var{var} = @var{expression} + @var{body} +endfor +@end group +@end example + +@noindent +where @var{body} stands for any statement or list of statements, +@var{expression} is any valid expression, and @var{var} may take several +forms. Usually it is a simple variable name or an indexed variable. If +the value of @var{expression} is a structure, @var{var} may also be a +list. @xref{Looping Over Structure Elements}, below. + +The assignment expression in the @code{for} statement works a bit +differently than Octave's normal assignment statement. Instead of +assigning the complete result of the expression, it assigns each column +of the expression to @var{var} in turn. If @var{expression} is a range, +a row vector, or a scalar, the value of @var{var} will be a scalar each +time the loop body is executed. If @var{var} is a column vector or a +matrix, @var{var} will be a column vector each time the loop body is +executed. + +The following example shows another way to create a vector containing +the first ten elements of the Fibonacci sequence, this time using the +@code{for} statement: + +@example +@group +fib = ones (1, 10); +for i = 3:10 + fib (i) = fib (i-1) + fib (i-2); +endfor +@end group +@end example + +@noindent +This code works by first evaluating the expression @code{3:10}, to +produce a range of values from 3 to 10 inclusive. Then the variable +@code{i} is assigned the first element of the range and the body of the +loop is executed once. When the end of the loop body is reached, the +next value in the range is assigned to the variable @code{i}, and the +loop body is executed again. This process continues until there are no +more elements to assign. + +Although it is possible to rewrite all @code{for} loops as @code{while} +loops, the Octave language has both statements because often a +@code{for} loop is both less work to type and more natural to think of. +Counting the number of iterations is very common in loops and it can be +easier to think of this counting as part of looping rather than as +something to do inside the loop. + +@menu +* Looping Over Structure Elements:: +@end menu + +@node Looping Over Structure Elements, , The for Statement, The for Statement +@subsection Looping Over Structure Elements +@cindex structure elements, looping over +@cindex looping over structure elements + +A special form of the @code{for} statement allows you to loop over all +the elements of a structure: + +@example +@group +for [ @var{val}, @var{key} ] = @var{expression} + @var{body} +endfor +@end group +@end example + +@noindent +In this form of the @code{for} statement, the value of @var{expression} +must be a structure. If it is, @var{key} and @var{val} are set to the +name of the element and the corresponding value in turn, until there are +no more elements. For example, + +@example +@group +x.a = 1 +x.b = [1, 2; 3, 4] +x.c = "string" +for [val, key] = x + key + val +endfor + + @print{} key = a + @print{} val = 1 + @print{} key = b + @print{} val = + @print{} + @print{} 1 2 + @print{} 3 4 + @print{} + @print{} key = c + @print{} val = string +@end group +@end example + +The elements are not accessed in any particular order. If you need to +cycle through the list in a particular way, you will have to use the +function @code{struct_elements} and sort the list yourself. + +The @var{key} variable may also be omitted. If it is, the brackets are +also optional. This is useful for cycling through the values of all the +structure elements when the names of the elements do not need to be +known. + +@node The break Statement, The continue Statement, The for Statement, Statements +@section The @code{break} Statement +@cindex @code{break} statement + +The @code{break} statement jumps out of the innermost @code{for} or +@code{while} loop that encloses it. The @code{break} statement may only +be used within the body of a loop. The following example finds the +smallest divisor of a given integer, and also identifies prime numbers: + +@example +@group +num = 103; +div = 2; +while (div*div <= num) + if (rem (num, div) == 0) + break; + endif + div++; +endwhile +if (rem (num, div) == 0) + printf ("Smallest divisor of %d is %d\n", num, div) +else + printf ("%d is prime\n", num); +endif +@end group +@end example + +When the remainder is zero in the first @code{while} statement, Octave +immediately @dfn{breaks out} of the loop. This means that Octave +proceeds immediately to the statement following the loop and continues +processing. (This is very different from the @code{exit} statement +which stops the entire Octave program.) + +Here is another program equivalent to the previous one. It illustrates +how the @var{condition} of a @code{while} statement could just as well +be replaced with a @code{break} inside an @code{if}: + +@example +@group +num = 103; +div = 2; +while (1) + if (rem (num, div) == 0) + printf ("Smallest divisor of %d is %d\n", num, div); + break; + endif + div++; + if (div*div > num) + printf ("%d is prime\n", num); + break; + endif +endwhile +@end group +@end example + +@node The continue Statement, The unwind_protect Statement, The break Statement, Statements +@section The @code{continue} Statement +@cindex @code{continue} statement + +The @code{continue} statement, like @code{break}, is used only inside +@code{for} or @code{while} loops. It skips over the rest of the loop +body, causing the next cycle around the loop to begin immediately. +Contrast this with @code{break}, which jumps out of the loop altogether. +Here is an example: + +@example +@group +# print elements of a vector of random +# integers that are even. + +# first, create a row vector of 10 random +# integers with values between 0 and 100: + +vec = round (rand (1, 10) * 100); + +# print what we're interested in: + +for x = vec + if (rem (x, 2) != 0) + continue; + endif + printf ("%d\n", x); +endfor +@end group +@end example + +If one of the elements of @var{vec} is an odd number, this example skips +the print statement for that element, and continues back to the first +statement in the loop. + +This is not a practical example of the @code{continue} statement, but it +should give you a clear understanding of how it works. Normally, one +would probably write the loop like this: + +@example +@group +for x = vec + if (rem (x, 2) == 0) + printf ("%d\n", x); + endif +endfor +@end group +@end example + +@node The unwind_protect Statement, The try Statement, The continue Statement, Statements +@section The @code{unwind_protect} Statement +@cindex @code{unwind_protect} statement +@cindex @code{unwind_protect_cleanup} +@cindex @code{end_unwind_protect} + +Octave supports a limited form of exception handling modelled after the +unwind-protect form of Lisp. + +The general form of an @code{unwind_protect} block looks like this: + +@example +@group +unwind_protect + @var{body} +unwind_protect_cleanup + @var{cleanup} +end_unwind_protect +@end group +@end example + +@noindent +Where @var{body} and @var{cleanup} are both optional and may contain any +Octave expressions or commands. The statements in @var{cleanup} are +guaranteed to be executed regardless of how control exits @var{body}. + +This is useful to protect temporary changes to global variables from +possible errors. For example, the following code will always restore +the original value of the built-in variable @code{do_fortran_indexing} +even if an error occurs while performing the indexing operation. + +@example +@group +save_do_fortran_indexing = do_fortran_indexing; +unwind_protect + do_fortran_indexing = 1; + elt = a (idx) +unwind_protect_cleanup + do_fortran_indexing = save_do_fortran_indexing; +end_unwind_protect +@end group +@end example + +Without @code{unwind_protect}, the value of @var{do_fortran_indexing} +would not be restored if an error occurs while performing the indexing +operation because evaluation would stop at the point of the error and +the statement to restore the value would not be executed. + +@node The try Statement, Continuation Lines, The unwind_protect Statement, Statements +@section The @code{try} Statement +@cindex @code{try} statement +@cindex @code{catch} +@cindex @code{end_try_catch} + +In addition to unwind_protect, Octave supports another limited form of +exception handling. + +The general form of a @code{try} block looks like this: + +@example +@group +try + @var{body} +catch + @var{cleanup} +end_try_catch +@end group +@end example + +Where @var{body} and @var{cleanup} are both optional and may contain any +Octave expressions or commands. The statements in @var{cleanup} are +only executed if an error occurs in @var{body}. + +No warnings or error messages are printed while @var{body} is +executing. If an error does occur during the execution of @var{body}, +@var{cleanup} can access the text of the message that would have been +printed in the builtin constant @code{__error_text__}. This is the same +as @code{eval (@var{try}, @var{catch})} (which may now also use +@code{__error_text__}) but it is more efficient since the commands do +not need to be parsed each time the @var{try} and @var{catch} statements +are evaluated. @xref{Error Handling}, for more information about the +@code{__error_text__} variable. + +Octave's @var{try} block is a very limited variation on the Lisp +condition-case form (limited because it cannot handle different classes +of errors separately). Perhaps at some point Octave can have some sort +of classification of errors and try-catch can be improved to be as +powerful as condition-case in Lisp. + +@cindex continuation lines +@cindex @code{...} continuation marker +@cindex @code{\} continuation marker + +@node Continuation Lines, , The try Statement, Statements +@section Continuation Lines + +In the Octave language, most statements end with a newline character and +you must tell Octave to ignore the newline character in order to +continue a statement from one line to the next. Lines that end with the +characters @code{...} or @code{\} are joined with the following line +before they are divided into tokens by Octave's parser. For example, +the lines + +@example +@group +x = long_variable_name ... + + longer_variable_name \ + - 42 +@end group +@end example + +@noindent +form a single statement. The backslash character on the second line +above is interpreted a continuation character, @emph{not} as a division +operator. + +For continuation lines that do not occur inside string constants, +whitespace and comments may appear between the continuation marker and +the newline character. For example, the statement + +@example +@group +x = long_variable_name ... # comment one + + longer_variable_name \ # comment two + - 42 # last comment +@end group +@end example + +@noindent +is equivalent to the one shown above. Inside string constants, the +continuation marker must appear at the end of the line just before the +newline character. + +Input that occurs inside parentheses can be continued to the next line +without having to use a continuation marker. For example, it is +possible to write statements like + +@example +@group +if (fine_dining_destination == on_a_boat + || fine_dining_destination == on_a_train) + suess (i, will, not, eat, them, sam, i, am, i, + will, not, eat, green, eggs, and, ham); +endif +@end group +@end example + +@noindent +without having to add to the clutter with continuation markers. diff --git a/doc/interpreter/strings.texi b/doc/interpreter/strings.texi deleted file mode 100644 --- a/doc/interpreter/strings.texi +++ /dev/null @@ -1,484 +0,0 @@ -@c Copyright (C) 1996, 1997 John W. Eaton -@c This is part of the Octave manual. -@c For copying conditions, see the file gpl.texi. - -@node Strings, Data Structures, Numeric Data Types, Top -@chapter Strings -@cindex strings -@cindex character strings -@opindex " -@opindex ' - -A @dfn{string constant} consists of a sequence of characters enclosed in -either double-quote or single-quote marks. For example, both of the -following expressions - -@example -@group -"parrot" -'parrot' -@end group -@end example - -@noindent -represent the string whose contents are @samp{parrot}. Strings in -Octave can be of any length. - -Since the single-quote mark is also used for the transpose operator -(@pxref{Arithmetic Ops}) but double-quote marks have no other purpose in -Octave, it is best to use double-quote marks to denote strings. - -@c XXX FIXME XXX -- this is probably pretty confusing. - -@cindex escape sequence notation -Some characters cannot be included literally in a string constant. You -represent them instead with @dfn{escape sequences}, which are character -sequences beginning with a backslash (@samp{\}). - -One use of an escape sequence is to include a double-quote -(single-quote) character in a string constant that has been defined -using double-quote (single-quote) marks. Since a plain double-quote -would end the string, you must use @samp{\"} to represent a single -double-quote character as a part of the string. The backslash character -itself is another character that cannot be included normally. You must -write @samp{\\} to put one backslash in the string. Thus, the string -whose contents are the two characters @samp{"\} may be written -@code{"\"\\"} or @code{'"\\'}. Similarly, the string whose contents are -the two characters @samp{'\} may be written @code{'\'\\'} or @code{"'\\"}. - -Another use of backslash is to represent unprintable characters -such as newline. While there is nothing to stop you from writing most -of these characters directly in a string constant, they may look ugly. - -Here is a table of all the escape sequences used in Octave. They are -the same as those used in the C programming language. - -@table @code -@item \\ -Represents a literal backslash, @samp{\}. - -@item \" -Represents a literal double-quote character, @samp{"}. - -@item \' -Represents a literal single-quote character, @samp{'}. - -@item \a -Represents the ``alert'' character, control-g, ASCII code 7. - -@item \b -Represents a backspace, control-h, ASCII code 8. - -@item \f -Represents a formfeed, control-l, ASCII code 12. - -@item \n -Represents a newline, control-j, ASCII code 10. - -@item \r -Represents a carriage return, control-m, ASCII code 13. - -@item \t -Represents a horizontal tab, control-i, ASCII code 9. - -@item \v -Represents a vertical tab, control-k, ASCII code 11. - -@c We don't do octal or hex this way yet. -@c -@c @item \@var{nnn} -@c Represents the octal value @var{nnn}, where @var{nnn} are one to three -@c digits between 0 and 7. For example, the code for the ASCII ESC -@c (escape) character is @samp{\033}.@refill -@c -@c @item \x@var{hh}@dots{} -@c Represents the hexadecimal value @var{hh}, where @var{hh} are hexadecimal -@c digits (@samp{0} through @samp{9} and either @samp{A} through @samp{F} or -@c @samp{a} through @samp{f}). Like the same construct in @sc{ansi} C, -@c the escape -@c sequence continues until the first non-hexadecimal digit is seen. However, -@c using more than two hexadecimal digits produces undefined results. (The -@c @samp{\x} escape sequence is not allowed in @sc{posix} @code{awk}.)@refill -@end table - -Strings may be concatenated using the notation for defining matrices. -For example, the expression - -@example -[ "foo" , "bar" , "baz" ] -@end example - -@noindent -produces the string whose contents are @samp{foobarbaz}. @xref{Numeric -Data Types} for more information about creating matrices. - -@menu -* Creating Strings:: -* Searching and Replacing:: -* String Conversions:: -* Character Class Functions:: -@end menu - -@node Creating Strings, Searching and Replacing, Strings, Strings -@section Creating Strings - -@deftypefn {Function File} {} blanks (@var{n}) -Return a string of @var{n} blanks. -@end deftypefn - -@deftypefn {Function File} {} int2str (@var{n}) -@deftypefnx {Function File} {} num2str (@var{x}) -Convert a number to a string. These functions are not very flexible, -but are provided for compatibility with @sc{Matlab}. For better control -over the results, use @code{sprintf} (@pxref{Formatted Output}). -@end deftypefn - -@deftypefn {Built-in Function} {} setstr (@var{x}) -Convert a matrix to a string. Each element of the matrix is converted -to the corresponding ASCII -character. For example, - -@example -@group -setstr ([97, 98, 99]) - @result{} "abc" -@end group -@end example -@end deftypefn - -@deftypefn {Function File} {} strcat (@var{s1}, @var{s2}, @dots{}) -Return a string containing all the arguments concatenated. For example, - -@example -@group -s = [ "ab"; "cde" ]; -strcat (s, s, s) - @result{} "ab ab ab " - "cdecdecde" -@end group -@end example -@end deftypefn - -@defvr {Built-in Variable} string_fill_char -The value of this variable is used to pad all strings in a string matrix -to the same length. It should be a single character. The default value -is @code{" "} (a single space). For example, - -@example -@group -string_fill_char = "X"; -[ "these"; "are"; "strings" ] - @result{} "theseXX" - "areXXXX" - "strings" -@end group -@end example -@end defvr - -@deftypefn {Function File} {} str2mat (@var{s_1}, @dots{}, @var{s_n}) -Return a matrix containing the strings @var{s_1}, @dots{}, @var{s_n} as -its rows. Each string is padded with blanks in order to form a valid -matrix. - -@strong{Note:} -This function is modelled after @sc{Matlab}. In Octave, you can create -a matrix of strings by @code{[@var{s_1}; @dots{}; @var{s_n}]} even if -the strings are not all the same length. -@end deftypefn - -@deftypefn {Built-in Function} {} isstr (@var{a}) -Return 1 if @var{a} is a string. Otherwise, return 0. -@end deftypefn - -@node Searching and Replacing, String Conversions, Creating Strings, Strings -@section Searching and Replacing - -@deftypefn {Function File} {} deblank (@var{s}) -Removes the trailing blanks from the string @var{s}. -@end deftypefn - -@deftypefn {Function File} {} findstr (@var{s}, @var{t}, @var{overlap}) -Return the vector of all positions in the longer of the two strings -@var{s} and @var{t} where an occurrence of the shorter of the two starts. -If the optional argument @var{overlap} is nonzero, the returned vector -can include overlapping positions (this is the default). For example, - -@example -findstr ("ababab", "a") - @result{} [ 1, 3, 5 ] -findstr ("abababa", "aba", 0) - @result{} [ 1, 5 ] -@end example -@end deftypefn - -@deftypefn {Function File} {} index (@var{s}, @var{t}) -Return the position of the first occurrence of the string @var{t} in the -string @var{s}, or 0 if no occurrence is found. For example, - -@example -index ("Teststring", "t") - @result{} 4 -@end example - -@strong{Note:} This function does not work for arrays of strings. -@end deftypefn - -@deftypefn {Function File} {} rindex (@var{s}, @var{t}) -Return the position of the last occurrence of the string @var{t} in the -string @var{s}, or 0 if no occurrence is found. For example, - -@example -rindex ("Teststring", "t") - @result{} 6 -@end example - -@strong{Note:} This function does not work for arrays of strings. -@end deftypefn - -@deftypefn {Function File} {} split (@var{s}, @var{t}) -Divides the string @var{s} into pieces separated by @var{t}, returning -the result in a string array (padded with blanks to form a valid -matrix). For example, - -@example -split ("Test string", "t") - @result{} "Tes " - " s " - "ring" -@end example -@end deftypefn - -@deftypefn {Function File} {} strcmp (@var{s1}, @var{s2}) -Compares two strings, returning 1 if they are the same, and 0 otherwise. - -@strong{Note:} For compatibility with @sc{Matlab}, Octave's strcmp -function returns 1 if the strings are equal, and 0 otherwise. This is -just the opposite of the corresponding C library function. -@end deftypefn - -@deftypefn {Function File} {} strrep (@var{s}, @var{x}, @var{y}) -Replaces all occurrences of the substring @var{x} of the string @var{s} -with the string @var{y}. For example, - -@example -strrep ("This is a test string", "is", "&%$") - @result{} "Th&%$ &%$ a test string" -@end example -@end deftypefn - -@deftypefn {Function File} {} substr (@var{s}, @var{beg}, @var{len}) -Return the substring of @var{s} which starts at character number -@var{beg} and is @var{len} characters long. For example, - -@example -substr ("This is a test string", 6, 9) - @result{} "is a test" -@end example - -@quotation -@strong{Note:} -This function is patterned after AWK. You can get the same result by -@code{@var{s} (@var{beg} : (@var{beg} + @var{len} - 1))}. -@end quotation -@end deftypefn - -@node String Conversions, Character Class Functions, Searching and Replacing, Strings -@section String Conversions - -@deftypefn {Function File} {} bin2dec (@var{s}) -Return a decimal number corresponding to the binary number -represented as a string of zeros and ones. For example, - -@example -bin2dec ("1110") - @result{} 14 -@end example -@end deftypefn - -@deftypefn {Function File} {} dec2bin (@var{n}) -Return a binary number corresponding the nonnegative decimal number -@var{n}, as a string of ones and zeros. For example, - -@example -dec2bin (14) - @result{} "1110" -@end example -@end deftypefn - -@deftypefn {Function File} {} dec2hex (@var{n}) -Return the hexadecimal number corresponding to the nonnegative decimal -number @var{n}, as a string. For example, - -@example -dec2hex (2748) - @result{} "abc" -@end example -@end deftypefn - -@deftypefn {Function File} {} hex2dec (@var{s}) -Return the decimal number corresponding to the hexadecimal number stored -in the string @var{s}. For example, - -@example -hex2dec ("12B") - @result{} 299 -hex2dec ("12b") - @result{} 299 -@end example -@end deftypefn - -@deftypefn {Function File} {} str2num (@var{s}) -Convert the string @var{s} to a number. -@end deftypefn - -@deftypefn {Function File} {} toascii (@var{s}) -Return ASCII representation of @var{s} in a matrix. For example, - -@example -@group -toascii ("ASCII") - @result{} [ 65, 83, 67, 73, 73 ] -@end group - -@end example -@end deftypefn - -@deftypefn {Function File} {} tolower (@var{s}) -Return a copy of the string @var{s}, with each upper-case character -replaced by the corresponding lower-case one; nonalphabetic characters -are left unchanged. For example, - -@example -tolower ("MiXeD cAsE 123") - @result{} "mixed case 123" -@end example -@end deftypefn - -@deftypefn {Function File} {} toupper (@var{s}) -Return a copy of the string @var{s}, with each lower-case character -replaced by the corresponding upper-case one; nonalphabetic characters -are left unchanged. For example, - -@example -@group -toupper ("MiXeD cAsE 123") - @result{} "MIXED CASE 123" -@end group -@end example -@end deftypefn - -@deftypefn {Built-in Function} {} undo_string_escapes (@var{s}) -Converts special characters in strings back to their escaped forms. For -example, the expression - -@example -bell = "\a"; -@end example - -@noindent -assigns the value of the alert character (control-g, ASCII code 7) to -the string variable @code{bell}. If this string is printed, the -system will ring the terminal bell (if it is possible). This is -normally the desired outcome. However, sometimes it is useful to be -able to print the original representation of the string, with the -special characters replaced by their escape sequences. For example, - -@example -octave:13> undo_string_escapes (bell) -ans = \a -@end example - -@noindent -replaces the unprintable alert character with its printable -representation. -@end deftypefn - -@defvr {Built-in Variable} implicit_num_to_str_ok -If the value of @code{implicit_num_to_str_ok} is nonzero, implicit -conversions of numbers to their ASCII character equivalents are -allowed when strings are constructed using a mixture of strings and -numbers in matrix notation. Otherwise, an error message is printed and -control is returned to the top level. The default value is 0. For -example, - -@example -@group -[ "f", 111, 111 ] - @result{} "foo" -@end group -@end example -@end defvr - -@defvr {Built-in Variable} implicit_str_to_num_ok -If the value of @code{implicit_str_to_num_ok} is nonzero, implicit -conversions of strings to their numeric ASCII equivalents are allowed. -Otherwise, an error message is printed and control is returned to the -top level. The default value is 0. -@end defvr - -@node Character Class Functions, , String Conversions, Strings -@section Character Class Functions - -Octave also provides the following character class test functions -patterned after the functions in the standard C library. They all -operate on string arrays and return matrices of zeros and ones. -Elements that are nonzero indicate that the condition was true for the -corresponding character in the string array. For example, - -@example -@group -isalpha ("!Q@@WERT^Y&") - @result{} [ 0, 1, 0, 1, 1, 1, 1, 0, 1, 0 ] -@end group -@end example - -@deftypefn {Mapping Function} {} isalnum (@var{s}) -Return 1 for characters that are letters or digits (@code{isalpha -(@var{a})} or @code{isdigit (@var{})} is true). -@end deftypefn - -@deftypefn {Mapping Function} {} isalpha (@var{s}) -Return true for characters that are letters (@code{isupper (@var{a})} -or @code{islower (@var{})} is true). -@end deftypefn - -@deftypefn {Mapping Function} {} isascii (@var{s}) -Return 1 for characters that are ASCII (in the range 0 to 127 decimal). -@end deftypefn - -@deftypefn {Mapping Function} {} iscntrl (@var{s}) -Return 1 for control characters. -@end deftypefn - -@deftypefn {Mapping Function} {} isdigit (@var{s}) -Return 1 for characters that are decimal digits. -@end deftypefn - -@deftypefn {Mapping Function} {} isgraph (@var{s}) -Return 1 for printable characters (but not the space character). -@end deftypefn - -@deftypefn {Mapping Function} {} islower (@var{s}) -Return 1 for characters that are lower case letters. -@end deftypefn - -@deftypefn {Mapping Function} {} isprint (@var{s}) -Return 1 for printable characters (including the space character). -@end deftypefn - -@deftypefn {Mapping Function} {} ispunct (@var{s}) -Return 1 for punctuation characters. -@end deftypefn - -@deftypefn {Mapping Function} {} isspace (@var{s}) -Return 1 for whitespace characters (space, formfeed, newline, -carriage return, tab, and vertical tab). -@end deftypefn - -@deftypefn {Mapping Function} {} isupper (@var{s}) -Return 1 for upper case letters. -@end deftypefn - -@deftypefn {Mapping Function} {} isxdigit (@var{s}) -Return 1 for characters that are hexadecimal digits. -@end deftypefn diff --git a/doc/interpreter/strings.txi b/doc/interpreter/strings.txi new file mode 100644 --- /dev/null +++ b/doc/interpreter/strings.txi @@ -0,0 +1,484 @@ +@c Copyright (C) 1996, 1997 John W. Eaton +@c This is part of the Octave manual. +@c For copying conditions, see the file gpl.texi. + +@node Strings, Data Structures, Numeric Data Types, Top +@chapter Strings +@cindex strings +@cindex character strings +@opindex " +@opindex ' + +A @dfn{string constant} consists of a sequence of characters enclosed in +either double-quote or single-quote marks. For example, both of the +following expressions + +@example +@group +"parrot" +'parrot' +@end group +@end example + +@noindent +represent the string whose contents are @samp{parrot}. Strings in +Octave can be of any length. + +Since the single-quote mark is also used for the transpose operator +(@pxref{Arithmetic Ops}) but double-quote marks have no other purpose in +Octave, it is best to use double-quote marks to denote strings. + +@c XXX FIXME XXX -- this is probably pretty confusing. + +@cindex escape sequence notation +Some characters cannot be included literally in a string constant. You +represent them instead with @dfn{escape sequences}, which are character +sequences beginning with a backslash (@samp{\}). + +One use of an escape sequence is to include a double-quote +(single-quote) character in a string constant that has been defined +using double-quote (single-quote) marks. Since a plain double-quote +would end the string, you must use @samp{\"} to represent a single +double-quote character as a part of the string. The backslash character +itself is another character that cannot be included normally. You must +write @samp{\\} to put one backslash in the string. Thus, the string +whose contents are the two characters @samp{"\} may be written +@code{"\"\\"} or @code{'"\\'}. Similarly, the string whose contents are +the two characters @samp{'\} may be written @code{'\'\\'} or @code{"'\\"}. + +Another use of backslash is to represent unprintable characters +such as newline. While there is nothing to stop you from writing most +of these characters directly in a string constant, they may look ugly. + +Here is a table of all the escape sequences used in Octave. They are +the same as those used in the C programming language. + +@table @code +@item \\ +Represents a literal backslash, @samp{\}. + +@item \" +Represents a literal double-quote character, @samp{"}. + +@item \' +Represents a literal single-quote character, @samp{'}. + +@item \a +Represents the ``alert'' character, control-g, ASCII code 7. + +@item \b +Represents a backspace, control-h, ASCII code 8. + +@item \f +Represents a formfeed, control-l, ASCII code 12. + +@item \n +Represents a newline, control-j, ASCII code 10. + +@item \r +Represents a carriage return, control-m, ASCII code 13. + +@item \t +Represents a horizontal tab, control-i, ASCII code 9. + +@item \v +Represents a vertical tab, control-k, ASCII code 11. + +@c We don't do octal or hex this way yet. +@c +@c @item \@var{nnn} +@c Represents the octal value @var{nnn}, where @var{nnn} are one to three +@c digits between 0 and 7. For example, the code for the ASCII ESC +@c (escape) character is @samp{\033}.@refill +@c +@c @item \x@var{hh}@dots{} +@c Represents the hexadecimal value @var{hh}, where @var{hh} are hexadecimal +@c digits (@samp{0} through @samp{9} and either @samp{A} through @samp{F} or +@c @samp{a} through @samp{f}). Like the same construct in @sc{ansi} C, +@c the escape +@c sequence continues until the first non-hexadecimal digit is seen. However, +@c using more than two hexadecimal digits produces undefined results. (The +@c @samp{\x} escape sequence is not allowed in @sc{posix} @code{awk}.)@refill +@end table + +Strings may be concatenated using the notation for defining matrices. +For example, the expression + +@example +[ "foo" , "bar" , "baz" ] +@end example + +@noindent +produces the string whose contents are @samp{foobarbaz}. @xref{Numeric +Data Types} for more information about creating matrices. + +@menu +* Creating Strings:: +* Searching and Replacing:: +* String Conversions:: +* Character Class Functions:: +@end menu + +@node Creating Strings, Searching and Replacing, Strings, Strings +@section Creating Strings + +@deftypefn {Function File} {} blanks (@var{n}) +Return a string of @var{n} blanks. +@end deftypefn + +@deftypefn {Function File} {} int2str (@var{n}) +@deftypefnx {Function File} {} num2str (@var{x}) +Convert a number to a string. These functions are not very flexible, +but are provided for compatibility with @sc{Matlab}. For better control +over the results, use @code{sprintf} (@pxref{Formatted Output}). +@end deftypefn + +@deftypefn {Built-in Function} {} setstr (@var{x}) +Convert a matrix to a string. Each element of the matrix is converted +to the corresponding ASCII +character. For example, + +@example +@group +setstr ([97, 98, 99]) + @result{} "abc" +@end group +@end example +@end deftypefn + +@deftypefn {Function File} {} strcat (@var{s1}, @var{s2}, @dots{}) +Return a string containing all the arguments concatenated. For example, + +@example +@group +s = [ "ab"; "cde" ]; +strcat (s, s, s) + @result{} "ab ab ab " + "cdecdecde" +@end group +@end example +@end deftypefn + +@defvr {Built-in Variable} string_fill_char +The value of this variable is used to pad all strings in a string matrix +to the same length. It should be a single character. The default value +is @code{" "} (a single space). For example, + +@example +@group +string_fill_char = "X"; +[ "these"; "are"; "strings" ] + @result{} "theseXX" + "areXXXX" + "strings" +@end group +@end example +@end defvr + +@deftypefn {Function File} {} str2mat (@var{s_1}, @dots{}, @var{s_n}) +Return a matrix containing the strings @var{s_1}, @dots{}, @var{s_n} as +its rows. Each string is padded with blanks in order to form a valid +matrix. + +@strong{Note:} +This function is modelled after @sc{Matlab}. In Octave, you can create +a matrix of strings by @code{[@var{s_1}; @dots{}; @var{s_n}]} even if +the strings are not all the same length. +@end deftypefn + +@deftypefn {Built-in Function} {} isstr (@var{a}) +Return 1 if @var{a} is a string. Otherwise, return 0. +@end deftypefn + +@node Searching and Replacing, String Conversions, Creating Strings, Strings +@section Searching and Replacing + +@deftypefn {Function File} {} deblank (@var{s}) +Removes the trailing blanks from the string @var{s}. +@end deftypefn + +@deftypefn {Function File} {} findstr (@var{s}, @var{t}, @var{overlap}) +Return the vector of all positions in the longer of the two strings +@var{s} and @var{t} where an occurrence of the shorter of the two starts. +If the optional argument @var{overlap} is nonzero, the returned vector +can include overlapping positions (this is the default). For example, + +@example +findstr ("ababab", "a") + @result{} [ 1, 3, 5 ] +findstr ("abababa", "aba", 0) + @result{} [ 1, 5 ] +@end example +@end deftypefn + +@deftypefn {Function File} {} index (@var{s}, @var{t}) +Return the position of the first occurrence of the string @var{t} in the +string @var{s}, or 0 if no occurrence is found. For example, + +@example +index ("Teststring", "t") + @result{} 4 +@end example + +@strong{Note:} This function does not work for arrays of strings. +@end deftypefn + +@deftypefn {Function File} {} rindex (@var{s}, @var{t}) +Return the position of the last occurrence of the string @var{t} in the +string @var{s}, or 0 if no occurrence is found. For example, + +@example +rindex ("Teststring", "t") + @result{} 6 +@end example + +@strong{Note:} This function does not work for arrays of strings. +@end deftypefn + +@deftypefn {Function File} {} split (@var{s}, @var{t}) +Divides the string @var{s} into pieces separated by @var{t}, returning +the result in a string array (padded with blanks to form a valid +matrix). For example, + +@example +split ("Test string", "t") + @result{} "Tes " + " s " + "ring" +@end example +@end deftypefn + +@deftypefn {Function File} {} strcmp (@var{s1}, @var{s2}) +Compares two strings, returning 1 if they are the same, and 0 otherwise. + +@strong{Note:} For compatibility with @sc{Matlab}, Octave's strcmp +function returns 1 if the strings are equal, and 0 otherwise. This is +just the opposite of the corresponding C library function. +@end deftypefn + +@deftypefn {Function File} {} strrep (@var{s}, @var{x}, @var{y}) +Replaces all occurrences of the substring @var{x} of the string @var{s} +with the string @var{y}. For example, + +@example +strrep ("This is a test string", "is", "&%$") + @result{} "Th&%$ &%$ a test string" +@end example +@end deftypefn + +@deftypefn {Function File} {} substr (@var{s}, @var{beg}, @var{len}) +Return the substring of @var{s} which starts at character number +@var{beg} and is @var{len} characters long. For example, + +@example +substr ("This is a test string", 6, 9) + @result{} "is a test" +@end example + +@quotation +@strong{Note:} +This function is patterned after AWK. You can get the same result by +@code{@var{s} (@var{beg} : (@var{beg} + @var{len} - 1))}. +@end quotation +@end deftypefn + +@node String Conversions, Character Class Functions, Searching and Replacing, Strings +@section String Conversions + +@deftypefn {Function File} {} bin2dec (@var{s}) +Return a decimal number corresponding to the binary number +represented as a string of zeros and ones. For example, + +@example +bin2dec ("1110") + @result{} 14 +@end example +@end deftypefn + +@deftypefn {Function File} {} dec2bin (@var{n}) +Return a binary number corresponding the nonnegative decimal number +@var{n}, as a string of ones and zeros. For example, + +@example +dec2bin (14) + @result{} "1110" +@end example +@end deftypefn + +@deftypefn {Function File} {} dec2hex (@var{n}) +Return the hexadecimal number corresponding to the nonnegative decimal +number @var{n}, as a string. For example, + +@example +dec2hex (2748) + @result{} "abc" +@end example +@end deftypefn + +@deftypefn {Function File} {} hex2dec (@var{s}) +Return the decimal number corresponding to the hexadecimal number stored +in the string @var{s}. For example, + +@example +hex2dec ("12B") + @result{} 299 +hex2dec ("12b") + @result{} 299 +@end example +@end deftypefn + +@deftypefn {Function File} {} str2num (@var{s}) +Convert the string @var{s} to a number. +@end deftypefn + +@deftypefn {Function File} {} toascii (@var{s}) +Return ASCII representation of @var{s} in a matrix. For example, + +@example +@group +toascii ("ASCII") + @result{} [ 65, 83, 67, 73, 73 ] +@end group + +@end example +@end deftypefn + +@deftypefn {Function File} {} tolower (@var{s}) +Return a copy of the string @var{s}, with each upper-case character +replaced by the corresponding lower-case one; nonalphabetic characters +are left unchanged. For example, + +@example +tolower ("MiXeD cAsE 123") + @result{} "mixed case 123" +@end example +@end deftypefn + +@deftypefn {Function File} {} toupper (@var{s}) +Return a copy of the string @var{s}, with each lower-case character +replaced by the corresponding upper-case one; nonalphabetic characters +are left unchanged. For example, + +@example +@group +toupper ("MiXeD cAsE 123") + @result{} "MIXED CASE 123" +@end group +@end example +@end deftypefn + +@deftypefn {Built-in Function} {} undo_string_escapes (@var{s}) +Converts special characters in strings back to their escaped forms. For +example, the expression + +@example +bell = "\a"; +@end example + +@noindent +assigns the value of the alert character (control-g, ASCII code 7) to +the string variable @code{bell}. If this string is printed, the +system will ring the terminal bell (if it is possible). This is +normally the desired outcome. However, sometimes it is useful to be +able to print the original representation of the string, with the +special characters replaced by their escape sequences. For example, + +@example +octave:13> undo_string_escapes (bell) +ans = \a +@end example + +@noindent +replaces the unprintable alert character with its printable +representation. +@end deftypefn + +@defvr {Built-in Variable} implicit_num_to_str_ok +If the value of @code{implicit_num_to_str_ok} is nonzero, implicit +conversions of numbers to their ASCII character equivalents are +allowed when strings are constructed using a mixture of strings and +numbers in matrix notation. Otherwise, an error message is printed and +control is returned to the top level. The default value is 0. For +example, + +@example +@group +[ "f", 111, 111 ] + @result{} "foo" +@end group +@end example +@end defvr + +@defvr {Built-in Variable} implicit_str_to_num_ok +If the value of @code{implicit_str_to_num_ok} is nonzero, implicit +conversions of strings to their numeric ASCII equivalents are allowed. +Otherwise, an error message is printed and control is returned to the +top level. The default value is 0. +@end defvr + +@node Character Class Functions, , String Conversions, Strings +@section Character Class Functions + +Octave also provides the following character class test functions +patterned after the functions in the standard C library. They all +operate on string arrays and return matrices of zeros and ones. +Elements that are nonzero indicate that the condition was true for the +corresponding character in the string array. For example, + +@example +@group +isalpha ("!Q@@WERT^Y&") + @result{} [ 0, 1, 0, 1, 1, 1, 1, 0, 1, 0 ] +@end group +@end example + +@deftypefn {Mapping Function} {} isalnum (@var{s}) +Return 1 for characters that are letters or digits (@code{isalpha +(@var{a})} or @code{isdigit (@var{})} is true). +@end deftypefn + +@deftypefn {Mapping Function} {} isalpha (@var{s}) +Return true for characters that are letters (@code{isupper (@var{a})} +or @code{islower (@var{})} is true). +@end deftypefn + +@deftypefn {Mapping Function} {} isascii (@var{s}) +Return 1 for characters that are ASCII (in the range 0 to 127 decimal). +@end deftypefn + +@deftypefn {Mapping Function} {} iscntrl (@var{s}) +Return 1 for control characters. +@end deftypefn + +@deftypefn {Mapping Function} {} isdigit (@var{s}) +Return 1 for characters that are decimal digits. +@end deftypefn + +@deftypefn {Mapping Function} {} isgraph (@var{s}) +Return 1 for printable characters (but not the space character). +@end deftypefn + +@deftypefn {Mapping Function} {} islower (@var{s}) +Return 1 for characters that are lower case letters. +@end deftypefn + +@deftypefn {Mapping Function} {} isprint (@var{s}) +Return 1 for printable characters (including the space character). +@end deftypefn + +@deftypefn {Mapping Function} {} ispunct (@var{s}) +Return 1 for punctuation characters. +@end deftypefn + +@deftypefn {Mapping Function} {} isspace (@var{s}) +Return 1 for whitespace characters (space, formfeed, newline, +carriage return, tab, and vertical tab). +@end deftypefn + +@deftypefn {Mapping Function} {} isupper (@var{s}) +Return 1 for upper case letters. +@end deftypefn + +@deftypefn {Mapping Function} {} isxdigit (@var{s}) +Return 1 for characters that are hexadecimal digits. +@end deftypefn diff --git a/doc/interpreter/struct.texi b/doc/interpreter/struct.texi deleted file mode 100644 --- a/doc/interpreter/struct.texi +++ /dev/null @@ -1,201 +0,0 @@ -@c Copyright (C) 1996, 1997 John W. Eaton -@c This is part of the Octave manual. -@c For copying conditions, see the file gpl.texi. - -@node Data Structures, Variables, Strings, Top -@chapter Data Structures -@cindex structures -@cindex data structures - -Octave includes support for organizing data in structures. The current -implementation uses an associative array with indices limited to -strings, but the syntax is more like C-style structures. Here are some -examples of using data structures in Octave. - -Elements of structures can be of any value type. For example, the three -expressions - -@example -@group -x.a = 1 -x.b = [1, 2; 3, 4] -x.c = "string" -@end group -@end example - -@noindent -create a structure with three elements. To print the value of the -structure, you can type its name, just as for any other variable: - -@example -@group -octave:2> x -x = -@{ - a = 1 - b = - - 1 2 - 3 4 - - c = string -@} -@end group -@end example - -@noindent -Note that Octave may print the elements in any order. - -Structures may be copied. - -@example -@group -octave:1> y = x -y = -@{ - a = 1 - b = - - 1 2 - 3 4 - - c = string -@} -@end group -@end example - -Since structures are themselves values, structure elements may reference -other structures. The following statements change the value of the -element @code{b} of the structure @code{x} to be a data structure -containing the single element @code{d}, which has a value of 3. - -@example -@group -octave:1> x.b.d = 3 -x.b.d = 3 -octave:2> x.b -ans = -@{ - d = 3 -@} -octave:3> x -x = -@{ - a = 1 - b = - @{ - d = 3 - @} - - c = string -@} -@end group -@end example - -Note that when Octave prints the value of a structure that contains -other structures, only a few levels are displayed. For example, - -@example -@group -octave:1> a.b.c.d.e = 1; -octave:2> a -a = -@{ - b = - @{ - c = - @} -@} -@end group -@end example - -@noindent -This prevents long and confusing output from large deeply nested -structures. - -@defvr {Built-in Variable} struct_levels_to_print -You can tell Octave how many structure levels to display by setting the -built-in variable @code{struct_levels_to_print}. The default value is 2. -@end defvr - -Functions can return structures. For example, the following function -separates the real and complex parts of a matrix and stores them in two -elements of the same structure variable. - -@example -@group -octave:1> function y = f (x) -> y.re = real (x); -> y.im = imag (x); -> endfunction -@end group -@end example - -When called with a complex-valued argument, @code{f} returns the data -structure containing the real and imaginary parts of the original -function argument. - -@example -@group -octave:2> f (rand (2) + rand (2) * I); -ans = -@{ - im = - - 0.26475 0.14828 - 0.18436 0.83669 - - re = - - 0.040239 0.242160 - 0.238081 0.402523 -@} -@end group -@end example - -Function return lists can include structure elements, and they may be -indexed like any other variable. For example, - -@example -@group -octave:1> [ x.u, x.s(2:3,2:3), x.v ] = svd ([1, 2; 3, 4]) -x.u = - - -0.40455 -0.91451 - -0.91451 0.40455 - -x.s = - - 0.00000 0.00000 0.00000 - 0.00000 5.46499 0.00000 - 0.00000 0.00000 0.36597 - -x.v = - - -0.57605 0.81742 - -0.81742 -0.57605 -@end group -@end example - -It is also possible to cycle through all the elements of a structure in -a loop, using a special form of the @code{for} statement -(@pxref{The for Statement}) - -The following functions are available to give you information about -structures. - -@deftypefn {Built-in Function} {} is_struct (@var{expr}) -Return 1 if the value of the expression @var{expr} is a structure. -@end deftypefn - -@deftypefn {Built-in Function} {} struct_contains (@var{expr}, @var{name}) -Return 1 if the expression @var{expr} is a structure and it includes an -element named @var{name}. The first argument must be a structure and -the second must be a string. -@end deftypefn - -@deftypefn {Built-in Function} {} struct_elements (@var{struct}) -Return a list of strings naming the elements of the structure -@var{struct}. It is an error to call @code{struct_elements} with an -argument that is not a structure. -@end deftypefn diff --git a/doc/interpreter/struct.txi b/doc/interpreter/struct.txi new file mode 100644 --- /dev/null +++ b/doc/interpreter/struct.txi @@ -0,0 +1,201 @@ +@c Copyright (C) 1996, 1997 John W. Eaton +@c This is part of the Octave manual. +@c For copying conditions, see the file gpl.texi. + +@node Data Structures, Variables, Strings, Top +@chapter Data Structures +@cindex structures +@cindex data structures + +Octave includes support for organizing data in structures. The current +implementation uses an associative array with indices limited to +strings, but the syntax is more like C-style structures. Here are some +examples of using data structures in Octave. + +Elements of structures can be of any value type. For example, the three +expressions + +@example +@group +x.a = 1 +x.b = [1, 2; 3, 4] +x.c = "string" +@end group +@end example + +@noindent +create a structure with three elements. To print the value of the +structure, you can type its name, just as for any other variable: + +@example +@group +octave:2> x +x = +@{ + a = 1 + b = + + 1 2 + 3 4 + + c = string +@} +@end group +@end example + +@noindent +Note that Octave may print the elements in any order. + +Structures may be copied. + +@example +@group +octave:1> y = x +y = +@{ + a = 1 + b = + + 1 2 + 3 4 + + c = string +@} +@end group +@end example + +Since structures are themselves values, structure elements may reference +other structures. The following statements change the value of the +element @code{b} of the structure @code{x} to be a data structure +containing the single element @code{d}, which has a value of 3. + +@example +@group +octave:1> x.b.d = 3 +x.b.d = 3 +octave:2> x.b +ans = +@{ + d = 3 +@} +octave:3> x +x = +@{ + a = 1 + b = + @{ + d = 3 + @} + + c = string +@} +@end group +@end example + +Note that when Octave prints the value of a structure that contains +other structures, only a few levels are displayed. For example, + +@example +@group +octave:1> a.b.c.d.e = 1; +octave:2> a +a = +@{ + b = + @{ + c = + @} +@} +@end group +@end example + +@noindent +This prevents long and confusing output from large deeply nested +structures. + +@defvr {Built-in Variable} struct_levels_to_print +You can tell Octave how many structure levels to display by setting the +built-in variable @code{struct_levels_to_print}. The default value is 2. +@end defvr + +Functions can return structures. For example, the following function +separates the real and complex parts of a matrix and stores them in two +elements of the same structure variable. + +@example +@group +octave:1> function y = f (x) +> y.re = real (x); +> y.im = imag (x); +> endfunction +@end group +@end example + +When called with a complex-valued argument, @code{f} returns the data +structure containing the real and imaginary parts of the original +function argument. + +@example +@group +octave:2> f (rand (2) + rand (2) * I); +ans = +@{ + im = + + 0.26475 0.14828 + 0.18436 0.83669 + + re = + + 0.040239 0.242160 + 0.238081 0.402523 +@} +@end group +@end example + +Function return lists can include structure elements, and they may be +indexed like any other variable. For example, + +@example +@group +octave:1> [ x.u, x.s(2:3,2:3), x.v ] = svd ([1, 2; 3, 4]) +x.u = + + -0.40455 -0.91451 + -0.91451 0.40455 + +x.s = + + 0.00000 0.00000 0.00000 + 0.00000 5.46499 0.00000 + 0.00000 0.00000 0.36597 + +x.v = + + -0.57605 0.81742 + -0.81742 -0.57605 +@end group +@end example + +It is also possible to cycle through all the elements of a structure in +a loop, using a special form of the @code{for} statement +(@pxref{The for Statement}) + +The following functions are available to give you information about +structures. + +@deftypefn {Built-in Function} {} is_struct (@var{expr}) +Return 1 if the value of the expression @var{expr} is a structure. +@end deftypefn + +@deftypefn {Built-in Function} {} struct_contains (@var{expr}, @var{name}) +Return 1 if the expression @var{expr} is a structure and it includes an +element named @var{name}. The first argument must be a structure and +the second must be a string. +@end deftypefn + +@deftypefn {Built-in Function} {} struct_elements (@var{struct}) +Return a list of strings naming the elements of the structure +@var{struct}. It is an error to call @code{struct_elements} with an +argument that is not a structure. +@end deftypefn diff --git a/doc/interpreter/system.texi b/doc/interpreter/system.texi deleted file mode 100644 --- a/doc/interpreter/system.texi +++ /dev/null @@ -1,1247 +0,0 @@ -@c Copyright (C) 1996, 1997 John W. Eaton -@c This is part of the Octave manual. -@c For copying conditions, see the file gpl.texi. - -@node System Utilities, Tips, Audio Processing, Top -@chapter System Utilities - -This chapter describes the functions that are available to allow you to -get information about what is happening outside of Octave, while it is -still running, and use this information in your program. For example, -you can get information about environment variables, the current time, -and even start other programs from the Octave prompt. - -@menu -* Timing Utilities:: -* Filesystem Utilities:: -* Controlling Subprocesses:: -* Process ID Information:: -* Environment Variables:: -* Current Working Directory:: -* Password Database Functions:: -* Group Database Functions:: -* System Information:: -@end menu - -@node Timing Utilities, Filesystem Utilities, System Utilities, System Utilities -@section Timing Utilities - -Octave's core set of functions for manipulating time values are -patterned after the corresponding functions from the standard C library. -Several of these functions use a data structure for time that includes -the following elements: - -@table @code -@item usec -Microseconds after the second (0-999999). - -@item sec -Seconds after the minute (0-61). This number can be 61 to account -for leap seconds. - -@item min -Minutes after the hour (0-59). - -@item hour -Hours since midnight (0-23). - -@item mday -Day of the month (1-31). - -@item mon -Months since January (0-11). - -@item year -Years since 1900. - -@item wday -Days since Sunday (0-6). - -@item yday -Days since January 1 (0-365). - -@item isdst -Daylight Savings Time flag. - -@item zone -Time zone. -@end table - -@noindent -In the descriptions of the following functions, this structure is -referred to as a @var{tm_struct}. - -@deftypefn {Loadable Function} {} time () -Return the current time as the number of seconds since the epoch. The -epoch is referenced to 00:00:00 CUT (Coordinated Universal Time) 1 Jan -1970. For example, on Monday February 17, 1997 at 07:15:06 CUT, the -value returned by @code{time} was 856163706. -@end deftypefn - -@deftypefn {Function File} {} ctime (@var{t}) -Convert a value returned from @code{time} (or any other nonnegative -integer), to the local time and return a string of the same form as -@code{asctime}. The function @code{ctime (time)} is equivalent to -@code{asctime (localtime (time))}. For example, - -@example -@group -ctime (time ()) - @result{} "Mon Feb 17 01:15:06 1997" -@end group -@end example -@end deftypefn - -@deftypefn {Loadable Function} {} gmtime (@var{t}) -Given a value returned from time (or any nonnegative integer), -return a time structure corresponding to CUT. For example, - -@example -@group -gmtime (time ()) - @result{} @{ - usec = 0 - year = 97 - mon = 1 - mday = 17 - sec = 6 - zone = CST - min = 15 - wday = 1 - hour = 7 - isdst = 0 - yday = 47 - @} -@end group -@end example -@end deftypefn - -@deftypefn {Loadable Function} {} localtime (@var{t}) -Given a value returned from time (or any nonnegative integer), -return a time structure corresponding to the local time zone. - -@example -@group -localtime (time ()) - @result{} @{ - usec = 0 - year = 97 - mon = 1 - mday = 17 - sec = 6 - zone = CST - min = 15 - wday = 1 - hour = 1 - isdst = 0 - yday = 47 - @} -@end group -@end example -@end deftypefn - -@deftypefn {Loadable Function} {} mktime (@var{tm_struct}) -Convert a time structure corresponding to the local time to the number -of seconds since the epoch. For example, - -@example -@group -mktime (localtime (time ()) - @result{} 856163706 -@end group -@end example -@end deftypefn - -@deftypefn {Function File} {} asctime (@var{tm_struct}) -Convert a time structure to a string using the following five-field -format: Thu Mar 28 08:40:14 1996. For example, - -@example -@group -asctime (localtime (time ()) - @result{} "Mon Feb 17 01:15:06 1997\n" -@end group -@end example - -This is equivalent to @code{ctime (time ())}. -@end deftypefn - -@deftypefn {Loadable Function} {} strftime (@var{tm_struct}) -Format a time structure in a flexible way using @samp{%} substitutions -similar to those in @code{printf}. Except where noted, substituted -fields have a fixed size; numeric fields are padded if necessary. -Padding is with zeros by default; for fields that display a single -number, padding can be changed or inhibited by following the @samp{%} -with one of the modifiers described below. Unknown field specifiers are -copied as normal characters. All other characters are copied to the -output without change. For example, - -@example -@group -strftime ("%r (%Z) %A %e %B %Y", localtime (time ()) - @result{} "01:15:06 AM (CST) Monday 17 February 1997" -@end group -@end example - -Octave's @code{strftime} function supports a superset of the ANSI C -field specifiers. - -@noindent -Literal character fields: - -@table @code -@item % -% character. - -@item n -Newline character. - -@item t -Tab character. -@end table - -@noindent -Numeric modifiers (a nonstandard extension): - -@table @code -@item - (dash) -Do not pad the field. - -@item _ (underscore) -Pad the field with spaces. -@end table - -@noindent -Time fields: - -@table @code -@item %H -Hour (00-23). - -@item %I -Hour (01-12). - -@item %k -Hour (0-23). - -@item %l -Hour (1-12). - -@item %M -Minute (00-59). - -@item %p -Locale's AM or PM. - -@item %r -Time, 12-hour (hh:mm:ss [AP]M). - -@item %R -Time, 24-hour (hh:mm). - -@item %s -Time in seconds since 00:00:00, Jan 1, 1970 (a nonstandard extension). - -@item %S -Second (00-61). - -@item %T -Time, 24-hour (hh:mm:ss). - -@item %X -Locale's time representation (%H:%M:%S). - -@item %Z -Time zone (EDT), or nothing if no time zone is determinable. -@end table - -@noindent -Date fields: - -@table @code -@item %a -Locale's abbreviated weekday name (Sun-Sat). - -@item %A -Locale's full weekday name, variable length (Sunday-Saturday). - -@item %b -Locale's abbreviated month name (Jan-Dec). - -@item %B -Locale's full month name, variable length (January-December). - -@item %c -Locale's date and time (Sat Nov 04 12:02:33 EST 1989). - -@item %C -Century (00-99). - -@item %d -Day of month (01-31). - -@item %e -Day of month ( 1-31). - -@item %D -Date (mm/dd/yy). - -@item %h -Same as %b. - -@item %j -Day of year (001-366). - -@item %m -Month (01-12). - -@item %U -Week number of year with Sunday as first day of week (00-53). - -@item %w -Day of week (0-6). - -@item %W -Week number of year with Monday as first day of week (00-53). - -@item %x -Locale's date representation (mm/dd/yy). - -@item %y -Last two digits of year (00-99). - -@item %Y -Year (1970-). -@end table -@end deftypefn - -Most of the remaining functions described in this section are not -patterned after the standard C library. Some are available for -compatiblity with @sc{Matlab} and others are provided because they are -useful. - -@deftypefn {Function File} {} clock () -Return a vector containing the current year, month (1-12), day (1-31), -hour (0-23), minute (0-59) and second (0-61). For example, - -@example -@group -clock () - @result{} [ 1993, 8, 20, 4, 56, 1 ] -@end group -@end example - -The function clock is more accurate on systems that have the -@code{gettimeofday} function. -@end deftypefn - -@deftypefn {Function File} {} date () -Return the date as a character string in the form DD-MMM-YY. For -example, - -@example -@group -date () - @result{} "20-Aug-93" -@end group -@end example -@end deftypefn - -@deftypefn {Function File} {} etime (@var{t1}, @var{t2}) -Return the difference (in seconds) between two time values returned from -@code{clock}. For example: - -@example -t0 = clock (); -# many computations later... -elapsed_time = etime (clock (), t0); -@end example - -@noindent -will set the variable @code{elapsed_time} to the number of seconds since -the variable @code{t0} was set. -@end deftypefn - -@deftypefn {Built-in Function} {[@var{total}, @var{user}, @var{system}] =} cputime (); -Return the CPU time used by your Octave session. The first output is -the total time spent executing your process and is equal to the sum of -second and third outputs, which are the number of CPU seconds spent -executing in user mode and the number of CPU seconds spent executing in -system mode, respectively. If your system does not have a way to report -CPU time usage, @code{cputime} returns 0 for each of its output values. -Note that because Octave used some CPU time to start, it is reasonable -to check to see if @code{cputime} works by checking to see if the total -CPU time used is nonzero. -@end deftypefn - -@deftypefn {Function File} {} is_leap_year (@var{year}) -Return 1 if the given year is a leap year and 0 otherwise. If no -arguments are provided, @code{is_leap_year} will use the current year. -For example, - -@example -@group -is_leap_year (2000) - @result{} 1 -@end group -@end example -@end deftypefn - -@deftypefn {Function File} {} tic () -@deftypefnx {Function File} {} toc () -These functions set and check a wall-clock timer. For example, - -@example -tic (); -# many computations later... -elapsed_time = toc (); -@end example - -@noindent -will set the variable @code{elapsed_time} to the number of seconds since -the most recent call to the function @code{tic}. - -If you are more interested in the CPU time that your process used, you -should use the @code{cputime} function instead. The @code{tic} and -@code{toc} functions report the actual wall clock time that elapsed -between the calls. This may include time spent processing other jobs or -doing nothing at all. For example, - -@example -@group -tic (); sleep (5); toc () - @result{} 5 -t = cputime (); sleep (5); cputime () - t - @result{} 0 -@end group -@end example - -@noindent -(This example also illustrates that the CPU timer may have a fairly -coarse resolution.) -@end deftypefn - -@deftypefn {Built-in Function} {} pause (@var{seconds}) -Suspend the execution of the program. If invoked without any arguments, -Octave waits until you type a character. With a numeric argument, it -pauses for the given number of seconds. For example, the following -statement prints a message and then waits 5 seconds before clearing the -screen. - -@example -@group -fprintf (stderr, "wait please...\n"); -pause (5); -clc; -@end group -@end example -@end deftypefn - -@deftypefn {Built-in Function} {} sleep (@var{seconds}) -Suspend the execution of the program for the given number of seconds. -@end deftypefn - -@deftypefn {Built-in Function} {} usleep (@var{microseconds}) -Suspend the execution of the program for the given number of -microseconds. On systems where it is not possible to sleep for periods -of time less than one second, @code{usleep} will pause the execution for -@code{round (@var{microseconds} / 1e6)} seconds. -@end deftypefn - -@node Filesystem Utilities, Controlling Subprocesses, Timing Utilities, System Utilities -@section Filesystem Utilities - -Octave includes the following functions for renaming and deleting files, -creating, deleting, and reading directories, and for getting information -about the status of files. - -@deftypefn {Built-in Function} {[@var{err}, @var{msg}] =} rename (@var{old}, @var{new}) -Change the name of file @var{old} to @var{new}. - -If successful, @var{err} is 0 and @var{msg} is an empty string. -Otherwise, @var{err} is nonzero and @var{msg} contains a -system-dependent error message. -@end deftypefn - -@deftypefn {Built-in Function} {[@var{err}, @var{msg}] =} unlink (@var{file}) -Delete @var{file}. - -If successful, @var{err} is 0 and @var{msg} is an empty string. -Otherwise, @var{err} is nonzero and @var{msg} contains a -system-dependent error message. -@end deftypefn - -@deftypefn {Built-in Function} {[@var{files}, @var{err}, @var{msg}] =} readdir (@var{dir}) -Return names of the files in the directory @var{dir} as an array of -strings. If an error occurs, return an empty matrix in @var{files}. - -If successful, @var{err} is 0 and @var{msg} is an empty string. -Otherwise, @var{err} is nonzero and @var{msg} contains a -system-dependent error message. -@end deftypefn - -@deftypefn {Built-in Function} {[@var{err}, @var{msg}] =} mkdir (@var{dir}) -Create a directory named @var{dir}. - -If successful, @var{err} is 0 and @var{msg} is an empty string. -Otherwise, @var{err} is nonzero and @var{msg} contains a -system-dependent error message. -@end deftypefn - -@deftypefn {Built-in Function} {[@var{err}, @var{msg}] =} rmdir (@var{dir}) -Remove the directory named @var{dir}. - -If successful, @var{err} is 0 and @var{msg} is an empty string. -Otherwise, @var{err} is nonzero and @var{msg} contains a -system-dependent error message. -@end deftypefn - -@deftypefn {Built-in Function} {[@var{err}, @var{msg}] =} mkfifo (@var{name}) -Create a FIFO special file. - -If successful, @var{err} is 0 and @var{msg} is an empty string. -Otherwise, @var{err} is nonzero and @var{msg} contains a -system-dependent error message. -@end deftypefn - -@c XXX FIXME XXX -- this needs to be explained, but I don't feel up to -@c it just now... - -@deftypefn {Built-in Function} {} umask (@var{mask}) -Set the permission mask for file creation. The parameter @var{mask} is -interpreted as an octal number. -@end deftypefn - -@deftypefn {Built-in Function} {[@var{info}, @var{err}, @var{msg}] =} stat (@var{file}) -@deftypefnx {Built-in Function} {[@var{info}, @var{err}, @var{msg}] =} lstat (@var{file}) -Return a structure @var{s} containing the following information about -@var{file}. - -@table @code -@item dev -ID of device containing a directory entry for this file. - -@item ino -File number of the file. - -@item modestr -File mode, as a string of ten letters or dashes as would be returned by -@kbd{ls -l}. - -@item nlink -Number of links. - -@item uid -User ID of file's owner. - -@item gid -Group ID of file's group. - -@item rdev -ID of device for block or character special files. - -@item size -Size in bytes. - -@item atime -Time of last access in the same form as time values returned from -@code{time}. @xref{Timing Utilities}. - -@item mtime -Time of last modification in the same form as time values returned from -@code{time}. @xref{Timing Utilities}. - -@item ctime -Time of last file status change in the same form as time values returned from -@code{time}. @xref{Timing Utilities}. - -@item blksize -Size of blocks in the file. - -@item blocks -Number of blocks allocated for file. -@end table - -If the call is successful @var{err} is 0 and @var{msg} is an empty -string. If the file does not exist, or some other error occurs, @var{s} -is an empty matrix, @var{err} is @minus{}1, and @var{msg} contains the -corresponding system error message. - -If @var{file} is a symbolic link, @code{stat} will return information -about the actual file the is referenced by the link. Use @code{lstat} -if you want information about the symbolic link itself. - -For example, - -@example -@group -[s, err, msg] = stat ("/vmlinuz") - @result{} s = - @{ - atime = 855399756 - rdev = 0 - ctime = 847219094 - uid = 0 - size = 389218 - blksize = 4096 - mtime = 847219094 - gid = 6 - nlink = 1 - blocks = 768 - modestr = -rw-r--r-- - ino = 9316 - dev = 2049 - @} - @result{} err = 0 - @result{} msg = -@end group -@end example -@end deftypefn - -@deftypefn {Built-in Function} {} glob (@var{pattern}) -Given an array of strings in @var{pattern}, return the list of file -names that any of them, or an empty string if no patterns match. Tilde -expansion is performed on each of the patterns before looking for -matching file names. For example, - -@example -@group -glob ("/vm*") - @result{} "/vmlinuz" -@end group -@end example - -Note that multiple values are returned in a string matrix with the fill -character set to ASCII NUL. -@end deftypefn - -@deftypefn {Built-in Function} {} fnmatch (@var{pattern}, @var{string}) -Return 1 or zero for each element of @var{string} that matches any of -the elements of the string array @var{pattern}, using the rules of -filename pattern matching. For example, - -@example -@group -fnmatch ("a*b", ["ab"; "axyzb"; "xyzab"]) - @result{} [ 1; 1; 0 ] -@end group -@end example -@end deftypefn - -@deftypefn {Built-in Function} {} file_in_path (@var{path}, @var{file}) -Return the absolute name name of @var{file} if it can be found in -@var{path}. The value of @var{path} should be a colon-separated list of -directories in the format described for the built-in variable -@code{LOADPATH}. - -If the file cannot be found in the path, an empty matrix is returned. -For example, - -@example -file_in_path (LOADPATH, "nargchk.m") - @result{} "@value{OCTAVEHOME}/share/octave/2.0/m/general/nargchk.m" -@end example -@end deftypefn - -@deftypefn {Built-in Function} {} tilde_expand (@var{string}) -Performs tilde expansion on @var{string}. If @var{string} begins with a -tilde character, (@samp{~}), all of the characters preceding the first -slash (or all characters, if there is no slash) are treated as a -possible user name, and the tilde and the following characters up to the -slash are replaced by the home directory of the named user. If the -tilde is followed immediately by a slash, the tilde is replaced by the -home directory of the user running Octave. For example, - -@example -@group -tilde_expand ("~joeuser/bin") - @result{} "/home/joeuser/bin" -tilde_expand ("~/bin") - @result{} "/home/jwe/bin" -@end group -@end example -@end deftypefn - -@node Controlling Subprocesses, Process ID Information, Filesystem Utilities, System Utilities -@section Controlling Subprocesses - -Octave includes some high-level commands like @code{system} and -@code{popen} for starting subprocesses. If you want to run another -program to perform some task and then look at its output, you will -probably want to use these functions. - -Octave also provides several very low-level Unix-like functions which -can also be used for starting subprocesses, but you should probably only -use them if you can't find any way to do what you need with the -higher-level functions. - -@deftypefn {Built-in Function} {} system (@var{string}, @var{return_output}, @var{type}) -Execute a shell command specified by @var{string}. The second argument is optional. -If @var{type} is @code{"async"}, the process is started in the -background and the process id of the child process is returned -immediately. Otherwise, the process is started, and Octave waits until -it exits. If @var{type} argument is omitted, a value of @code{"sync"} -is assumed. - -If two input arguments are given (the actual value of -@var{return_output} is irrelevant) and the subprocess is started -synchronously, or if @var{system} is called with one input argument and -one or more output arguments, the output from the command is returned. -Otherwise, if the subprocess is executed synchronously, it's output is -sent to the standard output. To send the output of a command executed -with @var{system} through the pager, use a command like - -@example -disp (system (cmd, 1)); -@end example - -@noindent -or - -@example -printf ("%s\n", system (cmd, 1)); -@end example - -The @code{system} function can return two values. The first is any -output from the command that was written to the standard output stream, -and the second is the output status of the command. For example, - -@example -[output, status] = system ("echo foo; exit 2"); -@end example - -@noindent -will set the variable @code{output} to the string @samp{foo}, and the -variable @code{status} to the integer @samp{2}. -@end deftypefn - -@deftypefn {Built-in Function} {fid =} popen (@var{command}, @var{mode}) -Start a process and create a pipe. The name of the command to run is -given by @var{command}. The file identifier corresponding to the input -or output stream of the process is returned in @var{fid}. The argument -@var{mode} may be - -@table @code -@item "r" -The pipe will be connected to the standard output of the process, and -open for reading. - -@item "w" -The pipe will be connected to the standard input of the process, and -open for writing. -@end table - -For example, - -@example -@group -fid = popen ("ls -ltr / | tail -3", "r"); -while (isstr (s = fgets (fid))) - fputs (stdout, s); -endwhile - @print{} drwxr-xr-x 33 root root 3072 Feb 15 13:28 etc - @print{} drwxr-xr-x 3 root root 1024 Feb 15 13:28 lib - @print{} drwxrwxrwt 15 root root 2048 Feb 17 14:53 tmp -@end group -@end example -@end deftypefn - -@deftypefn {Built-in Function} {} pclose (@var{fid}) -Close a file identifier that was opened by @code{popen}. You may also -use @code{fclose} for the same purpose. -@end deftypefn - -@deftypefn {Built-in Function} {[@var{in}, @var{out}, @var{pid}] =} popen2 (@var{command}, @var{args}) -Start a subprocess with two-way communication. The name of the process -is given by @var{command}, and @var{args} is an array of strings -containing options for the command. The file identifiers for the input -and output streams of the subprocess are returned in @var{in} and -@var{out}. If execution of the command is successful, @var{pid} -contains the process ID of the subprocess. Otherwise, @var{pid} is -@minus{}1. - -For example, - -@example -@group -[in, out, pid] = popen2 ("sort", "-nr"); -fputs (in, "these\nare\nsome\nstrings\n"); -fclose (in); -while (isstr (s = fgets (out))) - fputs (stdout, s); -endwhile -fclose (out); - @print{} are - @print{} some - @print{} strings - @print{} these -@end group -@end example -@end deftypefn - -@defvr {Built-in Variable} EXEC_PATH -The variable @code{EXEC_PATH} is a colon separated list of directories -to search when executing subprograms. Its initial value is taken from -the environment variable @code{OCTAVE_EXEC_PATH} (if it exists) or -@code{PATH}, but that value can be overridden by the command line -argument @code{--exec-path PATH}, or by setting the value of -@code{EXEC_PATH} in a startup script. If the value of @code{EXEC_PATH} -begins (ends) with a colon, the directories - -@example -@group -@var{octave-home}/libexec/octave/site/exec/@var{arch} -@var{octave-home}/libexec/octave/@var{version}/exec/@var{arch} -@end group -@end example - -@noindent -are prepended (appended) to @code{EXEC_PATH}, where @var{octave-home} -is the top-level directory where all of Octave is installed -(the default value is @file{@value{OCTAVEHOME}}). If you don't specify -a value for @code{EXEC_PATH} explicitly, these special directories are -prepended to your shell path. -@end defvr - -In most cases, the following functions simply decode their arguments and -make the corresponding Unix system calls. For a complete example of how -they can be used, look at the definition of the function @code{popen2}. - -@deftypefn {Built-in Function} {[@var{pid}, @var{msg}] =} fork () -Create a copy of the current process. - -Fork can return one of the following values: - -@table @asis -@item > 0 -You are in the parent process. The value returned from @code{fork} is -the process id of the child process. You should probably arrange to -wait for any child processes to exit. - -@item 0 -You are in the child process. You can call @code{exec} to start another -process. If that fails, you should probably call @code{exit}. - -@item < 0 -The call to @code{fork} failed for some reason. You must take evasive -action. A system dependent error message will be waiting in @var{msg}. -@end table -@end deftypefn - -@deftypefn {Built-in Function} {[@var{err}, @var{msg}] =} exec (@var{file}, @var{args}) -Replace current process with a new process. Calling @code{exec} without -first calling @code{fork} will terminate your current Octave process and -replace it with the program named by @var{file}. For example, - -@example -exec ("ls" "-l") -@end example - -@noindent -will run @code{ls} and return you to your shell prompt. - -If successful, @code{exec} does not return. If @code{exec} does return, -@var{err} will be nonzero, and @var{msg} will contain a system-dependent -error message. -@end deftypefn - -@deftypefn {Built-in Function} {[@var{file_ids}, @var{err}, @var{msg}] =} pipe () -Create a pipe and return the vector @var{file_ids}, which corresponding -to the reading and writing ends of the pipe. - -If successful, @var{err} is 0 and @var{msg} is an empty string. -Otherwise, @var{err} is nonzero and @var{msg} contains a -system-dependent error message. -@end deftypefn - -@deftypefn {Built-in Function} {[@var{fid}, @var{msg}] =} dup2 (@var{old}, @var{new}) -Duplicate a file descriptor. - -If successful, @var{fid} is greater than zero and contains the new file -ID. Otherwise, @var{fid} is negative and @var{msg} contains a -system-dependent error message. -@end deftypefn - -@deftypefn {Built-in Function} {[@var{pid}, @var{msg}] =} waitpid (@var{pid}, @var{options}) -Wait for process @var{pid} to terminate. The @var{pid} argument can be: - -@table @asis -@item @minus{}1 -Wait for any child process. - -@item 0 -Wait for any child process whose process group ID is equal to that of -the Octave interpreter process. - -@item > 0 -Wait for termination of the child process with ID @var{pid}. -@end table - -The @var{options} argument can be: - -@table @asis -@item 0 -Wait until signal is received or a child process exits (this is the -default if the @var{options} argument is missing). - -@item 1 -Do not hang if status is not immediately available. - -@item 2 -Report the status of any child processes that are stopped, and whose -status has not yet been reported since they stopped. - -@item 3 -Implies both 1 and 2. -@end table - -If the returned value of @var{pid} is greater than 0, it is the process -ID of the child process that exited. If an error occurs, @var{pid} will -be less than zero and @var{msg} will contain a system-dependent error -message. -@end deftypefn - -@deftypefn {Built-in Function} {[@var{err}, @var{msg}] =} fcntl (@var{fid}, @var{request}, @var{arg}) -Change the properties of the open file @var{fid}. The following values -may be passed as @var{request}: - -@vtable @code -@item F_DUPFD -Return a duplicate file descriptor. - -@item F_GETFD -Return the file descriptor flags for @var{fid}. - -@item F_SETFD -Set the file descriptor flags for @var{fid}. - -@item F_GETFL -Return the file status flags for @var{fid}. The following codes may be -returned (some of the flags may be undefined on some systems). - -@vtable @code -@item O_RDONLY -Open for reading only. - -@item O_WRONLY -Open for writing only. - -@item O_RDWR -Open for reading and writing. - -@item O_APPEND -Append on each write. - -@item O_NONBLOCK -Nonblocking mode. - -@item O_SYNC -Wait for writes to complete. - -@item O_ASYNC -Asynchronous I/O. -@end vtable - -@item F_SETFL -Set the file status flags for @var{fid} to the value specified by -@var{arg}. The only flags that can be changed are @code{O_APPEND} and -@code{O_NONBLOCK}. -@end vtable - -If successful, @var{err} is 0 and @var{msg} is an empty string. -Otherwise, @var{err} is nonzero and @var{msg} contains a -system-dependent error message. -@end deftypefn - -@node Process ID Information, Environment Variables, Controlling Subprocesses, System Utilities -@section Process, Group, and User IDs - -@deftypefn {Built-in Function} {} getpgrp () -Return the process group id of the current process. -@end deftypefn - -@deftypefn {Built-in Function} {} getpid () -Return the process id of the current process. -@end deftypefn - -@deftypefn {Built-in Function} {} getppid () -Return the process id of the parent process. -@end deftypefn - -@deftypefn {Built-in Function} {} geteuid () -Return the effective user id of the current process. -@end deftypefn - -@deftypefn {Built-in Function} {} getuid () -Return the real user id of the current process. -@end deftypefn - -@deftypefn {Built-in Function} {} getegid () -Return the effective group id of the current process. -@end deftypefn - -@deftypefn {Built-in Function} {} getgid () -Return the real group id of the current process. -@end deftypefn - -@node Environment Variables, Current Working Directory, Process ID Information, System Utilities -@section Environment Variables - -@deftypefn {Built-in Function} {} getenv (@var{var}) -Return the value of the environment variable @var{var}. For example, - -@example -getenv ("PATH") -@end example - -@noindent -returns a string containing the value of your path. -@end deftypefn - -@deftypefn {Built-in Function} {} putenv (@var{var}, @var{value}) -Set the value of the environment variable @var{var} to @var{value}. -@end deftypefn - -@node Current Working Directory, Password Database Functions, Environment Variables, System Utilities -@section Current Working Directory - -@deffn {Command} cd dir -@deffnx {Command} chdir dir -Change the current working directory to @var{dir}. For example, - -@example -cd ~/octave -@end example - -@noindent -Changes the current working directory to @file{~/octave}. If the -directory does not exist, an error message is printed and the working -directory is not changed. -@end deffn - -@deftypefn {Built-in Function} {} pwd () -Return the current working directory. -@end deftypefn - -@deffn {Command} ls options -@deffnx {Command} dir options -List directory contents. For example, - -@example -ls -l - @print{} total 12 - @print{} -rw-r--r-- 1 jwe users 4488 Aug 19 04:02 foo.m - @print{} -rw-r--r-- 1 jwe users 1315 Aug 17 23:14 bar.m -@end example - -The @code{dir} and @code{ls} commands are implemented by calling your -system's directory listing command, so the available options may vary -from system to system. -@end deffn - -@node Password Database Functions, Group Database Functions, Current Working Directory, System Utilities -@section Password Database Functions - -Octave's password database functions return information in a structure -with the following fields. - -@table @code -@item name -The user name. - -@item passwd -The encrypted password, if available. - -@item uid -The numeric user id. - -@item gid -The numeric group id. - -@item gecos -The GECOS field. - -@item dir -The home directory. - -@item shell -The initial shell. -@end table - -In the descriptions of the following functions, this data structure is -referred to as a @var{pw_struct}. - -@deftypefn {Loadable Function} {@var{pw_struct} = } getpwent () -Return a structure containing an entry from the password database, -opening it if necessary. Once the end of the data has been reached, -@code{getpwent} returns 0. -@end deftypefn - -@deftypefn {Loadable Function} {@var{pw_struct} = } getpwuid (@var{uid}). -Return a structure containing the first entry from the password database -with the user ID @var{uid}. If the user ID does not exist in the -database, @code{getpwuid} returns 0. -@end deftypefn - -@deftypefn {Loadable Function} {@var{pw_struct} = } getpwnam (@var{name}) -Return a structure containing the first entry from the password database -with the user name @var{name}. If the user name does not exist in the -database, @code{getpwname} returns 0. -@end deftypefn - -@deftypefn {Loadable Function} {} setpwent () -Return the internal pointer to the beginning of the password database. -@end deftypefn - -@deftypefn {Loadable Function} {} endpwent () -Close the password database. -@end deftypefn - -@node Group Database Functions, System Information, Password Database Functions, System Utilities -@section Group Database Functions - -Octave's group database functions return information in a structure -with the following fields. - -@table @code -@item name -The user name. - -@item passwd -The encrypted password, if available. - -@item gid -The numeric group id. - -@item mem -The members of the group. -@end table - -In the descriptions of the following functions, this data structure is -referred to as a @var{grp_struct}. - -@deftypefn {Loadable Function} {@var{grp_struct} =} getgrent () -Return an entry from the group database, opening it if necessary. -Once the end of the data has been reached, @code{getgrent} returns 0. -@end deftypefn - -@deftypefn {Loadable Function} {@var{grp_struct} =} getgrgid (@var{gid}). -Return the first entry from the group database with the group ID -@var{gid}. If the group ID does not exist in the database, -@code{getgrgid} returns 0. -@end deftypefn - -@deftypefn {Loadable Function} {@var{grp_struct} =} getgrnam (@var{name}) -Return the first entry from the group database with the group name -@var{name}. If the group name does not exist in the database, -@code{getgrname} returns 0. -@end deftypefn - -@deftypefn {Loadable Function} {} setgrent () -Return the internal pointer to the beginning of the group database. -@end deftypefn - -@deftypefn {Loadable Function} {} endgrent () -Close the group database. -@end deftypefn - -@node System Information, , Group Database Functions, System Utilities -@section System Information - -@deftypefn {Built-in Function} {} computer () -Print or return a string of the form @var{cpu}-@var{vendor}-@var{os} -that identifies the kind of computer Octave is running on. If invoked -with an output argument, the value is returned instead of printed. For -example, - -@example -@group -computer () - @print{} i586-pc-linux-gnu - -x = computer () - @result{} x = "i586-pc-linux-gnu" -@end group -@end example -@end deftypefn - -@deftypefn {Built-in Function} {} isieee () -Return 1 if your computer claims to conform to the IEEE standard for -floating point calculations. -@end deftypefn - -@deftypefn {Built-in Function} {} version () -Return Octave's version number as a string. This is also the value of -the built-in variable @code{OCTAVE_VERSION}. -@end deftypefn - -@defvr {Built-in Variable} OCTAVE_VERSION -The version number of Octave, as a string. -@end defvr - -@deftypefn {Built-in Function} {} octave_config_info () -Return a structure containing configuration and installation -information. -@end deftypefn - -@deftypefn {Loadable Function} {} getrusage () -Return a structure containing a number of statistics about the current -Octave process. Not all fields are available on all systems. If it is -not possible to get CPU time statistics, the CPU time slots are set to -zero. Other missing data are replaced by NaN. Here is a list of all -the possible fields that can be present in the structure returned by -@code{getrusage}: - -@table @code -@item -@item idrss -Unshared data size. - -@item inblock -Number of block input operations. - -@item isrss -Unshared stack size. - -@item ixrss -Shared memory size. - -@item majflt -Number of major page faults. - -@item maxrss -Maximum data size. - -@item minflt -Number of minor page faults. - -@item msgrcv -Number of messages received. - -@item msgsnd -Number of messages sent. - -@item nivcsw -Number of involuntary context switches. - -@item nsignals -Number of signals received. - -@item nswap -Number of swaps. - -@item nvcsw -Number of voluntary context switches. - -@item oublock -Number of block output operations. - -@item stime -A structure containing the system CPU time used. The structure has the -elements @code{sec} (seconds) @code{usec} (microseconds). - -@item utime -A structure containing the user CPU time used. The structure has the -elements @code{sec} (seconds) @code{usec} (microseconds). -@end table -@end deftypefn diff --git a/doc/interpreter/system.txi b/doc/interpreter/system.txi new file mode 100644 --- /dev/null +++ b/doc/interpreter/system.txi @@ -0,0 +1,1088 @@ +@c Copyright (C) 1996, 1997 John W. Eaton +@c This is part of the Octave manual. +@c For copying conditions, see the file gpl.texi. + +@node System Utilities, Tips, Audio Processing, Top +@chapter System Utilities + +This chapter describes the functions that are available to allow you to +get information about what is happening outside of Octave, while it is +still running, and use this information in your program. For example, +you can get information about environment variables, the current time, +and even start other programs from the Octave prompt. + +@menu +* Timing Utilities:: +* Filesystem Utilities:: +* Controlling Subprocesses:: +* Process ID Information:: +* Environment Variables:: +* Current Working Directory:: +* Password Database Functions:: +* Group Database Functions:: +* System Information:: +@end menu + +@node Timing Utilities, Filesystem Utilities, System Utilities, System Utilities +@section Timing Utilities + +Octave's core set of functions for manipulating time values are +patterned after the corresponding functions from the standard C library. +Several of these functions use a data structure for time that includes +the following elements: + +@table @code +@item usec +Microseconds after the second (0-999999). + +@item sec +Seconds after the minute (0-61). This number can be 61 to account +for leap seconds. + +@item min +Minutes after the hour (0-59). + +@item hour +Hours since midnight (0-23). + +@item mday +Day of the month (1-31). + +@item mon +Months since January (0-11). + +@item year +Years since 1900. + +@item wday +Days since Sunday (0-6). + +@item yday +Days since January 1 (0-365). + +@item isdst +Daylight Savings Time flag. + +@item zone +Time zone. +@end table + +@noindent +In the descriptions of the following functions, this structure is +referred to as a @var{tm_struct}. + +@deftypefn {Loadable Function} {} time () +Return the current time as the number of seconds since the epoch. The +epoch is referenced to 00:00:00 CUT (Coordinated Universal Time) 1 Jan +1970. For example, on Monday February 17, 1997 at 07:15:06 CUT, the +value returned by @code{time} was 856163706. +@end deftypefn + +@DOCSTRING(ctime) + +@deftypefn {Loadable Function} {} gmtime (@var{t}) +Given a value returned from time (or any nonnegative integer), +return a time structure corresponding to CUT. For example, + +@example +@group +gmtime (time ()) + @result{} @{ + usec = 0 + year = 97 + mon = 1 + mday = 17 + sec = 6 + zone = CST + min = 15 + wday = 1 + hour = 7 + isdst = 0 + yday = 47 + @} +@end group +@end example +@end deftypefn + +@deftypefn {Loadable Function} {} localtime (@var{t}) +Given a value returned from time (or any nonnegative integer), +return a time structure corresponding to the local time zone. + +@example +@group +localtime (time ()) + @result{} @{ + usec = 0 + year = 97 + mon = 1 + mday = 17 + sec = 6 + zone = CST + min = 15 + wday = 1 + hour = 1 + isdst = 0 + yday = 47 + @} +@end group +@end example +@end deftypefn + +@deftypefn {Loadable Function} {} mktime (@var{tm_struct}) +Convert a time structure corresponding to the local time to the number +of seconds since the epoch. For example, + +@example +@group +mktime (localtime (time ()) + @result{} 856163706 +@end group +@end example +@end deftypefn + +@deftypefn {Function File} {} asctime (@var{tm_struct}) +Convert a time structure to a string using the following five-field +format: Thu Mar 28 08:40:14 1996. For example, + +@example +@group +asctime (localtime (time ()) + @result{} "Mon Feb 17 01:15:06 1997\n" +@end group +@end example + +This is equivalent to @code{ctime (time ())}. +@end deftypefn + +@DOCSTRING(strftime) + +Most of the remaining functions described in this section are not +patterned after the standard C library. Some are available for +compatiblity with @sc{Matlab} and others are provided because they are +useful. + +@deftypefn {Function File} {} clock () +Return a vector containing the current year, month (1-12), day (1-31), +hour (0-23), minute (0-59) and second (0-61). For example, + +@example +@group +clock () + @result{} [ 1993, 8, 20, 4, 56, 1 ] +@end group +@end example + +The function clock is more accurate on systems that have the +@code{gettimeofday} function. +@end deftypefn + +@deftypefn {Function File} {} date () +Return the date as a character string in the form DD-MMM-YY. For +example, + +@example +@group +date () + @result{} "20-Aug-93" +@end group +@end example +@end deftypefn + +@deftypefn {Function File} {} etime (@var{t1}, @var{t2}) +Return the difference (in seconds) between two time values returned from +@code{clock}. For example: + +@example +t0 = clock (); +# many computations later... +elapsed_time = etime (clock (), t0); +@end example + +@noindent +will set the variable @code{elapsed_time} to the number of seconds since +the variable @code{t0} was set. +@end deftypefn + +@deftypefn {Built-in Function} {[@var{total}, @var{user}, @var{system}] =} cputime (); +Return the CPU time used by your Octave session. The first output is +the total time spent executing your process and is equal to the sum of +second and third outputs, which are the number of CPU seconds spent +executing in user mode and the number of CPU seconds spent executing in +system mode, respectively. If your system does not have a way to report +CPU time usage, @code{cputime} returns 0 for each of its output values. +Note that because Octave used some CPU time to start, it is reasonable +to check to see if @code{cputime} works by checking to see if the total +CPU time used is nonzero. +@end deftypefn + +@deftypefn {Function File} {} is_leap_year (@var{year}) +Return 1 if the given year is a leap year and 0 otherwise. If no +arguments are provided, @code{is_leap_year} will use the current year. +For example, + +@example +@group +is_leap_year (2000) + @result{} 1 +@end group +@end example +@end deftypefn + +@deftypefn {Function File} {} tic () +@deftypefnx {Function File} {} toc () +These functions set and check a wall-clock timer. For example, + +@example +tic (); +# many computations later... +elapsed_time = toc (); +@end example + +@noindent +will set the variable @code{elapsed_time} to the number of seconds since +the most recent call to the function @code{tic}. + +If you are more interested in the CPU time that your process used, you +should use the @code{cputime} function instead. The @code{tic} and +@code{toc} functions report the actual wall clock time that elapsed +between the calls. This may include time spent processing other jobs or +doing nothing at all. For example, + +@example +@group +tic (); sleep (5); toc () + @result{} 5 +t = cputime (); sleep (5); cputime () - t + @result{} 0 +@end group +@end example + +@noindent +(This example also illustrates that the CPU timer may have a fairly +coarse resolution.) +@end deftypefn + +@deftypefn {Built-in Function} {} pause (@var{seconds}) +Suspend the execution of the program. If invoked without any arguments, +Octave waits until you type a character. With a numeric argument, it +pauses for the given number of seconds. For example, the following +statement prints a message and then waits 5 seconds before clearing the +screen. + +@example +@group +fprintf (stderr, "wait please...\n"); +pause (5); +clc; +@end group +@end example +@end deftypefn + +@deftypefn {Built-in Function} {} sleep (@var{seconds}) +Suspend the execution of the program for the given number of seconds. +@end deftypefn + +@deftypefn {Built-in Function} {} usleep (@var{microseconds}) +Suspend the execution of the program for the given number of +microseconds. On systems where it is not possible to sleep for periods +of time less than one second, @code{usleep} will pause the execution for +@code{round (@var{microseconds} / 1e6)} seconds. +@end deftypefn + +@node Filesystem Utilities, Controlling Subprocesses, Timing Utilities, System Utilities +@section Filesystem Utilities + +Octave includes the following functions for renaming and deleting files, +creating, deleting, and reading directories, and for getting information +about the status of files. + +@deftypefn {Built-in Function} {[@var{err}, @var{msg}] =} rename (@var{old}, @var{new}) +Change the name of file @var{old} to @var{new}. + +If successful, @var{err} is 0 and @var{msg} is an empty string. +Otherwise, @var{err} is nonzero and @var{msg} contains a +system-dependent error message. +@end deftypefn + +@deftypefn {Built-in Function} {[@var{err}, @var{msg}] =} unlink (@var{file}) +Delete @var{file}. + +If successful, @var{err} is 0 and @var{msg} is an empty string. +Otherwise, @var{err} is nonzero and @var{msg} contains a +system-dependent error message. +@end deftypefn + +@deftypefn {Built-in Function} {[@var{files}, @var{err}, @var{msg}] =} readdir (@var{dir}) +Return names of the files in the directory @var{dir} as an array of +strings. If an error occurs, return an empty matrix in @var{files}. + +If successful, @var{err} is 0 and @var{msg} is an empty string. +Otherwise, @var{err} is nonzero and @var{msg} contains a +system-dependent error message. +@end deftypefn + +@deftypefn {Built-in Function} {[@var{err}, @var{msg}] =} mkdir (@var{dir}) +Create a directory named @var{dir}. + +If successful, @var{err} is 0 and @var{msg} is an empty string. +Otherwise, @var{err} is nonzero and @var{msg} contains a +system-dependent error message. +@end deftypefn + +@deftypefn {Built-in Function} {[@var{err}, @var{msg}] =} rmdir (@var{dir}) +Remove the directory named @var{dir}. + +If successful, @var{err} is 0 and @var{msg} is an empty string. +Otherwise, @var{err} is nonzero and @var{msg} contains a +system-dependent error message. +@end deftypefn + +@deftypefn {Built-in Function} {[@var{err}, @var{msg}] =} mkfifo (@var{name}) +Create a FIFO special file. + +If successful, @var{err} is 0 and @var{msg} is an empty string. +Otherwise, @var{err} is nonzero and @var{msg} contains a +system-dependent error message. +@end deftypefn + +@c XXX FIXME XXX -- this needs to be explained, but I don't feel up to +@c it just now... + +@deftypefn {Built-in Function} {} umask (@var{mask}) +Set the permission mask for file creation. The parameter @var{mask} is +interpreted as an octal number. +@end deftypefn + +@deftypefn {Built-in Function} {[@var{info}, @var{err}, @var{msg}] =} stat (@var{file}) +@deftypefnx {Built-in Function} {[@var{info}, @var{err}, @var{msg}] =} lstat (@var{file}) +Return a structure @var{s} containing the following information about +@var{file}. + +@table @code +@item dev +ID of device containing a directory entry for this file. + +@item ino +File number of the file. + +@item modestr +File mode, as a string of ten letters or dashes as would be returned by +@kbd{ls -l}. + +@item nlink +Number of links. + +@item uid +User ID of file's owner. + +@item gid +Group ID of file's group. + +@item rdev +ID of device for block or character special files. + +@item size +Size in bytes. + +@item atime +Time of last access in the same form as time values returned from +@code{time}. @xref{Timing Utilities}. + +@item mtime +Time of last modification in the same form as time values returned from +@code{time}. @xref{Timing Utilities}. + +@item ctime +Time of last file status change in the same form as time values returned from +@code{time}. @xref{Timing Utilities}. + +@item blksize +Size of blocks in the file. + +@item blocks +Number of blocks allocated for file. +@end table + +If the call is successful @var{err} is 0 and @var{msg} is an empty +string. If the file does not exist, or some other error occurs, @var{s} +is an empty matrix, @var{err} is @minus{}1, and @var{msg} contains the +corresponding system error message. + +If @var{file} is a symbolic link, @code{stat} will return information +about the actual file the is referenced by the link. Use @code{lstat} +if you want information about the symbolic link itself. + +For example, + +@example +@group +[s, err, msg] = stat ("/vmlinuz") + @result{} s = + @{ + atime = 855399756 + rdev = 0 + ctime = 847219094 + uid = 0 + size = 389218 + blksize = 4096 + mtime = 847219094 + gid = 6 + nlink = 1 + blocks = 768 + modestr = -rw-r--r-- + ino = 9316 + dev = 2049 + @} + @result{} err = 0 + @result{} msg = +@end group +@end example +@end deftypefn + +@deftypefn {Built-in Function} {} glob (@var{pattern}) +Given an array of strings in @var{pattern}, return the list of file +names that any of them, or an empty string if no patterns match. Tilde +expansion is performed on each of the patterns before looking for +matching file names. For example, + +@example +@group +glob ("/vm*") + @result{} "/vmlinuz" +@end group +@end example + +Note that multiple values are returned in a string matrix with the fill +character set to ASCII NUL. +@end deftypefn + +@deftypefn {Built-in Function} {} fnmatch (@var{pattern}, @var{string}) +Return 1 or zero for each element of @var{string} that matches any of +the elements of the string array @var{pattern}, using the rules of +filename pattern matching. For example, + +@example +@group +fnmatch ("a*b", ["ab"; "axyzb"; "xyzab"]) + @result{} [ 1; 1; 0 ] +@end group +@end example +@end deftypefn + +@deftypefn {Built-in Function} {} file_in_path (@var{path}, @var{file}) +Return the absolute name name of @var{file} if it can be found in +@var{path}. The value of @var{path} should be a colon-separated list of +directories in the format described for the built-in variable +@code{LOADPATH}. + +If the file cannot be found in the path, an empty matrix is returned. +For example, + +@example +file_in_path (LOADPATH, "nargchk.m") + @result{} "@value{OCTAVEHOME}/share/octave/2.0/m/general/nargchk.m" +@end example +@end deftypefn + +@deftypefn {Built-in Function} {} tilde_expand (@var{string}) +Performs tilde expansion on @var{string}. If @var{string} begins with a +tilde character, (@samp{~}), all of the characters preceding the first +slash (or all characters, if there is no slash) are treated as a +possible user name, and the tilde and the following characters up to the +slash are replaced by the home directory of the named user. If the +tilde is followed immediately by a slash, the tilde is replaced by the +home directory of the user running Octave. For example, + +@example +@group +tilde_expand ("~joeuser/bin") + @result{} "/home/joeuser/bin" +tilde_expand ("~/bin") + @result{} "/home/jwe/bin" +@end group +@end example +@end deftypefn + +@node Controlling Subprocesses, Process ID Information, Filesystem Utilities, System Utilities +@section Controlling Subprocesses + +Octave includes some high-level commands like @code{system} and +@code{popen} for starting subprocesses. If you want to run another +program to perform some task and then look at its output, you will +probably want to use these functions. + +Octave also provides several very low-level Unix-like functions which +can also be used for starting subprocesses, but you should probably only +use them if you can't find any way to do what you need with the +higher-level functions. + +@deftypefn {Built-in Function} {} system (@var{string}, @var{return_output}, @var{type}) +Execute a shell command specified by @var{string}. The second argument is optional. +If @var{type} is @code{"async"}, the process is started in the +background and the process id of the child process is returned +immediately. Otherwise, the process is started, and Octave waits until +it exits. If @var{type} argument is omitted, a value of @code{"sync"} +is assumed. + +If two input arguments are given (the actual value of +@var{return_output} is irrelevant) and the subprocess is started +synchronously, or if @var{system} is called with one input argument and +one or more output arguments, the output from the command is returned. +Otherwise, if the subprocess is executed synchronously, it's output is +sent to the standard output. To send the output of a command executed +with @var{system} through the pager, use a command like + +@example +disp (system (cmd, 1)); +@end example + +@noindent +or + +@example +printf ("%s\n", system (cmd, 1)); +@end example + +The @code{system} function can return two values. The first is any +output from the command that was written to the standard output stream, +and the second is the output status of the command. For example, + +@example +[output, status] = system ("echo foo; exit 2"); +@end example + +@noindent +will set the variable @code{output} to the string @samp{foo}, and the +variable @code{status} to the integer @samp{2}. +@end deftypefn + +@deftypefn {Built-in Function} {fid =} popen (@var{command}, @var{mode}) +Start a process and create a pipe. The name of the command to run is +given by @var{command}. The file identifier corresponding to the input +or output stream of the process is returned in @var{fid}. The argument +@var{mode} may be + +@table @code +@item "r" +The pipe will be connected to the standard output of the process, and +open for reading. + +@item "w" +The pipe will be connected to the standard input of the process, and +open for writing. +@end table + +For example, + +@example +@group +fid = popen ("ls -ltr / | tail -3", "r"); +while (isstr (s = fgets (fid))) + fputs (stdout, s); +endwhile + @print{} drwxr-xr-x 33 root root 3072 Feb 15 13:28 etc + @print{} drwxr-xr-x 3 root root 1024 Feb 15 13:28 lib + @print{} drwxrwxrwt 15 root root 2048 Feb 17 14:53 tmp +@end group +@end example +@end deftypefn + +@deftypefn {Built-in Function} {} pclose (@var{fid}) +Close a file identifier that was opened by @code{popen}. You may also +use @code{fclose} for the same purpose. +@end deftypefn + +@deftypefn {Built-in Function} {[@var{in}, @var{out}, @var{pid}] =} popen2 (@var{command}, @var{args}) +Start a subprocess with two-way communication. The name of the process +is given by @var{command}, and @var{args} is an array of strings +containing options for the command. The file identifiers for the input +and output streams of the subprocess are returned in @var{in} and +@var{out}. If execution of the command is successful, @var{pid} +contains the process ID of the subprocess. Otherwise, @var{pid} is +@minus{}1. + +For example, + +@example +@group +[in, out, pid] = popen2 ("sort", "-nr"); +fputs (in, "these\nare\nsome\nstrings\n"); +fclose (in); +while (isstr (s = fgets (out))) + fputs (stdout, s); +endwhile +fclose (out); + @print{} are + @print{} some + @print{} strings + @print{} these +@end group +@end example +@end deftypefn + +@defvr {Built-in Variable} EXEC_PATH +The variable @code{EXEC_PATH} is a colon separated list of directories +to search when executing subprograms. Its initial value is taken from +the environment variable @code{OCTAVE_EXEC_PATH} (if it exists) or +@code{PATH}, but that value can be overridden by the command line +argument @code{--exec-path PATH}, or by setting the value of +@code{EXEC_PATH} in a startup script. If the value of @code{EXEC_PATH} +begins (ends) with a colon, the directories + +@example +@group +@var{octave-home}/libexec/octave/site/exec/@var{arch} +@var{octave-home}/libexec/octave/@var{version}/exec/@var{arch} +@end group +@end example + +@noindent +are prepended (appended) to @code{EXEC_PATH}, where @var{octave-home} +is the top-level directory where all of Octave is installed +(the default value is @file{@value{OCTAVEHOME}}). If you don't specify +a value for @code{EXEC_PATH} explicitly, these special directories are +prepended to your shell path. +@end defvr + +In most cases, the following functions simply decode their arguments and +make the corresponding Unix system calls. For a complete example of how +they can be used, look at the definition of the function @code{popen2}. + +@deftypefn {Built-in Function} {[@var{pid}, @var{msg}] =} fork () +Create a copy of the current process. + +Fork can return one of the following values: + +@table @asis +@item > 0 +You are in the parent process. The value returned from @code{fork} is +the process id of the child process. You should probably arrange to +wait for any child processes to exit. + +@item 0 +You are in the child process. You can call @code{exec} to start another +process. If that fails, you should probably call @code{exit}. + +@item < 0 +The call to @code{fork} failed for some reason. You must take evasive +action. A system dependent error message will be waiting in @var{msg}. +@end table +@end deftypefn + +@deftypefn {Built-in Function} {[@var{err}, @var{msg}] =} exec (@var{file}, @var{args}) +Replace current process with a new process. Calling @code{exec} without +first calling @code{fork} will terminate your current Octave process and +replace it with the program named by @var{file}. For example, + +@example +exec ("ls" "-l") +@end example + +@noindent +will run @code{ls} and return you to your shell prompt. + +If successful, @code{exec} does not return. If @code{exec} does return, +@var{err} will be nonzero, and @var{msg} will contain a system-dependent +error message. +@end deftypefn + +@deftypefn {Built-in Function} {[@var{file_ids}, @var{err}, @var{msg}] =} pipe () +Create a pipe and return the vector @var{file_ids}, which corresponding +to the reading and writing ends of the pipe. + +If successful, @var{err} is 0 and @var{msg} is an empty string. +Otherwise, @var{err} is nonzero and @var{msg} contains a +system-dependent error message. +@end deftypefn + +@deftypefn {Built-in Function} {[@var{fid}, @var{msg}] =} dup2 (@var{old}, @var{new}) +Duplicate a file descriptor. + +If successful, @var{fid} is greater than zero and contains the new file +ID. Otherwise, @var{fid} is negative and @var{msg} contains a +system-dependent error message. +@end deftypefn + +@deftypefn {Built-in Function} {[@var{pid}, @var{msg}] =} waitpid (@var{pid}, @var{options}) +Wait for process @var{pid} to terminate. The @var{pid} argument can be: + +@table @asis +@item @minus{}1 +Wait for any child process. + +@item 0 +Wait for any child process whose process group ID is equal to that of +the Octave interpreter process. + +@item > 0 +Wait for termination of the child process with ID @var{pid}. +@end table + +The @var{options} argument can be: + +@table @asis +@item 0 +Wait until signal is received or a child process exits (this is the +default if the @var{options} argument is missing). + +@item 1 +Do not hang if status is not immediately available. + +@item 2 +Report the status of any child processes that are stopped, and whose +status has not yet been reported since they stopped. + +@item 3 +Implies both 1 and 2. +@end table + +If the returned value of @var{pid} is greater than 0, it is the process +ID of the child process that exited. If an error occurs, @var{pid} will +be less than zero and @var{msg} will contain a system-dependent error +message. +@end deftypefn + +@deftypefn {Built-in Function} {[@var{err}, @var{msg}] =} fcntl (@var{fid}, @var{request}, @var{arg}) +Change the properties of the open file @var{fid}. The following values +may be passed as @var{request}: + +@vtable @code +@item F_DUPFD +Return a duplicate file descriptor. + +@item F_GETFD +Return the file descriptor flags for @var{fid}. + +@item F_SETFD +Set the file descriptor flags for @var{fid}. + +@item F_GETFL +Return the file status flags for @var{fid}. The following codes may be +returned (some of the flags may be undefined on some systems). + +@vtable @code +@item O_RDONLY +Open for reading only. + +@item O_WRONLY +Open for writing only. + +@item O_RDWR +Open for reading and writing. + +@item O_APPEND +Append on each write. + +@item O_NONBLOCK +Nonblocking mode. + +@item O_SYNC +Wait for writes to complete. + +@item O_ASYNC +Asynchronous I/O. +@end vtable + +@item F_SETFL +Set the file status flags for @var{fid} to the value specified by +@var{arg}. The only flags that can be changed are @code{O_APPEND} and +@code{O_NONBLOCK}. +@end vtable + +If successful, @var{err} is 0 and @var{msg} is an empty string. +Otherwise, @var{err} is nonzero and @var{msg} contains a +system-dependent error message. +@end deftypefn + +@node Process ID Information, Environment Variables, Controlling Subprocesses, System Utilities +@section Process, Group, and User IDs + +@deftypefn {Built-in Function} {} getpgrp () +Return the process group id of the current process. +@end deftypefn + +@deftypefn {Built-in Function} {} getpid () +Return the process id of the current process. +@end deftypefn + +@deftypefn {Built-in Function} {} getppid () +Return the process id of the parent process. +@end deftypefn + +@deftypefn {Built-in Function} {} geteuid () +Return the effective user id of the current process. +@end deftypefn + +@deftypefn {Built-in Function} {} getuid () +Return the real user id of the current process. +@end deftypefn + +@deftypefn {Built-in Function} {} getegid () +Return the effective group id of the current process. +@end deftypefn + +@deftypefn {Built-in Function} {} getgid () +Return the real group id of the current process. +@end deftypefn + +@node Environment Variables, Current Working Directory, Process ID Information, System Utilities +@section Environment Variables + +@deftypefn {Built-in Function} {} getenv (@var{var}) +Return the value of the environment variable @var{var}. For example, + +@example +getenv ("PATH") +@end example + +@noindent +returns a string containing the value of your path. +@end deftypefn + +@deftypefn {Built-in Function} {} putenv (@var{var}, @var{value}) +Set the value of the environment variable @var{var} to @var{value}. +@end deftypefn + +@node Current Working Directory, Password Database Functions, Environment Variables, System Utilities +@section Current Working Directory + +@deffn {Command} cd dir +@deffnx {Command} chdir dir +Change the current working directory to @var{dir}. For example, + +@example +cd ~/octave +@end example + +@noindent +Changes the current working directory to @file{~/octave}. If the +directory does not exist, an error message is printed and the working +directory is not changed. +@end deffn + +@deftypefn {Built-in Function} {} pwd () +Return the current working directory. +@end deftypefn + +@deffn {Command} ls options +@deffnx {Command} dir options +List directory contents. For example, + +@example +ls -l + @print{} total 12 + @print{} -rw-r--r-- 1 jwe users 4488 Aug 19 04:02 foo.m + @print{} -rw-r--r-- 1 jwe users 1315 Aug 17 23:14 bar.m +@end example + +The @code{dir} and @code{ls} commands are implemented by calling your +system's directory listing command, so the available options may vary +from system to system. +@end deffn + +@node Password Database Functions, Group Database Functions, Current Working Directory, System Utilities +@section Password Database Functions + +Octave's password database functions return information in a structure +with the following fields. + +@table @code +@item name +The user name. + +@item passwd +The encrypted password, if available. + +@item uid +The numeric user id. + +@item gid +The numeric group id. + +@item gecos +The GECOS field. + +@item dir +The home directory. + +@item shell +The initial shell. +@end table + +In the descriptions of the following functions, this data structure is +referred to as a @var{pw_struct}. + +@deftypefn {Loadable Function} {@var{pw_struct} = } getpwent () +Return a structure containing an entry from the password database, +opening it if necessary. Once the end of the data has been reached, +@code{getpwent} returns 0. +@end deftypefn + +@deftypefn {Loadable Function} {@var{pw_struct} = } getpwuid (@var{uid}). +Return a structure containing the first entry from the password database +with the user ID @var{uid}. If the user ID does not exist in the +database, @code{getpwuid} returns 0. +@end deftypefn + +@deftypefn {Loadable Function} {@var{pw_struct} = } getpwnam (@var{name}) +Return a structure containing the first entry from the password database +with the user name @var{name}. If the user name does not exist in the +database, @code{getpwname} returns 0. +@end deftypefn + +@deftypefn {Loadable Function} {} setpwent () +Return the internal pointer to the beginning of the password database. +@end deftypefn + +@deftypefn {Loadable Function} {} endpwent () +Close the password database. +@end deftypefn + +@node Group Database Functions, System Information, Password Database Functions, System Utilities +@section Group Database Functions + +Octave's group database functions return information in a structure +with the following fields. + +@table @code +@item name +The user name. + +@item passwd +The encrypted password, if available. + +@item gid +The numeric group id. + +@item mem +The members of the group. +@end table + +In the descriptions of the following functions, this data structure is +referred to as a @var{grp_struct}. + +@deftypefn {Loadable Function} {@var{grp_struct} =} getgrent () +Return an entry from the group database, opening it if necessary. +Once the end of the data has been reached, @code{getgrent} returns 0. +@end deftypefn + +@deftypefn {Loadable Function} {@var{grp_struct} =} getgrgid (@var{gid}). +Return the first entry from the group database with the group ID +@var{gid}. If the group ID does not exist in the database, +@code{getgrgid} returns 0. +@end deftypefn + +@deftypefn {Loadable Function} {@var{grp_struct} =} getgrnam (@var{name}) +Return the first entry from the group database with the group name +@var{name}. If the group name does not exist in the database, +@code{getgrname} returns 0. +@end deftypefn + +@deftypefn {Loadable Function} {} setgrent () +Return the internal pointer to the beginning of the group database. +@end deftypefn + +@deftypefn {Loadable Function} {} endgrent () +Close the group database. +@end deftypefn + +@node System Information, , Group Database Functions, System Utilities +@section System Information + +@deftypefn {Built-in Function} {} computer () +Print or return a string of the form @var{cpu}-@var{vendor}-@var{os} +that identifies the kind of computer Octave is running on. If invoked +with an output argument, the value is returned instead of printed. For +example, + +@example +@group +computer () + @print{} i586-pc-linux-gnu + +x = computer () + @result{} x = "i586-pc-linux-gnu" +@end group +@end example +@end deftypefn + +@deftypefn {Built-in Function} {} isieee () +Return 1 if your computer claims to conform to the IEEE standard for +floating point calculations. +@end deftypefn + +@deftypefn {Built-in Function} {} version () +Return Octave's version number as a string. This is also the value of +the built-in variable @code{OCTAVE_VERSION}. +@end deftypefn + +@defvr {Built-in Variable} OCTAVE_VERSION +The version number of Octave, as a string. +@end defvr + +@deftypefn {Built-in Function} {} octave_config_info () +Return a structure containing configuration and installation +information. +@end deftypefn + +@deftypefn {Loadable Function} {} getrusage () +Return a structure containing a number of statistics about the current +Octave process. Not all fields are available on all systems. If it is +not possible to get CPU time statistics, the CPU time slots are set to +zero. Other missing data are replaced by NaN. Here is a list of all +the possible fields that can be present in the structure returned by +@code{getrusage}: + +@table @code +@item +@item idrss +Unshared data size. + +@item inblock +Number of block input operations. + +@item isrss +Unshared stack size. + +@item ixrss +Shared memory size. + +@item majflt +Number of major page faults. + +@item maxrss +Maximum data size. + +@item minflt +Number of minor page faults. + +@item msgrcv +Number of messages received. + +@item msgsnd +Number of messages sent. + +@item nivcsw +Number of involuntary context switches. + +@item nsignals +Number of signals received. + +@item nswap +Number of swaps. + +@item nvcsw +Number of voluntary context switches. + +@item oublock +Number of block output operations. + +@item stime +A structure containing the system CPU time used. The structure has the +elements @code{sec} (seconds) @code{usec} (microseconds). + +@item utime +A structure containing the user CPU time used. The structure has the +elements @code{sec} (seconds) @code{usec} (microseconds). +@end table +@end deftypefn diff --git a/doc/interpreter/tips.texi b/doc/interpreter/tips.texi deleted file mode 100644 --- a/doc/interpreter/tips.texi +++ /dev/null @@ -1,363 +0,0 @@ -@c Copyright (C) 1996, 1997 John W. Eaton -@c This is part of the Octave manual. -@c For copying conditions, see the file gpl.texi. - -@node Tips, Trouble, System Utilities, Top -@appendix Tips and Standards -@cindex tips -@cindex standards of coding style -@cindex coding standards - -This chapter describes no additional features of Octave. Instead it -gives advice on making effective use of the features described in the -previous chapters. - -@menu -* Style Tips:: Writing clean and robust programs. -* Coding Tips:: Making code run faster. -* Documentation Tips:: Writing readable documentation strings. -* Comment Tips:: Conventions for writing comments. -* Function Headers:: Standard headers for functions. -@end menu - -@node Style Tips, Coding Tips, Tips, Tips -@section Writing Clean Octave Programs - -Here are some tips for avoiding common errors in writing Octave code -intended for widespread use: - -@itemize @bullet -@item -Since all global variables share the same name space, and all functions -share another name space, you should choose a short word to distinguish -your program from other Octave programs. Then take care to begin the -names of all global variables, constants, and functions with the chosen -prefix. This helps avoid name conflicts. - -If you write a function that you think ought to be added to Octave under -a certain name, such as @code{fiddle_matrix}, don't call it by that name -in your program. Call it @code{mylib_fiddle_matrix} in your program, -and send mail to @email{bug-octave@@bevo.che.wisc.edu} suggesting that it -be added to Octave. If and when it is, the name can be changed easily -enough. - -If one prefix is insufficient, your package may use two or three -alternative common prefixes, so long as they make sense. - -Separate the prefix from the rest of the symbol name with an underscore -@samp{_}. This will be consistent with Octave itself and with most -Octave programs. - -@item -When you encounter an error condition, call the function @code{error} -(or @code{usage}). The @code{error} and @code{usage} functions do not -return. -@xref{Errors}. - -@item -Please put a copyright notice on the file if you give copies to anyone. -Use the same lines that appear at the top of the function files -distributed with Octave. If you have not signed papers to assign the -copyright to anyone else, then place your name in the copyright notice. -@end itemize - -@node Coding Tips, Documentation Tips, Style Tips, Tips -@section Tips for Making Code Run Faster. -@cindex execution speed -@cindex speedups - -Here are some ways of improving the execution speed of Octave programs. - -@itemize @bullet -@item -Avoid looping wherever possible. - -@item -Use iteration rather than recursion whenever possible. -Function calls are slow in Octave. - -@item -Avoid resizing matrices unnecessarily. When building a single result -matrix from a series of calculations, set the size of the result matrix -first, then insert values into it. Write - -@example -@group -result = zeros (big_n, big_m) -for i = over:and_over - r1 = @dots{} - r2 = @dots{} - result (r1, r2) = new_value (); -endfor -@end group -@end example - -@noindent -instead of - -@example -@group -result = []; -for i = ever:and_ever - result = [ result, new_value() ]; -endfor -@end group -@end example - -@item -Avoid calling @code{eval} or @code{feval} whenever possible, because -they require Octave to parse input or look up the name of a function in -the symbol table. - -If you are using @code{eval} as an exception handling mechanism and not -because you need to execute some arbitrary text, use the @code{try} -statement instead. @xref{The try Statement}. - -@item -If you are calling lots of functions but none of them will need to -change during your run, set the variable -@code{ignore_function_time_stamp} to @code{"all"} so that Octave doesn't -waste a lot of time checking to see if you have updated your function -files. -@end itemize - -@node Documentation Tips, Comment Tips, Coding Tips, Tips -@section Tips for Documentation Strings - -Here are some tips for the writing of documentation strings. - -@itemize @bullet -@item -Every command, function, or variable intended for users to know about -should have a documentation string. - -@item -An internal variable or subroutine of an Octave program might as well have -a documentation string. - -@item -The first line of the documentation string should consist of one or two -complete sentences that stand on their own as a summary. - -The documentation string can have additional lines that expand on the -details of how to use the function or variable. The additional lines -should also be made up of complete sentences. - -@item -For consistency, phrase the verb in the first sentence of a -documentation string as an infinitive with ``to'' omitted. For -instance, use ``Return the frob of A and B.'' in preference to ``Returns -the frob of A and B@.'' Usually it looks good to do likewise for the -rest of the first paragraph. Subsequent paragraphs usually look better -if they have proper subjects. - -@item -Write documentation strings in the active voice, not the passive, and in -the present tense, not the future. For instance, use ``Return a list -containing A and B.'' instead of ``A list containing A and B will be -returned.'' - -@item -Avoid using the word ``cause'' (or its equivalents) unnecessarily. -Instead of, ``Cause Octave to display text in boldface,'' write just -``Display text in boldface.'' - -@item -Do not start or end a documentation string with whitespace. - -@item -Format the documentation string so that it fits in an Emacs window on an -80-column screen. It is a good idea for most lines to be no wider than -60 characters. - -However, rather than simply filling the entire documentation string, you -can make it much more readable by choosing line breaks with care. -Use blank lines between topics if the documentation string is long. - -@item -@strong{Do not} indent subsequent lines of a documentation string so -that the text is lined up in the source code with the text of the first -line. This looks nice in the source code, but looks bizarre when users -view the documentation. Remember that the indentation before the -starting double-quote is not part of the string! - -@item -The documentation string for a variable that is a yes-or-no flag should -start with words such as ``Nonzero means@dots{}'', to make it clear that -all nonzero values are equivalent and indicate explicitly what zero and -nonzero mean. - -@item -When a function's documentation string mentions the value of an argument -of the function, use the argument name in capital letters as if it were -a name for that value. Thus, the documentation string of the operator -@code{/} refers to its second argument as @samp{DIVISOR}, because the -actual argument name is @code{divisor}. - -Also use all caps for meta-syntactic variables, such as when you show -the decomposition of a list or vector into subunits, some of which may -vary. -@end itemize - -@node Comment Tips, Function Headers, Documentation Tips, Tips -@section Tips on Writing Comments - -Here are the conventions to follow when writing comments. - -@table @samp -@item # -Comments that start with a single sharp-sign, @samp{#}, should all be -aligned to the same column on the right of the source code. Such -comments usually explain how the code on the same line does its job. In -the Emacs mode for Octave, the @kbd{M-;} (@code{indent-for-comment}) -command automatically inserts such a @samp{#} in the right place, or -aligns such a comment if it is already present. - -@item ## -Comments that start with two semicolons, @samp{##}, should be aligned to -the same level of indentation as the code. Such comments usually -describe the purpose of the following lines or the state of the program -at that point. -@end table - -@noindent -The indentation commands of the Octave mode in Emacs, such as @kbd{M-;} -(@code{indent-for-comment}) and @kbd{TAB} (@code{octave-indent-line}) -automatically indent comments according to these conventions, -depending on the number of semicolons. @xref{Comments,, -Manipulating Comments, emacs, The GNU Emacs Manual}. - -@node Function Headers, , Comment Tips, Tips -@section Conventional Headers for Octave Functions -@cindex header comments - -Octave has conventions for using special comments in function files -to give information such as who wrote them. This section explains these -conventions. - -The top of the file should contain a copyright notice, followed by a -block of comments that can be used as the help text for the function. -Here is an example: - -@example -## Copyright (C) 1996, 1997 John W. Eaton -## -## This file is part of Octave. -## -## Octave is free software; you can redistribute it and/or -## modify it under the terms of the GNU General Public -## License as published by the Free Software Foundation; -## either version 2, or (at your option) any later version. -## -## Octave is distributed in the hope that it will be useful, -## but WITHOUT ANY WARRANTY; without even the implied -## warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -## PURPOSE. See the GNU General Public License for more -## details. -## -## You should have received a copy of the GNU General Public -## License along with Octave; see the file COPYING. If not, -## write to the Free Software Foundation, 59 Temple Place - -## Suite 330, Boston, MA 02111-1307, USA. - -## usage: [IN, OUT, PID] = popen2 (COMMAND, ARGS) -## -## Start a subprocess with two-way communication. COMMAND -## specifies the name of the command to start. ARGS is an -## array of strings containing options for COMMAND. IN and -## OUT are the file ids of the input and streams for the -## subprocess, and PID is the process id of the subprocess, -## or -1 if COMMAND could not be executed. -## -## Example: -## -## [in, out, pid] = popen2 ("sort", "-nr"); -## fputs (in, "these\nare\nsome\nstrings\n"); -## fclose (in); -## while (isstr (s = fgets (out))) -## fputs (stdout, s); -## endwhile -## fclose (out); -@end example - -Octave uses the first block of comments in a function file that do not -appear to be a copyright notice as the help text for the file. For -Octave to recognize the first comment block as a copyright notice, it -must match the regular expression - -@example -^ Copyright (C).*\n\n This file is part of Octave. -@end example - -@noindent -or - -@example -^ Copyright (C).*\n\n This program is free softwar -@end example - -@noindent -(after stripping the leading comment characters). This is a fairly -strict requirement, and may be relaxed somewhat in the future. - -After the copyright notice and help text come several @dfn{header -comment} lines, each beginning with @samp{## @var{header-name}:}. For -example, - -@example -@group -## Author: jwe -## Keywords: subprocesses input-output -## Maintainer: jwe -@end group -@end example - -Here is a table of the conventional possibilities for @var{header-name}: - -@table @samp -@item Author -This line states the name and net address of at least the principal -author of the library. - -@smallexample -## Author: John W. Eaton -@end smallexample - -@item Maintainer -This line should contain a single name/address as in the Author line, or -an address only, or the string @samp{jwe}. If there is no maintainer -line, the person(s) in the Author field are presumed to be the -maintainers. The example above is mildly bogus because the maintainer -line is redundant. - -The idea behind the @samp{Author} and @samp{Maintainer} lines is to make -possible a function to ``send mail to the maintainer'' without -having to mine the name out by hand. - -Be sure to surround the network address with @samp{<@dots{}>} if -you include the person's full name as well as the network address. - -@item Created -This optional line gives the original creation date of the -file. For historical interest only. - -@item Version -If you wish to record version numbers for the individual Octave program, -put them in this line. - -@item Adapted-By -In this header line, place the name of the person who adapted the -library for installation (to make it fit the style conventions, for -example). - -@item Keywords -This line lists keywords. Eventually, it will be used by an apropos -command to allow people will find your package when they're looking for -things by topic area. To separate the keywords, you can use spaces, -commas, or both. -@end table - -Just about every Octave function ought to have the @samp{Author} and -@samp{Keywords} header comment lines. Use the others if they are -appropriate. You can also put in header lines with other header -names---they have no standard meanings, so they can't do any harm. diff --git a/doc/interpreter/tips.txi b/doc/interpreter/tips.txi new file mode 100644 --- /dev/null +++ b/doc/interpreter/tips.txi @@ -0,0 +1,363 @@ +@c Copyright (C) 1996, 1997 John W. Eaton +@c This is part of the Octave manual. +@c For copying conditions, see the file gpl.texi. + +@node Tips, Trouble, System Utilities, Top +@appendix Tips and Standards +@cindex tips +@cindex standards of coding style +@cindex coding standards + +This chapter describes no additional features of Octave. Instead it +gives advice on making effective use of the features described in the +previous chapters. + +@menu +* Style Tips:: Writing clean and robust programs. +* Coding Tips:: Making code run faster. +* Documentation Tips:: Writing readable documentation strings. +* Comment Tips:: Conventions for writing comments. +* Function Headers:: Standard headers for functions. +@end menu + +@node Style Tips, Coding Tips, Tips, Tips +@section Writing Clean Octave Programs + +Here are some tips for avoiding common errors in writing Octave code +intended for widespread use: + +@itemize @bullet +@item +Since all global variables share the same name space, and all functions +share another name space, you should choose a short word to distinguish +your program from other Octave programs. Then take care to begin the +names of all global variables, constants, and functions with the chosen +prefix. This helps avoid name conflicts. + +If you write a function that you think ought to be added to Octave under +a certain name, such as @code{fiddle_matrix}, don't call it by that name +in your program. Call it @code{mylib_fiddle_matrix} in your program, +and send mail to @email{bug-octave@@bevo.che.wisc.edu} suggesting that it +be added to Octave. If and when it is, the name can be changed easily +enough. + +If one prefix is insufficient, your package may use two or three +alternative common prefixes, so long as they make sense. + +Separate the prefix from the rest of the symbol name with an underscore +@samp{_}. This will be consistent with Octave itself and with most +Octave programs. + +@item +When you encounter an error condition, call the function @code{error} +(or @code{usage}). The @code{error} and @code{usage} functions do not +return. +@xref{Errors}. + +@item +Please put a copyright notice on the file if you give copies to anyone. +Use the same lines that appear at the top of the function files +distributed with Octave. If you have not signed papers to assign the +copyright to anyone else, then place your name in the copyright notice. +@end itemize + +@node Coding Tips, Documentation Tips, Style Tips, Tips +@section Tips for Making Code Run Faster. +@cindex execution speed +@cindex speedups + +Here are some ways of improving the execution speed of Octave programs. + +@itemize @bullet +@item +Avoid looping wherever possible. + +@item +Use iteration rather than recursion whenever possible. +Function calls are slow in Octave. + +@item +Avoid resizing matrices unnecessarily. When building a single result +matrix from a series of calculations, set the size of the result matrix +first, then insert values into it. Write + +@example +@group +result = zeros (big_n, big_m) +for i = over:and_over + r1 = @dots{} + r2 = @dots{} + result (r1, r2) = new_value (); +endfor +@end group +@end example + +@noindent +instead of + +@example +@group +result = []; +for i = ever:and_ever + result = [ result, new_value() ]; +endfor +@end group +@end example + +@item +Avoid calling @code{eval} or @code{feval} whenever possible, because +they require Octave to parse input or look up the name of a function in +the symbol table. + +If you are using @code{eval} as an exception handling mechanism and not +because you need to execute some arbitrary text, use the @code{try} +statement instead. @xref{The try Statement}. + +@item +If you are calling lots of functions but none of them will need to +change during your run, set the variable +@code{ignore_function_time_stamp} to @code{"all"} so that Octave doesn't +waste a lot of time checking to see if you have updated your function +files. +@end itemize + +@node Documentation Tips, Comment Tips, Coding Tips, Tips +@section Tips for Documentation Strings + +Here are some tips for the writing of documentation strings. + +@itemize @bullet +@item +Every command, function, or variable intended for users to know about +should have a documentation string. + +@item +An internal variable or subroutine of an Octave program might as well have +a documentation string. + +@item +The first line of the documentation string should consist of one or two +complete sentences that stand on their own as a summary. + +The documentation string can have additional lines that expand on the +details of how to use the function or variable. The additional lines +should also be made up of complete sentences. + +@item +For consistency, phrase the verb in the first sentence of a +documentation string as an infinitive with ``to'' omitted. For +instance, use ``Return the frob of A and B.'' in preference to ``Returns +the frob of A and B@.'' Usually it looks good to do likewise for the +rest of the first paragraph. Subsequent paragraphs usually look better +if they have proper subjects. + +@item +Write documentation strings in the active voice, not the passive, and in +the present tense, not the future. For instance, use ``Return a list +containing A and B.'' instead of ``A list containing A and B will be +returned.'' + +@item +Avoid using the word ``cause'' (or its equivalents) unnecessarily. +Instead of, ``Cause Octave to display text in boldface,'' write just +``Display text in boldface.'' + +@item +Do not start or end a documentation string with whitespace. + +@item +Format the documentation string so that it fits in an Emacs window on an +80-column screen. It is a good idea for most lines to be no wider than +60 characters. + +However, rather than simply filling the entire documentation string, you +can make it much more readable by choosing line breaks with care. +Use blank lines between topics if the documentation string is long. + +@item +@strong{Do not} indent subsequent lines of a documentation string so +that the text is lined up in the source code with the text of the first +line. This looks nice in the source code, but looks bizarre when users +view the documentation. Remember that the indentation before the +starting double-quote is not part of the string! + +@item +The documentation string for a variable that is a yes-or-no flag should +start with words such as ``Nonzero means@dots{}'', to make it clear that +all nonzero values are equivalent and indicate explicitly what zero and +nonzero mean. + +@item +When a function's documentation string mentions the value of an argument +of the function, use the argument name in capital letters as if it were +a name for that value. Thus, the documentation string of the operator +@code{/} refers to its second argument as @samp{DIVISOR}, because the +actual argument name is @code{divisor}. + +Also use all caps for meta-syntactic variables, such as when you show +the decomposition of a list or vector into subunits, some of which may +vary. +@end itemize + +@node Comment Tips, Function Headers, Documentation Tips, Tips +@section Tips on Writing Comments + +Here are the conventions to follow when writing comments. + +@table @samp +@item # +Comments that start with a single sharp-sign, @samp{#}, should all be +aligned to the same column on the right of the source code. Such +comments usually explain how the code on the same line does its job. In +the Emacs mode for Octave, the @kbd{M-;} (@code{indent-for-comment}) +command automatically inserts such a @samp{#} in the right place, or +aligns such a comment if it is already present. + +@item ## +Comments that start with two semicolons, @samp{##}, should be aligned to +the same level of indentation as the code. Such comments usually +describe the purpose of the following lines or the state of the program +at that point. +@end table + +@noindent +The indentation commands of the Octave mode in Emacs, such as @kbd{M-;} +(@code{indent-for-comment}) and @kbd{TAB} (@code{octave-indent-line}) +automatically indent comments according to these conventions, +depending on the number of semicolons. @xref{Comments,, +Manipulating Comments, emacs, The GNU Emacs Manual}. + +@node Function Headers, , Comment Tips, Tips +@section Conventional Headers for Octave Functions +@cindex header comments + +Octave has conventions for using special comments in function files +to give information such as who wrote them. This section explains these +conventions. + +The top of the file should contain a copyright notice, followed by a +block of comments that can be used as the help text for the function. +Here is an example: + +@example +## Copyright (C) 1996, 1997 John W. Eaton +## +## This file is part of Octave. +## +## Octave is free software; you can redistribute it and/or +## modify it under the terms of the GNU General Public +## License as published by the Free Software Foundation; +## either version 2, or (at your option) any later version. +## +## Octave is distributed in the hope that it will be useful, +## but WITHOUT ANY WARRANTY; without even the implied +## warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +## PURPOSE. See the GNU General Public License for more +## details. +## +## You should have received a copy of the GNU General Public +## License along with Octave; see the file COPYING. If not, +## write to the Free Software Foundation, 59 Temple Place - +## Suite 330, Boston, MA 02111-1307, USA. + +## usage: [IN, OUT, PID] = popen2 (COMMAND, ARGS) +## +## Start a subprocess with two-way communication. COMMAND +## specifies the name of the command to start. ARGS is an +## array of strings containing options for COMMAND. IN and +## OUT are the file ids of the input and streams for the +## subprocess, and PID is the process id of the subprocess, +## or -1 if COMMAND could not be executed. +## +## Example: +## +## [in, out, pid] = popen2 ("sort", "-nr"); +## fputs (in, "these\nare\nsome\nstrings\n"); +## fclose (in); +## while (isstr (s = fgets (out))) +## fputs (stdout, s); +## endwhile +## fclose (out); +@end example + +Octave uses the first block of comments in a function file that do not +appear to be a copyright notice as the help text for the file. For +Octave to recognize the first comment block as a copyright notice, it +must match the regular expression + +@example +^ Copyright (C).*\n\n This file is part of Octave. +@end example + +@noindent +or + +@example +^ Copyright (C).*\n\n This program is free softwar +@end example + +@noindent +(after stripping the leading comment characters). This is a fairly +strict requirement, and may be relaxed somewhat in the future. + +After the copyright notice and help text come several @dfn{header +comment} lines, each beginning with @samp{## @var{header-name}:}. For +example, + +@example +@group +## Author: jwe +## Keywords: subprocesses input-output +## Maintainer: jwe +@end group +@end example + +Here is a table of the conventional possibilities for @var{header-name}: + +@table @samp +@item Author +This line states the name and net address of at least the principal +author of the library. + +@smallexample +## Author: John W. Eaton +@end smallexample + +@item Maintainer +This line should contain a single name/address as in the Author line, or +an address only, or the string @samp{jwe}. If there is no maintainer +line, the person(s) in the Author field are presumed to be the +maintainers. The example above is mildly bogus because the maintainer +line is redundant. + +The idea behind the @samp{Author} and @samp{Maintainer} lines is to make +possible a function to ``send mail to the maintainer'' without +having to mine the name out by hand. + +Be sure to surround the network address with @samp{<@dots{}>} if +you include the person's full name as well as the network address. + +@item Created +This optional line gives the original creation date of the +file. For historical interest only. + +@item Version +If you wish to record version numbers for the individual Octave program, +put them in this line. + +@item Adapted-By +In this header line, place the name of the person who adapted the +library for installation (to make it fit the style conventions, for +example). + +@item Keywords +This line lists keywords. Eventually, it will be used by an apropos +command to allow people will find your package when they're looking for +things by topic area. To separate the keywords, you can use spaces, +commas, or both. +@end table + +Just about every Octave function ought to have the @samp{Author} and +@samp{Keywords} header comment lines. Use the others if they are +appropriate. You can also put in header lines with other header +names---they have no standard meanings, so they can't do any harm. diff --git a/doc/interpreter/var.texi b/doc/interpreter/var.texi deleted file mode 100644 --- a/doc/interpreter/var.texi +++ /dev/null @@ -1,624 +0,0 @@ -@c Copyright (C) 1996, 1997 John W. Eaton -@c This is part of the Octave manual. -@c For copying conditions, see the file gpl.texi. - -@node Variables, Expressions, Data Structures, Top -@chapter Variables -@cindex variables, user-defined -@cindex user-defined variables - -Variables let you give names to values and refer to them later. You have -already seen variables in many of the examples. The name of a variable -must be a sequence of letters, digits and underscores, but it may not begin -with a digit. Octave does not enforce a limit on the length of variable -names, but it is seldom useful to have variables with names longer than -about 30 characters. The following are all valid variable names - -@cindex job hunting -@cindex getting a good job -@cindex flying high and fast -@example -@group -x -x15 -__foo_bar_baz__ -fucnrdthsucngtagdjb -@end group -@end example - -@noindent -However, names like @code{__foo_bar_baz__} that begin and end with two -underscores are understood to be reserved for internal use by Octave. -You should not use them in code you write, except to access Octave's -documented internal variables and built-in symbolic constants. - -Case is significant in variable names. The symbols @code{a} and -@code{A} are distinct variables. - -A variable name is a valid expression by itself. It represents the -variable's current value. Variables are given new values with -@dfn{assignment operators} and @dfn{increment operators}. -@xref{Assignment Ops, ,Assignment Expressions}. - -A number of variables have special built-in meanings. For example, -@code{ans} holds the current working directory, and @code{pi} names the -ratio of the circumference of a circle to its diameter. @xref{Summary of -Built-in Variables}, for a list of all the predefined variables. Some -of these built-in symbols are constants and may not be changed. Others -can be used and assigned just like all other variables, but their values -are also used or changed automatically by Octave. - -Variables in Octave do not have fixed types, so it is possible to first -store a numeric value in a variable and then to later use the same name -to hold a string value in the same program. Variables may not be used -before they have been given a value. Doing so results in an error. - -@menu -* Global Variables:: -* Status of Variables:: -* Summary of Built-in Variables:: -* Defaults from the Environment:: -@end menu - -@node Global Variables, Status of Variables, Variables, Variables -@section Global Variables -@cindex global variables -@cindex @code{global} statement -@cindex variables, global - -A variable that has been declared @dfn{global} may be accessed from -within a function body without having to pass it as a formal parameter. - -A variable may be declared global using a @code{global} declaration -statement. The following statements are all global declarations. - -@example -@group -global a -global b = 2 -global c = 3, d, e = 5 -@end group -@end example - -It is necessary declare a variable as global within a function body in -order to access it. For example, - -@example -@group -global x -function f () - x = 1; -endfunction -f () -@end group -@end example - -@noindent -does @emph{not} set the value of the global variable @code{x} to 1. In -order to change the value of the global variable @code{x}, you must also -declare it to be global within the function body, like this - -@example -@group -function f () - global x; - x = 1; -endfunction -@end group -@end example - -Passing a global variable in a function parameter list will -make a local copy and not modify the global value. For example, given -the function - -@example -@group -function f (x) - x = 0 -endfunction -@end group -@end example - -@noindent -and the definition of @code{x} as a global variable at the top level, - -@example -global x = 13 -@end example - -@noindent -the expression - -@example -f (x) -@end example - -@noindent -will display the value of @code{x} from inside the function as 0, -but the value of @code{x} at the top level remains unchanged, because -the function works with a @emph{copy} of its argument. - -@defvr {Built-in Variable} warn_comma_in_global_decl -If the value of @code{warn_comma_in_global_decl} is nonzero, a -warning is issued for statements like - -@example -global a = 1, b -@end example - -@noindent -which makes the variables @code{a} and @code{b} global and assigns the -value 1 to the variable @code{a}, because in this context, the comma is -not interpreted as a statement separator. - -The default value of @code{warn_comma_in_global_decl} is nonzero. -@end defvr - -@defvr default_global_variable_value -if @code{initialize_global_variables} is nonzero, the value of -@code{default_glbaol_variable_value} is used as the initial value of -global variables that are not explicitly initialized. for example, - -@example -@group -initialize_global_variables = 1; -default_global_variable_value = 13; -global foo; -foo - @result{} 13 -@end group -@end example - -the variable @code{default_global_variable_value} is initially undefined. -@end defvr - -@deftypefn {Built-in Function} {} is_global (@var{name}) -Return 1 if @var{name} is globally visible. Otherwise, return 0. For -example, - -@example -@group -global x -is_global ("x") - @result{} 1 -@end group -@end example -@end deftypefn - -@node Status of Variables, Summary of Built-in Variables, Global Variables, Variables -@section Status of Variables - -@deffn {Command} clear options pattern @dots{} -Delete the names matching the given patterns from the symbol table. The -pattern may contain the following special characters: -@table @code -@item ? -Match any single character. - -@item * -Match zero or more characters. - -@item [ @var{list} ] -Match the list of characters specified by @var{list}. If the first -character is @code{!} or @code{^}, match all characters except those -specified by @var{list}. For example, the pattern @samp{[a-zA-Z]} will -match all lower and upper case alphabetic characters. -@end table - -For example, the command - -@example -clear foo b*r -@end example - -@noindent -clears the name @code{foo} and all names that begin with the letter -@code{b} and end with the letter @code{r}. - -If @code{clear} is called without any arguments, all user-defined -variables (local and global) are cleared from the symbol table. If -@code{clear} is called with at least one argument, only the visible -names matching the arguments are cleared. For example, suppose you have -defined a function @code{foo}, and then hidden it by performing the -assignment @code{foo = 2}. Executing the command @kbd{clear foo} once -will clear the variable definition and restore the definition of -@code{foo} as a function. Executing @kbd{clear foo} a second time will -clear the function definition. - -This command may not be used within a function body. -@end deffn - -@deffn {Command} who options pattern @dots{} -@deffnx {Command} whos options pattern @dots{} -List currently defined symbols matching the given patterns. The -following are valid options. They may be shortened to one character but -may not be combined. - -@table @code -@item -all -List all currently defined symbols. - -@item -builtins -List built-in variables and functions. This includes all currently -compiled function files, but does not include all function files that -are in the @code{LOADPATH}. - -@item -functions -List user-defined functions. - -@item -long -Print a long listing including the type and dimensions of any symbols. -The symbols in the first column of output indicate whether it is -possible to redefine the symbol, and whether it is possible for it to be -cleared. - -@item -variables -List user-defined variables. -@end table - -Valid patterns are the same as described for the @code{clear} command -above. If no patterns are supplied, all symbols from the given category -are listed. By default, only user defined functions and variables -visible in the local scope are displayed. - -The command @kbd{whos} is equivalent to @kbd{who -long}. -@end deffn - -@deftypefn {Built-in Function} {} exist (@var{name}) -Return 1 if the name exists as a variable, 2 if the name (after -appending @samp{.m}) is a function file in the path, 3 if the name is a -@samp{.oct} file in the path, or 5 if the name is a built-in function. -Otherwise, return 0. -@end deftypefn - -@deftypefn {Built-in Function} {} document (@var{symbol}, @var{text}) -Set the documentation string for @var{symbol} to @var{text}. -@end deftypefn - -@deffn {Command} type options name @dots{} -Display the definition of each @var{name} that refers to a function. - -Normally also displays if each @var{name} is user-defined or builtin; -the @code{-q} option suppresses this behaviour. - -Currently, Octave can only display functions that can be compiled -cleanly, because it uses its internal representation of the function to -recreate the program text. - -Comments are not displayed because Octave's parser currently discards -them as it converts the text of a function file to its internal -representation. This problem may be fixed in a future release. -@end deffn - -@deffn {Command} which name @dots{} -Display the type of each @var{name}. If @var{name} is defined from a -function file, the full name of the file is also displayed. -@end deffn - -@node Summary of Built-in Variables, Defaults from the Environment, Status of Variables, Variables -@section Summary of Built-in Variables - -Here is a summary of all of Octave's built-in variables along with -cross references to additional information and their default values. In -the following table @var{octave-home} stands for the root directory -where all of Octave is installed (the default is @file{@value{OCTAVEHOME}}, -@var{version} stands for the Octave version number (for example, -@value{VERSION}) and @var{arch} stands for the type of system for which -Octave was compiled (for example, @code{@value{TARGETHOSTTYPE}}). - -@vtable @code -@item DEFAULT_LOADPATH -@xref{Function Files}. - -Default value: @code{".:@var{octave-home}/lib/@var{version}"}. - -@item EDITOR -@xref{Commands For History}. - -Default value: @code{"emacs"}. - -@item EXEC_PATH -@xref{Controlling Subprocesses}. - -Default value: @code{":$PATH"}. - -@item INFO_FILE -@xref{Getting Help}. - -Default value: @code{"@var{octave-home}/info/octave.info"}. - -@item INFO_PROGRAM -@xref{Getting Help}. - -Default value: @code{"@var{octave-home}/libexec/octave/@var{version}/exec/@var{arch}/info"}. - -@item LOADPATH -@xref{Function Files}. - -Default value: @code{":"}, which tells Octave to use the directories -specified by the built-in variable @code{DEFAULT_LOADPATH}. - -@item OCTAVE_HOME - -Default value: @code{"@value{OCTAVEHOME}"}. - -@item PAGER -@xref{Input and Output}. - -Default value: @code{"less", or "more"}. - -@item PS1 -@xref{Customizing the Prompt}. - -Default value: @code{"\s:\#> "}. - -@item PS2 -@xref{Customizing the Prompt}. - -Default value: @code{"> "}. - -@item PS4 -@xref{Customizing the Prompt}. - -Default value: @code{"+ "}. - -@item auto_unload_dot_oct_files -@xref{Dynamically Linked Functions}. - -Default value: 0. - -@item automatic_replot -@xref{Two-Dimensional Plotting}. - -Default value: 0. - -@item beep_on_error -@xref{Error Handling}. - -Default value: 0. - -@item completion_append_char -@xref{Commands For Completion}. - -Default value: @code{" "}. - -@item default_eval_print_flag -@xref{Evaluation}. - -Default value: 1. - -@item default_return_value -@xref{Multiple Return Values}. - -Default value: @code{[]}. - -@item default_save_format -@xref{Simple File I/O}. - -Default value: @code{"ascii"}. - -@item do_fortran_indexing -@xref{Index Expressions}. - -Default value: 0. - -@item crash_dumps_octave_core -@xref{Simple File I/O}. - -Default value: 1. - -@item define_all_return_values -@xref{Multiple Return Values}. - -Default value: 0. - -@item empty_list_elements_ok -@xref{Empty Matrices}. - -Default value: @code{"warn"}. - -@item fixed_point_format -@xref{Matrices}. - -Default value: 0. - -@item gnuplot_binary -@xref{Three-Dimensional Plotting}. - -Default value: @code{"gnuplot"}. - -@item history_file -@xref{Commands For History}. - -Default value: @code{"~/.octave_hist"}. - -@item history_size -@xref{Commands For History}. - -Default value: 1024. - -@item ignore_function_time_stamp -@xref{Function Files}. - -Default value: @code{"system"}. - -@item implicit_num_to_str_ok -@xref{String Conversions}. - -Default value: 0. - -@item implicit_str_to_num_ok -@xref{String Conversions}. - -Default value: 0. - -@item max_recursion_depth -@xref{Recursion}. - -Default value: 256. - -@item ok_to_lose_imaginary_part -@xref{Special Utility Matrices}. - -Default value: @code{"warn"}. - -@item output_max_field_width -@xref{Matrices}. - -Default value: 10. - -@item output_precision -@xref{Matrices}. - -Default value: 5. - -@item page_screen_output -@xref{Input and Output}. - -Default value: 1. - -@item prefer_column_vectors -@xref{Index Expressions}. - -Default value: 1. - -@item print_answer_id_name -@xref{Terminal Output}. - -Default value: 1. - -@item print_empty_dimensions -@xref{Empty Matrices}. - -Default value: 1. - -@item resize_on_range_error -@xref{Index Expressions}. - -Default value: 1. - -@item return_last_computed_value -@xref{Returning From a Function}. - -Default value: 0. - -@item save_precision -@xref{Simple File I/O}. - -Default value: 17. - -@item saving_history -@xref{Commands For History}. - -Default value: 1. - -@item silent_functions -@xref{Defining Functions}. - -Default value: 0. - -@item split_long_rows -@xref{Matrices}. - -Default value: 1. - -@item struct_levels_to_print -@xref{Data Structures}. - -Default value: 2. - -@item suppress_verbose_help_message -@xref{Getting Help}. - -Default value: 1. - -@item treat_neg_dim_as_zero -@xref{Special Utility Matrices}. - -Default value: 0. - -@item warn_assign_as_truth_value -@xref{The if Statement}. - -Default value: 1. - -@item warn_comma_in_global_decl -@xref{Global Variables}. - -Default value: 1. - -@item warn_divide_by_zero -@xref{Arithmetic Ops}. - -Default value: 1. - -@item warn_function_name_clash -@xref{Function Files}. - -Default value: 1. - -@item warn_reload_forces_clear -@xref{Dynamically Linked Functions}. - -Default value: 1. - -@item warn_variable_switch_label -@xref{The switch Statement}. - -Default value: 0. - -@item whitespace_in_literal_matrix -@xref{Matrices}. - -Default value: @code{""}. -@end vtable - - -@node Defaults from the Environment, , Summary of Built-in Variables, Variables -@section Defaults from the Environment - -Octave uses the values of the following environment variables to set the -default values for the corresponding built-in variables. In addition, -the values from the environment may be overridden by command-line -arguments. @xref{Command Line Options}. - -@vtable @code -@item EDITOR -@xref{Commands For History}. - -Built-in variable: @code{EDITOR}. - -@item OCTAVE_EXEC_PATH -@xref{Controlling Subprocesses}. - -Built-in variable: @code{EXEC_PATH}. -Command-line argument: @code{--exec-path}. - -@item OCTAVE_PATH -@xref{Function Files}. - -Built-in variable: @code{LOADPATH}. -Command-line argument: @code{--path}. - -@item OCTAVE_INFO_FILE -@xref{Getting Help}. - -Built-in variable: @code{INFO_FILE}. -Command-line argument: @code{--info-file}. - -@item OCTAVE_INFO_PROGRAM -@xref{Getting Help}. - -Built-in variable: @code{INFO_PROGRAM}. -Command-line argument: @code{--info-program}. - -@item OCTAVE_HISTSIZE -@xref{Commands For History}. - -Built-in variable: @code{history_size}. - -@item OCTAVE_HISTFILE -@xref{Commands For History}. - -Built-in variable: @code{history_file}. -@end vtable diff --git a/doc/interpreter/var.txi b/doc/interpreter/var.txi new file mode 100644 --- /dev/null +++ b/doc/interpreter/var.txi @@ -0,0 +1,624 @@ +@c Copyright (C) 1996, 1997 John W. Eaton +@c This is part of the Octave manual. +@c For copying conditions, see the file gpl.texi. + +@node Variables, Expressions, Data Structures, Top +@chapter Variables +@cindex variables, user-defined +@cindex user-defined variables + +Variables let you give names to values and refer to them later. You have +already seen variables in many of the examples. The name of a variable +must be a sequence of letters, digits and underscores, but it may not begin +with a digit. Octave does not enforce a limit on the length of variable +names, but it is seldom useful to have variables with names longer than +about 30 characters. The following are all valid variable names + +@cindex job hunting +@cindex getting a good job +@cindex flying high and fast +@example +@group +x +x15 +__foo_bar_baz__ +fucnrdthsucngtagdjb +@end group +@end example + +@noindent +However, names like @code{__foo_bar_baz__} that begin and end with two +underscores are understood to be reserved for internal use by Octave. +You should not use them in code you write, except to access Octave's +documented internal variables and built-in symbolic constants. + +Case is significant in variable names. The symbols @code{a} and +@code{A} are distinct variables. + +A variable name is a valid expression by itself. It represents the +variable's current value. Variables are given new values with +@dfn{assignment operators} and @dfn{increment operators}. +@xref{Assignment Ops, ,Assignment Expressions}. + +A number of variables have special built-in meanings. For example, +@code{ans} holds the current working directory, and @code{pi} names the +ratio of the circumference of a circle to its diameter. @xref{Summary of +Built-in Variables}, for a list of all the predefined variables. Some +of these built-in symbols are constants and may not be changed. Others +can be used and assigned just like all other variables, but their values +are also used or changed automatically by Octave. + +Variables in Octave do not have fixed types, so it is possible to first +store a numeric value in a variable and then to later use the same name +to hold a string value in the same program. Variables may not be used +before they have been given a value. Doing so results in an error. + +@menu +* Global Variables:: +* Status of Variables:: +* Summary of Built-in Variables:: +* Defaults from the Environment:: +@end menu + +@node Global Variables, Status of Variables, Variables, Variables +@section Global Variables +@cindex global variables +@cindex @code{global} statement +@cindex variables, global + +A variable that has been declared @dfn{global} may be accessed from +within a function body without having to pass it as a formal parameter. + +A variable may be declared global using a @code{global} declaration +statement. The following statements are all global declarations. + +@example +@group +global a +global b = 2 +global c = 3, d, e = 5 +@end group +@end example + +It is necessary declare a variable as global within a function body in +order to access it. For example, + +@example +@group +global x +function f () + x = 1; +endfunction +f () +@end group +@end example + +@noindent +does @emph{not} set the value of the global variable @code{x} to 1. In +order to change the value of the global variable @code{x}, you must also +declare it to be global within the function body, like this + +@example +@group +function f () + global x; + x = 1; +endfunction +@end group +@end example + +Passing a global variable in a function parameter list will +make a local copy and not modify the global value. For example, given +the function + +@example +@group +function f (x) + x = 0 +endfunction +@end group +@end example + +@noindent +and the definition of @code{x} as a global variable at the top level, + +@example +global x = 13 +@end example + +@noindent +the expression + +@example +f (x) +@end example + +@noindent +will display the value of @code{x} from inside the function as 0, +but the value of @code{x} at the top level remains unchanged, because +the function works with a @emph{copy} of its argument. + +@defvr {Built-in Variable} warn_comma_in_global_decl +If the value of @code{warn_comma_in_global_decl} is nonzero, a +warning is issued for statements like + +@example +global a = 1, b +@end example + +@noindent +which makes the variables @code{a} and @code{b} global and assigns the +value 1 to the variable @code{a}, because in this context, the comma is +not interpreted as a statement separator. + +The default value of @code{warn_comma_in_global_decl} is nonzero. +@end defvr + +@defvr default_global_variable_value +if @code{initialize_global_variables} is nonzero, the value of +@code{default_glbaol_variable_value} is used as the initial value of +global variables that are not explicitly initialized. for example, + +@example +@group +initialize_global_variables = 1; +default_global_variable_value = 13; +global foo; +foo + @result{} 13 +@end group +@end example + +the variable @code{default_global_variable_value} is initially undefined. +@end defvr + +@deftypefn {Built-in Function} {} is_global (@var{name}) +Return 1 if @var{name} is globally visible. Otherwise, return 0. For +example, + +@example +@group +global x +is_global ("x") + @result{} 1 +@end group +@end example +@end deftypefn + +@node Status of Variables, Summary of Built-in Variables, Global Variables, Variables +@section Status of Variables + +@deffn {Command} clear options pattern @dots{} +Delete the names matching the given patterns from the symbol table. The +pattern may contain the following special characters: +@table @code +@item ? +Match any single character. + +@item * +Match zero or more characters. + +@item [ @var{list} ] +Match the list of characters specified by @var{list}. If the first +character is @code{!} or @code{^}, match all characters except those +specified by @var{list}. For example, the pattern @samp{[a-zA-Z]} will +match all lower and upper case alphabetic characters. +@end table + +For example, the command + +@example +clear foo b*r +@end example + +@noindent +clears the name @code{foo} and all names that begin with the letter +@code{b} and end with the letter @code{r}. + +If @code{clear} is called without any arguments, all user-defined +variables (local and global) are cleared from the symbol table. If +@code{clear} is called with at least one argument, only the visible +names matching the arguments are cleared. For example, suppose you have +defined a function @code{foo}, and then hidden it by performing the +assignment @code{foo = 2}. Executing the command @kbd{clear foo} once +will clear the variable definition and restore the definition of +@code{foo} as a function. Executing @kbd{clear foo} a second time will +clear the function definition. + +This command may not be used within a function body. +@end deffn + +@deffn {Command} who options pattern @dots{} +@deffnx {Command} whos options pattern @dots{} +List currently defined symbols matching the given patterns. The +following are valid options. They may be shortened to one character but +may not be combined. + +@table @code +@item -all +List all currently defined symbols. + +@item -builtins +List built-in variables and functions. This includes all currently +compiled function files, but does not include all function files that +are in the @code{LOADPATH}. + +@item -functions +List user-defined functions. + +@item -long +Print a long listing including the type and dimensions of any symbols. +The symbols in the first column of output indicate whether it is +possible to redefine the symbol, and whether it is possible for it to be +cleared. + +@item -variables +List user-defined variables. +@end table + +Valid patterns are the same as described for the @code{clear} command +above. If no patterns are supplied, all symbols from the given category +are listed. By default, only user defined functions and variables +visible in the local scope are displayed. + +The command @kbd{whos} is equivalent to @kbd{who -long}. +@end deffn + +@deftypefn {Built-in Function} {} exist (@var{name}) +Return 1 if the name exists as a variable, 2 if the name (after +appending @samp{.m}) is a function file in the path, 3 if the name is a +@samp{.oct} file in the path, or 5 if the name is a built-in function. +Otherwise, return 0. +@end deftypefn + +@deftypefn {Built-in Function} {} document (@var{symbol}, @var{text}) +Set the documentation string for @var{symbol} to @var{text}. +@end deftypefn + +@deffn {Command} type options name @dots{} +Display the definition of each @var{name} that refers to a function. + +Normally also displays if each @var{name} is user-defined or builtin; +the @code{-q} option suppresses this behaviour. + +Currently, Octave can only display functions that can be compiled +cleanly, because it uses its internal representation of the function to +recreate the program text. + +Comments are not displayed because Octave's parser currently discards +them as it converts the text of a function file to its internal +representation. This problem may be fixed in a future release. +@end deffn + +@deffn {Command} which name @dots{} +Display the type of each @var{name}. If @var{name} is defined from a +function file, the full name of the file is also displayed. +@end deffn + +@node Summary of Built-in Variables, Defaults from the Environment, Status of Variables, Variables +@section Summary of Built-in Variables + +Here is a summary of all of Octave's built-in variables along with +cross references to additional information and their default values. In +the following table @var{octave-home} stands for the root directory +where all of Octave is installed (the default is @file{@value{OCTAVEHOME}}, +@var{version} stands for the Octave version number (for example, +@value{VERSION}) and @var{arch} stands for the type of system for which +Octave was compiled (for example, @code{@value{TARGETHOSTTYPE}}). + +@vtable @code +@item DEFAULT_LOADPATH +@xref{Function Files}. + +Default value: @code{".:@var{octave-home}/lib/@var{version}"}. + +@item EDITOR +@xref{Commands For History}. + +Default value: @code{"emacs"}. + +@item EXEC_PATH +@xref{Controlling Subprocesses}. + +Default value: @code{":$PATH"}. + +@item INFO_FILE +@xref{Getting Help}. + +Default value: @code{"@var{octave-home}/info/octave.info"}. + +@item INFO_PROGRAM +@xref{Getting Help}. + +Default value: @code{"@var{octave-home}/libexec/octave/@var{version}/exec/@var{arch}/info"}. + +@item LOADPATH +@xref{Function Files}. + +Default value: @code{":"}, which tells Octave to use the directories +specified by the built-in variable @code{DEFAULT_LOADPATH}. + +@item OCTAVE_HOME + +Default value: @code{"@value{OCTAVEHOME}"}. + +@item PAGER +@xref{Input and Output}. + +Default value: @code{"less", or "more"}. + +@item PS1 +@xref{Customizing the Prompt}. + +Default value: @code{"\s:\#> "}. + +@item PS2 +@xref{Customizing the Prompt}. + +Default value: @code{"> "}. + +@item PS4 +@xref{Customizing the Prompt}. + +Default value: @code{"+ "}. + +@item auto_unload_dot_oct_files +@xref{Dynamically Linked Functions}. + +Default value: 0. + +@item automatic_replot +@xref{Two-Dimensional Plotting}. + +Default value: 0. + +@item beep_on_error +@xref{Error Handling}. + +Default value: 0. + +@item completion_append_char +@xref{Commands For Completion}. + +Default value: @code{" "}. + +@item default_eval_print_flag +@xref{Evaluation}. + +Default value: 1. + +@item default_return_value +@xref{Multiple Return Values}. + +Default value: @code{[]}. + +@item default_save_format +@xref{Simple File I/O}. + +Default value: @code{"ascii"}. + +@item do_fortran_indexing +@xref{Index Expressions}. + +Default value: 0. + +@item crash_dumps_octave_core +@xref{Simple File I/O}. + +Default value: 1. + +@item define_all_return_values +@xref{Multiple Return Values}. + +Default value: 0. + +@item empty_list_elements_ok +@xref{Empty Matrices}. + +Default value: @code{"warn"}. + +@item fixed_point_format +@xref{Matrices}. + +Default value: 0. + +@item gnuplot_binary +@xref{Three-Dimensional Plotting}. + +Default value: @code{"gnuplot"}. + +@item history_file +@xref{Commands For History}. + +Default value: @code{"~/.octave_hist"}. + +@item history_size +@xref{Commands For History}. + +Default value: 1024. + +@item ignore_function_time_stamp +@xref{Function Files}. + +Default value: @code{"system"}. + +@item implicit_num_to_str_ok +@xref{String Conversions}. + +Default value: 0. + +@item implicit_str_to_num_ok +@xref{String Conversions}. + +Default value: 0. + +@item max_recursion_depth +@xref{Recursion}. + +Default value: 256. + +@item ok_to_lose_imaginary_part +@xref{Special Utility Matrices}. + +Default value: @code{"warn"}. + +@item output_max_field_width +@xref{Matrices}. + +Default value: 10. + +@item output_precision +@xref{Matrices}. + +Default value: 5. + +@item page_screen_output +@xref{Input and Output}. + +Default value: 1. + +@item prefer_column_vectors +@xref{Index Expressions}. + +Default value: 1. + +@item print_answer_id_name +@xref{Terminal Output}. + +Default value: 1. + +@item print_empty_dimensions +@xref{Empty Matrices}. + +Default value: 1. + +@item resize_on_range_error +@xref{Index Expressions}. + +Default value: 1. + +@item return_last_computed_value +@xref{Returning From a Function}. + +Default value: 0. + +@item save_precision +@xref{Simple File I/O}. + +Default value: 17. + +@item saving_history +@xref{Commands For History}. + +Default value: 1. + +@item silent_functions +@xref{Defining Functions}. + +Default value: 0. + +@item split_long_rows +@xref{Matrices}. + +Default value: 1. + +@item struct_levels_to_print +@xref{Data Structures}. + +Default value: 2. + +@item suppress_verbose_help_message +@xref{Getting Help}. + +Default value: 1. + +@item treat_neg_dim_as_zero +@xref{Special Utility Matrices}. + +Default value: 0. + +@item warn_assign_as_truth_value +@xref{The if Statement}. + +Default value: 1. + +@item warn_comma_in_global_decl +@xref{Global Variables}. + +Default value: 1. + +@item warn_divide_by_zero +@xref{Arithmetic Ops}. + +Default value: 1. + +@item warn_function_name_clash +@xref{Function Files}. + +Default value: 1. + +@item warn_reload_forces_clear +@xref{Dynamically Linked Functions}. + +Default value: 1. + +@item warn_variable_switch_label +@xref{The switch Statement}. + +Default value: 0. + +@item whitespace_in_literal_matrix +@xref{Matrices}. + +Default value: @code{""}. +@end vtable + + +@node Defaults from the Environment, , Summary of Built-in Variables, Variables +@section Defaults from the Environment + +Octave uses the values of the following environment variables to set the +default values for the corresponding built-in variables. In addition, +the values from the environment may be overridden by command-line +arguments. @xref{Command Line Options}. + +@vtable @code +@item EDITOR +@xref{Commands For History}. + +Built-in variable: @code{EDITOR}. + +@item OCTAVE_EXEC_PATH +@xref{Controlling Subprocesses}. + +Built-in variable: @code{EXEC_PATH}. +Command-line argument: @code{--exec-path}. + +@item OCTAVE_PATH +@xref{Function Files}. + +Built-in variable: @code{LOADPATH}. +Command-line argument: @code{--path}. + +@item OCTAVE_INFO_FILE +@xref{Getting Help}. + +Built-in variable: @code{INFO_FILE}. +Command-line argument: @code{--info-file}. + +@item OCTAVE_INFO_PROGRAM +@xref{Getting Help}. + +Built-in variable: @code{INFO_PROGRAM}. +Command-line argument: @code{--info-program}. + +@item OCTAVE_HISTSIZE +@xref{Commands For History}. + +Built-in variable: @code{history_size}. + +@item OCTAVE_HISTFILE +@xref{Commands For History}. + +Built-in variable: @code{history_file}. +@end vtable diff --git a/doc/interpreter/vr-idx.texi b/doc/interpreter/vr-idx.texi deleted file mode 100644 --- a/doc/interpreter/vr-idx.texi +++ /dev/null @@ -1,8 +0,0 @@ -@c Copyright (C) 1996, 1997 John W. Eaton -@c This is part of the Octave manual. -@c For copying conditions, see the file gpl.texi. - -@node Variable Index, Function Index, Concept Index, Top -@unnumbered Variable Index - -@printindex vr diff --git a/doc/interpreter/vr-idx.txi b/doc/interpreter/vr-idx.txi new file mode 100644 --- /dev/null +++ b/doc/interpreter/vr-idx.txi @@ -0,0 +1,8 @@ +@c Copyright (C) 1996, 1997 John W. Eaton +@c This is part of the Octave manual. +@c For copying conditions, see the file gpl.texi. + +@node Variable Index, Function Index, Concept Index, Top +@unnumbered Variable Index + +@printindex vr