This is Info file octave, produced by Makeinfo-1.64 from the input file
octave.tex.

START-INFO-DIR-ENTRY
* Octave: (octave).     Interactive language for numerical computations.
END-INFO-DIR-ENTRY

   Copyright (C) 1996 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.

   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.


File: octave,  Node: C-Style I/O Functions,  Prev: Basic Input and Output,  Up: Input and Output

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, FILE refers either to an integer file number (as
returned by `fopen') or a file name.

   There are three files that are always available:

 - Built-in Variable: stdin
     The standard input stream (file number 0).  When Octave is used
     interactively, this is filtered through the command line editing
     functions.

 - Built-in Variable: stdout
     The standard output stream (file number 1).  Data written to the
     standard output is normally filtered through the pager.

 - Built-in Variable: stderr
     The standard error stream (file number 2).  Even if paging is
     turned on, the standard error is not sent to the pager.  It is
     useful for error messages and prompts.

   You should always use the symbolic names given in the table above,
rather than referring to these files by number, since it will make your
programs clearer.

* Menu:

* Opening and Closing Files::
* Formatted Output::
* Output Conversion Syntax::
* Table of Output Conversions::
* Integer Conversions::
* Floating-Point Conversions::
* Other Output Conversions::
* Formatted Input::
* Input Conversion Syntax::
* Table of Input Conversions::
* Numeric Input Conversions::
* String Input Conversions::
* Binary I/O::
* Other I/O Functions::


File: octave,  Node: Opening and Closing Files,  Next: Formatted Output,  Prev: C-Style I/O Functions,  Up: C-Style I/O Functions

Opening and Closing Files
-------------------------

 - Built-in Function: fid = fopen (NAME, MODE)
     Opens the named file with the specified mode.  Returns an integer
     value that may be used to refer to the file later.  The MODE is a
     one or two character string that specifies whether the file is to
     be opened for reading, writing, or both.  For example,

          myfile = fopen ("splat.dat", "r");

     opens the file `splat.dat' for reading.  Opening a file that is
     already open has no effect.

     The possible values `mode' may have are

    `r'
          Open a file for reading.

    `w'
          Open a file for writing.  The previous contents are discared.

    `a'
          Open or create a file for writing at the end of the file.

    `r+'
          Open an existing file for reading and writing.

    `w+'
          Open a file for reading or writing.  The previous contents are
          discared.

    `a+'
          Open or create a file for reading or writing at the end of the
          file.

 - Built-in Function:  fclose (FID)
     Closes the specified file.  If an error is encountered while
     trying to close the file, an error message is printed and `fclose'
     returns 0.  Otherwise, it returns 1.


File: octave,  Node: Formatted Output,  Next: Output Conversion Syntax,  Prev: Opening and Closing Files,  Up: C-Style I/O Functions

Formatted Output
----------------

   This section describes how to call `printf' and related functions.

   The following functions are available for formatted output.  They are
modelled after the C language functions of the same name.

 - Function File:  printf (TEMPLATE, ...)
     The `printf' function prints the optional arguments under the
     control of the template string TEMPLATE to the stream `stdout'.

 - Built-in Function:  fprintf (FID, TEMPLATE, ...)
     This function is just like `printf', except that the output is
     written to the stream FID instead of `stdout'.

 - Built-in Function:  sprintf (TEMPLATE, ...)
     This is like `printf', except that the output is written to a
     string.  Unlike the C library function, which requires you to
     provide a suitably sized string as an argument, Octave's `sprintf'
     function returns the string, automatically sized to hold all of
     the items converted.

   The `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 "conversion specifications" introduced by a
`%' character in the template cause subsequent arguments to be
formatted and written to the output stream.  For example,

     pct = 37;
     filename = "foo.txt";
     printf ("Processing of `%s' is %d%% finished.\nPlease be patient.\n",
             filename, pct);

produces output like

     Processing of `foo.txt' is 37% finished.
     Please be patient.

   This example shows the use of the `%d' conversion to specify that a
scalar argument should be printed in decimal notation, the `%s'
conversion to specify printing of a string argument, and the `%%'
conversion to print a literal `%' character.

   There are also conversions for printing an integer argument as an
unsigned value in octal, decimal, or hexadecimal radix (`%o', `%u', or
`%x', respectively); or as a character value (`%c').

   Floating-point numbers can be printed in normal, fixed-point notation
using the `%f' conversion or in exponential notation using the `%e'
conversion.  The `%g' conversion uses either `%e' or `%f' format,
depending on what is more appropriate for the magnitude of the
particular number.

   You can control formatting more precisely by writing "modifiers"
between the `%' 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.


File: octave,  Node: Output Conversion Syntax,  Next: Table of Output Conversions,  Prev: Formatted Output,  Up: C-Style I/O Functions

Output Conversion Syntax
------------------------

   This section provides details about the precise syntax of conversion
specifications that can appear in a `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 `printf' template string have the
general form:

     % FLAGS WIDTH [ . PRECISION ] TYPE CONVERSION

   For example, in the conversion specifier `%-10.8ld', the `-' is a
flag, `10' specifies the field width, the precision is `8', the letter
`l' is a type modifier, and `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 `%' character followed in sequence by:

   * Zero or more "flag characters" that modify the normal behavior of
     the conversion specification.

   * An optional decimal integer specifying the "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
     *minimum* value; if the normal conversion produces more characters
     than this, the field is *not* truncated.  Normally, the output is
     right-justified within the field.

     You can also specify a field width of `*'.  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
     `-' flag (see below) and to use the absolute value as the field
     width.

   * An optional "precision" to specify the number of digits to be
     written for the numeric conversions.  If the precision is
     specified, it consists of a period (`.') followed optionally by a
     decimal integer (which defaults to zero if omitted).

     You can also specify a precision of `*'.  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.

   * An optional "type modifier character".  This character is ignored
     by Octave's `printf' function, but is recognized to provide
     compatibility with the C language `printf'.

   * A character that specifies the conversion to be applied.

   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.


File: octave,  Node: Table of Output Conversions,  Next: Integer Conversions,  Prev: Output Conversion Syntax,  Up: C-Style I/O Functions

Table of Output Conversions
---------------------------

   Here is a table summarizing what all the different conversions do:

`%d', `%i'
     Print an integer as a signed decimal number.  *Note Integer
     Conversions::, for details.  `%d' and `%i' are synonymous for
     output, but are different when used with `scanf' for input (*note
     Table of Input Conversions::.).

`%o'
     Print an integer as an unsigned octal number.  *Note Integer
     Conversions::, for details.

`%u'
     Print an integer as an unsigned decimal number.  *Note Integer
     Conversions::, for details.

`%x', `%X'
     Print an integer as an unsigned hexadecimal number.  `%x' uses
     lower-case letters and `%X' uses upper-case.  *Note Integer
     Conversions::, for details.

`%f'
     Print a floating-point number in normal (fixed-point) notation.
     *Note Floating-Point Conversions::, for details.

`%e', `%E'
     Print a floating-point number in exponential notation.  `%e' uses
     lower-case letters and `%E' uses upper-case.  *Note Floating-Point
     Conversions::, for details.

`%g', `%G'
     Print a floating-point number in either normal or exponential
     notation, whichever is more appropriate for its magnitude.  `%g'
     uses lower-case letters and `%G' uses upper-case.  *Note
     Floating-Point Conversions::, for details.

`%c'
     Print a single character.  *Note Other Output Conversions::.

`%s'
     Print a string.  *Note Other Output Conversions::.

`%%'
     Print a literal `%' character.  *Note Other Output Conversions::.

   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.


File: octave,  Node: Integer Conversions,  Next: Floating-Point Conversions,  Prev: Table of Output Conversions,  Up: C-Style I/O Functions

Integer Conversions
-------------------

   This section describes the options for the `%d', `%i', `%o', `%u',
`%x', and `%X' conversion specifications.  These conversions print
integers in various formats.

   The `%d' and `%i' conversion specifications both print an numeric
argument as a signed decimal number; while `%o', `%u', and `%x' print
the argument as an unsigned octal, decimal, or hexadecimal number
(respectively).  The `%X' conversion specification is just like `%x'
except that it uses the characters `ABCDEF' as digits instead of
`abcdef'.

   The following flags are meaningful:

`-'
     Left-justify the result in the field (instead of the normal
     right-justification).

`+'
     For the signed `%d' and `%i' conversions, print a plus sign if the
     value is positive.

` '
     For the signed `%d' and `%i' conversions, if the result doesn't
     start with a plus or minus sign, prefix it with a space character
     instead.  Since the `+' flag ensures that the result includes a
     sign, this flag is ignored if you supply both of them.

`#'
     For the `%o' conversion, this forces the leading digit to be `0',
     as if by increasing the precision.  For `%x' or `%X', this
     prefixes a leading `0x' or `0X' (respectively) to the result.
     This doesn't do anything useful for the `%d', `%i', or `%u'
     conversions.

`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
     `-' flag is also specified, or if a precision is specified.

   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.


File: octave,  Node: Floating-Point Conversions,  Next: Other Output Conversions,  Prev: Integer Conversions,  Up: C-Style I/O Functions

Floating-Point Conversions
--------------------------

   This section discusses the conversion specifications for
floating-point numbers: the `%f', `%e', `%E', `%g', and `%G'
conversions.

   The `%f' conversion prints its argument in fixed-point notation,
producing output of the form [`-']DDD`.'DDD, where the number of digits
following the decimal point is controlled by the precision you specify.

   The `%e' conversion prints its argument in exponential notation,
producing output of the form [`-']D`.'DDD`e'[`+'|`-']DD.  Again, the
number of digits following the decimal point is controlled by the
precision.  The exponent always contains at least two digits.  The `%E'
conversion is similar but the exponent is marked with the letter `E'
instead of `e'.

   The `%g' and `%G' conversions print the argument in the style of
`%e' or `%E' (respectively) if the exponent would be less than -4 or
greater than or equal to the precision; otherwise they use the `%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:

`-'
     Left-justify the result in the field.  Normally the result is
     right-justified.

`+'
     Always include a plus or minus sign in the result.

` '
     If the result doesn't start with a plus or minus sign, prefix it
     with a space instead.  Since the `+' flag ensures that the result
     includes a sign, this flag is ignored if you supply both of them.

`#'
     Specifies that the result should always include a decimal point,
     even if no digits follow it.  For the `%g' and `%G' conversions,
     this also forces trailing zeros after the decimal point to be left
     in place where they would otherwise be removed.

`0'
     Pad the field with zeros instead of spaces; the zeros are placed
     after any sign.  This flag is ignored if the `-' flag is also
     specified.

   The precision specifies how many digits follow the decimal-point
character for the `%f', `%e', and `%E' conversions.  For these
conversions, the default precision is `6'.  If the precision is
explicitly `0', this suppresses the decimal point character entirely.
For the `%g' and `%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 `0' or not specified for `%g' or `%G', it is treated like
a value of `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.


File: octave,  Node: Other Output Conversions,  Next: Formatted Input,  Prev: Floating-Point Conversions,  Up: C-Style I/O Functions

Other Output Conversions
------------------------

   This section describes miscellaneous conversions for `printf'.

   The `%c' conversion prints a single character.  The `-' 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:

     printf ("%c%c%c%c%c", "h", "e", "l", "l", "o");

prints `hello'.

   The `%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 `-' 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:

     printf ("%3s%-6s", "no", "where");

prints ` nowhere '.


File: octave,  Node: Formatted Input,  Next: Input Conversion Syntax,  Prev: Other Output Conversions,  Up: C-Style I/O Functions

Formatted Input
---------------

   Here are the descriptions of the functions for performing formatted
input.

 - Built-in Function:  scanf (TEMPLATE)
     The `scanf' function reads formatted input from the stream `stdin'
     under the control of the template string TEMPLATE.  The resulting
     values are returned.

 - Built-in Function:  fscanf (FID, TEMPLATE)
     This function is just like `scanf', except that the input is read
     from the stream FID instead of `stdin'.

 - Built-in Function:  sscanf (STRING, TEMPLATE)
     This is like `scanf', except that the characters are taken from the
     string STRING instead of from a stream.  Reaching the end of the
     string is treated as an end-of-file condition.

   Calls to `scanf' are superficially similar to calls to `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 `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 `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.

   When a "matching failure" occurs, `scanf' returns immediately,
leaving the first non-matching character as the next character to be
read from the stream, and `scanf' returns all the items that were
successfully converted.

   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.


File: octave,  Node: Input Conversion Syntax,  Next: Table of Input Conversions,  Prev: Formatted Input,  Up: C-Style I/O Functions

Input Conversion Syntax
-----------------------

   A `scanf' template string is a string that contains ordinary
multibyte characters interspersed with conversion specifications that
start with `%'.

   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 ` , ' 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 `scanf' template string have the
general form:

     % FLAGS WIDTH TYPE CONVERSION

   In more detail, an input conversion specification consists of an
initial `%' character followed in sequence by:

   * An optional "flag character" `*', which says to ignore the text
     read for this specification.  When `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 use a pointer argument, and does not increment the
     count of successful assignments.

   * An optional decimal integer that specifies the "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 (those that don't are explicitly
     documented), and these discarded characters don't count towards
     the maximum field width.

   * An optional type modifier character.  This character is ignored by
     Octave's `scanf' function, but is recognized to provide
     compatibility with the C language `scanf'.

   * A character that specifies the conversion to be applied.

   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.


File: octave,  Node: Table of Input Conversions,  Next: Numeric Input Conversions,  Prev: Input Conversion Syntax,  Up: C-Style I/O Functions

Table of Input Conversions
--------------------------

   Here is a table that summarizes the various conversion
specifications:

`%d'
     Matches an optionally signed integer written in decimal.  *Note
     Numeric Input Conversions::.

`%i'
     Matches an optionally signed integer in any of the formats that
     the C language defines for specifying an integer constant.  *Note
     Numeric Input Conversions::.

`%o'
     Matches an unsigned integer written in octal radix.  *Note Numeric
     Input Conversions::.

`%u'
     Matches an unsigned integer written in decimal radix.  *Note
     Numeric Input Conversions::.

`%x', `%X'
     Matches an unsigned integer written in hexadecimal radix.  *Note
     Numeric Input Conversions::.

`%e', `%f', `%g', `%E', `%G'
     Matches an optionally signed floating-point number.  *Note Numeric
     Input Conversions::.

`%s'
     Matches a string containing only non-whitespace characters.  *Note
     String Input Conversions::.

`%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.  *Note String Input Conversions::.

`%%'
     This matches a literal `%' character in the input stream.  No
     corresponding argument is used.

   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.


File: octave,  Node: Numeric Input Conversions,  Next: String Input Conversions,  Prev: Table of Input Conversions,  Up: C-Style I/O Functions

Numeric Input Conversions
-------------------------

   This section describes the `scanf' conversions for reading numeric
values.

   The `%d' conversion matches an optionally signed integer in decimal
radix.

   The `%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 `10', `0xa', or `012' could be read
in as integers under the `%i' conversion.  Each of these specifies a
number with decimal value `10'.

   The `%o', `%u', and `%x' conversions match unsigned integers in
octal, decimal, and hexadecimal radices, respectively.

   The `%X' conversion is identical to the `%x' conversion.  They both
permit either uppercase or lowercase letters to be used as digits.

   Unlike the C language `scanf', Octave ignores the `h', `l', and `L'
modifiers.


File: octave,  Node: String Input Conversions,  Next: Binary I/O,  Prev: Numeric Input Conversions,  Up: C-Style I/O Functions

String Input Conversions
------------------------

   This section describes the `scanf' input conversions for reading
string and character values: `%s' and `%c'.

   The `%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 N characters, and fails if it cannot get that many.

   The `%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:

      hello, world

with the conversion `%10c' produces `" hello, wo"', but reading the
same input with the conversion `%10s' produces `"hello,"'.


File: octave,  Node: Binary I/O,  Next: Other I/O Functions,  Prev: String Input Conversions,  Up: C-Style I/O Functions

Binary I/O
----------

   Octave has to C-style functions for reading and writing binary data.
They are `fread' and `fwrite' and are patterned after the standard C
functions with the same names.

 - Built-in Function:  fread (FID, SIZE, PRECISION)
     This function reads data in binary form of type PRECISION from the
     specified FID, which may be either a file name, or a file number
     as returned from `fopen'.

     The argument SIZE specifies the size of the matrix to return.  It
     may be a scalar or a two-element vector.  If it is a scalar,
     `fread' returns a column vector of the specified length.  If it is
     a two-element vector, it specifies the number of rows and columns
     of the result matrix, and `fread' fills the elements of the matrix
     in column-major order.

     The argument PRECISION is a string specifying the type of data to
     read and may be one of `"char"', `"schar"', `"short"', `"int"',
     `"long"', `"float"', `"double"', `"uchar"', `"ushort"', `"uint"',
     or `"ulong"'.  The default precision is `"uchar"'.

     The `fread' function returns two values, `data', which is the data
     read from the file, and `count', which is the number of elements
     read.

 - Built-in Function:  fwrite (FID, DATA, PRECISION)
     This function writes data in binary form of type PRECISION to the
     specified FID, which may be either a file name, or a file number
     as returned from `fopen'.

     The argument DATA is a matrix of values that are to be written to
     the file.  The values are extracted in column-major order.

     The argument PRECISION is a string specifying the type of data to
     read and may be one of `"char"', `"schar"', `"short"', `"int"',
     `"long"', `"float"', `"double"', `"uchar"', `"ushort"', `"uint"',
     or `"ulong"'.  The default precision is `"uchar"'.

     The `fwrite' function returns the number of elements written.

     The behavior of `fwrite' is undefined if the values in DATA are
     too large to fit in the specified precision.


File: octave,  Node: Other I/O Functions,  Prev: Binary I/O,  Up: C-Style I/O Functions

Other I/O Functions
-------------------

 - Built-in Function:  fgetl (FID, LEN)
     Read `len' characters from a file.

 - Built-in Function:  fgets (FID, LEN)
     Read `len' characters from a file.

 - Built-in Function:  fflush (FID)
     Flush output to 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 `input'.

   Three functions are available for setting and determining the
position of the file pointer for a given file.

 - Built-in Function:  ftell (FID)
     Return the position of the file pointer as the number of characters
     from the beginning of the file FID.

 - Built-in Function:  fseek (FID, offset, origin)
     Set the file pointer to any location within the file FID.  The
     pointer is positioned `offset' characters from the `origin', which
     may be one of the predefined variables `SEEK_CUR' (current
     position), `SEEK_SET' (beginning), or `SEEK_END' (end of file). If
     `origin' is omitted, `SEEK_SET' is assumed.  The offset must be
     zero, or a value returned by `ftell' (in which case `origin' must
     be `SEEK_SET'.

 - Built-in Variable: SEEK_SET
 - Built-in Variable: SEEK_CUR
 - Built-in Variable: SEEK_END
     These variables may be used as the optional third argument for the
     function `fseek'.

 - Built-in Function:  frewind (FID)
     Move the file pointer to the beginning of the file FID, returning
     1 for success, and 0 if an error was encountered.  It is
     equivalent to `fseek (FID, 0, SEEK_SET)'.

   The following example stores the current file position in the
variable `marker', moves the pointer to the beginning of the file, reads
four characters, and then returns to the original position.

     marker = ftell (myfile);
     frewind (myfile);
     fourch = fgets (myfile, 4);
     fseek (myfile, marker, SEEK_SET);

 - Built-in Function:  feof (FID)
     Returns 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.

 - Built-in Function:  ferror (FID)
     Returns 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.

 - Built-in Function:  kbhit ()
     Read a single keystroke from the keyboard.  For example,

          x = kbhit ();

     will set X to the next character typed at the keyboard, without
     requiring a carriage return to be typed.

 - Built-in Function:  freport ()
     Finally, it is often useful to know exactly which files have been
     opened, and whether they are open for reading, writing, or both.
     The command `freport' prints this information for all open files.
     For example,

          octave:13> freport
          
           number  mode  name
          
                0     r  stdin
                1     w  stdout
                2     w  stderr
                3     r  myfile

 - Built-in Function:  fputs (FID, STRING)
     Write a string to a file with no formatting.

 - Built-in Function:  puts (STRING)
     Write a string to the standard output with no formatting.

 - Built-in Function: [IN, OUT, PID] = popen2 (COMMAND, ARGS)
     Start a subprocess with 2-way communication.

 - Built-in Function: fid = popen (COMMAND, MODE)
     Open a pipe to a subprocess.

 - Built-in Function:  pclose (FID)
     Close a pipe from a subprocess.


File: octave,  Node: Special Matrices,  Next: Matrix Manipulation,  Prev: Input and Output,  Up: Top

Special Matrices
****************

   Octave provides a number of functions for creating special matrix
forms.  In nearly all cases, it is best to use the built-in functions
for this purpose than to try to use other tricks to achieve the same
effect.

* Menu:

* Special Utility Matrices::
* Famous Matrices::


File: octave,  Node: Special Utility Matrices,  Next: Famous Matrices,  Prev: Special Matrices,  Up: Special Matrices

Special Utility Matrices
========================

 - Built-in Function:  eye (X)
 - Built-in Function:  eye (N, M)
     Returns an identity matrix.  If invoked with a single scalar
     argument, `eye' returns a square matrix with the dimension
     specified.  If you supply two scalar arguments, `eye' takes them
     to be the number of rows and columns.  If given a vector with two
     elements, `eye' uses the values of the elements as the number of
     rows and columns, respecively.  For example,

          eye (3)
          
               =>  1  0  0
                   0  1  0
                   0  0  1

     The following expressions all produce the same result:

          eye (2)
          eye (2, 2)
          eye (size ([1, 2; 3, 4])

     For compatibility with MATLAB, calling `eye' with no arguments is
     equivalent to calling it with an argument of 1.

 - Built-in Function:  ones (X)
 - Built-in Function:  ones (N, M)
     Returns a matrix whose elements are all 1.  The arguments are
     handled the same as the arguments for `eye'.

     If you need to create a matrix whose values are all the same, you
     should use an expression like

          val_matrix = val * ones (n, m)

 - Built-in Function:  zeros (X)
 - Built-in Function:  zeros (N, M)
     Returns a matrix whose elements are all 0.  The arguments are
     handled the same as the arguments for `eye'.

 - Loadable Function:  rand (X)
 - Loadable Function:  rand (N, M)
 - Loadable Function:  rand (`"seed"', X)
     Returns a matrix with random elements uniformly distributed on the
     interval (0, 1).  The arguments are handled the same as the
     arguments for `eye'.  In addition, you can set the seed for the
     random number generator using the form

          randn ("seed", X)

     where X is a scalar value.  If called as

          rand ("seed")

     `rand' returns the current value of the seed.

 - Loadable Function:  randn (X)
 - Loadable Function:  randn (N, M)
 - Loadable Function:  randn (`"seed"', X)
     Returns a matrix with normally distributed random elements.  The
     arguments are handled the same as the arguments for `eye'.  In
     addition, you can set the seed for the random number generator
     using the form

          randn ("seed", X)

     where X is a scalar value.  If called as

          randn ("seed")

     `randn' returns the current value of the seed.

   The `rand' and `randn' functions use separate generators.  This
ensures that

     rand ("seed", 13);
     randn ("seed", 13);
     u = rand (100, 1);
     n = randn (100, 1);

and

     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

produce equivalent results.

   Normally, `rand' and `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, `rand' and `randn' return a
single element of a random sequence.

   The `rand' and `randn' functions use Fortran code from 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.

 - Built-in Function:  diag (V, K)
     Returns a diagonal matrix with vector V on diagonal K.  The second
     argument is optional.  If it is positive, the vector is placed on
     the K-th super-diagonal.  If it is negative, it is placed on the
     -K-th sub-diagonal.  The default value of K is 0, and the vector
     is placed on the main diagonal.  For example,

          diag ([1, 2, 3], 1)
          
               =>  0  1  0  0
                   0  0  2  0
                   0  0  0  3
                   0  0  0  0

   The functions `linspace' and `logspace' make it very easy to create
vectors with evenly or logarithmically spaced elements.  *Note Ranges::.

 - Function File:  linspace (BASE, LIMIT, N)
     creates a row vector with N (N greater than 1) linearly spaced
     elements between BASE and LIMIT.  The BASE and LIMIT are always
     included in the range.  If BASE is greater than LIMIT, the
     elements are stored in decreasing order.  If the number of points
     is not specified, a value of 100 is used.

     The `linspace' function always returns a row vector, regardless of
     the value of `prefer_column_vectors'.

 - Function File:  logspace (BASE, LIMIT, N)
     Similar to `linspace' except that the values are logarithmically
     spaced.

     If LIMIT is equal to pi, the points are between 10^base and pi,
     *not* 10^base and 10^pi, in order to  be compatible with the
     corresponding MATLAB function.


File: octave,  Node: Famous Matrices,  Prev: Special Utility Matrices,  Up: Special Matrices

Famous Matrices
===============

   The following functions return famous matrix forms.

 - Function File:  hadamard (K)
     Return the Hadamard matrix of order n = 2^k.

 - Function File:  hankel (C, R)
     Return the Hankel matrix constructed given the first column C, and
     (optionally) the last row R.  If the last element of C is not the
     same as the first element of R, the last element of 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 C, and an n-vector R, has
     the elements

          H (i, j) = c (i+j-1),  i+j-1 <= m;
          H (i, j) = r (i+j-m),  otherwise

 - Function File:  hilb (N)
     Return the Hilbert matrix of order N.  The i, j element of a
     Hilbert matrix is defined as

          H (i, j) = 1 / (i + j - 1)

 - Function File:  invhilb (N)
     Return the inverse of a Hilbert matrix of order N.  This is exact.
     Compare with the numerical calculation of `inverse (hilb (n))',
     which suffers from the ill-conditioning of the Hilbert matrix, and
     the finite precision of your computer's floating point arithmetic.

 - Function File:  toeplitz (C, R)
     Return the Toeplitz matrix constructed given the first column C,
     and (optionally) the first row R.  If the first element of C is
     not the same as the first element of R, the first element of 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

          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)

 - Function File:  vander (C)
     Return the Vandermonde matrix whose next to last column is C.

     A Vandermonde matrix has the form

          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


File: octave,  Node: Matrix Manipulation,  Next: String Functions,  Prev: Special Matrices,  Up: Top

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::


File: octave,  Node: Finding Elements and Checking Conditions,  Next: Rearranging Matrices,  Prev: Matrix Manipulation,  Up: Matrix Manipulation

Finding Elements and Checking Conditions
========================================

   The functions `any' and `all' are useful for determining whether any
or all of the elements of a matrix satisfy some condition.  The `find'
function is also useful in determining which elements of a matrix meet
a specified condition.

 - Built-in Function:  any (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,

          any (eye (2, 4))
          
               => [ 1, 1, 0, 0 ]

     To see if any of the elements of a matrix are nonzero, you can use
     a statement like

          any (any (a))

 - Built-in Function:  all (X)
     The function `all' behaves like the function `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.

   Since the comparison operators (*note 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,

     all (all (rand (5) < 0.9))
     
          => 0

tests a random 5 by 5 matrix to see if all of it's elements are less
than 0.9.

   Note that in conditional contexts (like the test clause of `if' and
`while' statements) Octave treats the test as if you had typed `all
(all (condition))'.

 - Mapping Function:  isinf (X)
     Return 1 for elements of X that are infinite and zero otherwise.
     For example,

          isinf ([13, Inf, NaN])
          
               => [ 0, 1, 0 ]

 - Mapping Function:  isnan (X)
     Return 1 for elements of X that are NaN values and zero otherwise.
     For example,

          isnan ([13, Inf, NaN])
          
               => [ 0, 0, 1 ]

 - Mapping Function:  finite (X)
     Return 1 for elements of X that are NaN values and zero otherwise.
     For example,

          finite ([13, Inf, NaN])
          
               => [ 1, 0, 0 ]

 - Loadable Function:  find (X)
     The function `find' returns 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,

          find (eye (2))
          
               => [ 1; 4 ]

     If two outputs are requested, `find' returns the row and column
     indices of nonzero elements of a matrix.  For example,

          [i, j] = find (2 * eye (2))
          
               => i = [ 1; 2 ]
          
               => j = [ 1; 2 ]

     If three outputs are requested, `find' also returns a vector
     containing the the nonzero values.  For example,

          [i, j, v] = find (3 * eye (2))
          
               => i = [ 1; 2 ]
          
               => j = [ 1; 2 ]
          
               => v = [ 3; 3 ]


File: octave,  Node: Rearranging Matrices,  Prev: Finding Elements and Checking Conditions,  Up: Matrix Manipulation

Rearranging Matrices
====================

 - Function File:  fliplr (X)
     Return a copy of X with the order of the columns reversed.  For
     example,

          fliplr ([1, 2; 3, 4])
          
               =>  2  1
                   4  3

 - Function File:  flipud (X)
     Return a copy of X with the order of the rows reversed.  For
     example,

          flipud ([1, 2; 3, 4])
          
               =>  3  4
                   1  2

 - Function File:  rot90 (X, N)
     Returns a copy of 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 N rotate the matrix in a
     clockwise direction.  For example,

          rot90 ([1, 2; 3, 4], -1)
          
               =>  3  1
                   4  2

     rotates the given matrix clockwise by 90 degrees.  The following
     are all equivalent statements:

          rot90 ([1, 2; 3, 4], -1)
          rot90 ([1, 2; 3, 4], 3)
          rot90 ([1, 2; 3, 4], 7)

 - Function File:  reshape (A, M, N)
     Return a matrix with M rows and N columns whose elements are taken
     from the matrix 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,

          reshape ([1, 2, 3, 4], 2, 2)
          
               =>  1  3
                   2  4

     If the variable `do_fortran_indexing' is nonzero, the `reshape'
     function is equivalent to

          retval = zeros (m, n);
          retval (:) = a;

     but it is somewhat less cryptic to use `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.

 - Loadable Function: [s, i] = sort (X)
     Returns a copy of X with the elements elements arranged in
     increasing order.  For matrices, `sort' orders the elements in each
     column.

     For example,

          sort ([1, 2; 2, 3; 3, 1])
          
               =>  1  1
                   2  2
                   3  3

     The `sort' function may also be used to produce a matrix
     containing the original row indices of the elements in the sorted
     matrix.  For example,

          [s, i] = sort ([1, 2; 2, 3; 3, 1])
          
               => s = 1  1
                      2  2
                      3  3
          
               => i = 1  3
                      2  1
                      3  2

   Since the `sort' function does not allow sort keys to be specified,
so it can't be used to order the rows of a matrix according to the
values of the elements in various columns(1) 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.

     a = [1, 2; 2, 3; 3, 1];
     [s, i] = sort (a (:, 2));
     a (i, :)
     
          =>  3  1
              1  2
              2  3

 - Function File:  tril (A, K)
 - Function File:  triu (A, K)
     Return a new matrix form by extracting extract the lower (`tril')
     or upper (`triu') triangular part of the matrix 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 K is zero, so that `triu' and `tril' normally
     include the main diagonal as part of the result matrix.

     If the value of K is negative, additional elements above (for
     `tril') or below (for `triu') the main diagonal are also selected.

     The absolute value of K must not be greater than the number of
     sub- or super-diagonals.

     For example,

          tril (ones (3), -1)
          
               =>  0  0  0
                   1  0  0
                   1  1  0

     and

          tril (ones (3), 1)
          
               =>  1  1  0
                   1  1  1
                   1  1  1

   ---------- Footnotes ----------

   (1)  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.

