home *** CD-ROM | disk | FTP | other *** search
/ Geek Gadgets 1 / ADE-1.bin / ade-dist / octave-1.1.1p1-bin.lha / info / octave.info-3 (.txt) < prev    next >
GNU Info File  |  1996-10-12  |  37KB  |  778 lines

  1. This is Info file octave.info, produced by Makeinfo-1.64 from the input
  2. file octave.texi.
  3.    Copyright (C) 1993, 1994, 1995 John W. Eaton.
  4.    Permission is granted to make and distribute verbatim copies of this
  5. manual provided the copyright notice and this permission notice are
  6. preserved on all copies.
  7.    Permission is granted to copy and distribute modified versions of
  8. this manual under the conditions for verbatim copying, provided that
  9. the entire resulting derived work is distributed under the terms of a
  10. permission notice identical to this one.
  11.    Permission is granted to copy and distribute translations of this
  12. manual into another language, under the above conditions for modified
  13. versions.
  14. File: octave.info,  Node: The while Statement,  Next: The for Statement,  Prev: The if Statement,  Up: Statements
  15. The `while' Statement
  16. =====================
  17.    In programming, a "loop" means a part of a program that is (or at
  18. least can be) executed two or more times in succession.
  19.    The `while' statement is the simplest looping statement in Octave.
  20. It repeatedly executes a statement as long as a condition is true.  As
  21. with the condition in an `if' statement, the condition in a `while'
  22. statement is considered true if its value is non-zero, and false if its
  23. value is zero.  If the value of the conditional expression in an `if'
  24. statement is a vector or a matrix, it is considered true only if *all*
  25. of the elements are non-zero.
  26.    Octave's `while' statement looks like this:
  27.      while (CONDITION)
  28.        BODY
  29.      endwhile
  30. Here BODY is a statement or list of statements that we call the "body"
  31. of the loop, and CONDITION is an expression that controls how long the
  32. loop keeps running.
  33.    The first thing the `while' statement does is test CONDITION.  If
  34. CONDITION is true, it executes the statement BODY.  After BODY has been
  35. executed, CONDITION is tested again, and if it is still true, BODY is
  36. executed again.  This process repeats until CONDITION is no longer
  37. true.  If CONDITION is initially false, the body of the loop is never
  38. executed.
  39.    This example creates a variable `fib' that contains the elements of
  40. the Fibonacci sequence.
  41.      fib = ones (1, 10);
  42.      i = 3;
  43.      while (i <= 10)
  44.        fib (i) = fib (i-1) + fib (i-2);
  45.        i++;
  46.      endwhile
  47. Here the body of the loop contains two statements.
  48.    The loop works like this: first, the value of `i' is set to 3.
  49. Then, the `while' tests whether `i' is less than or equal to 10.  This
  50. is the case when `i' equals 3, so the value of the `i'-th element of
  51. `fib' is set to the sum of the previous two values in the sequence.
  52. Then the `i++' increments the value of `i' and the loop repeats.  The
  53. loop terminates when `i' reaches 11.
  54.    A newline is not required between the condition and the body; but
  55. using one makes the program clearer unless the body is very simple.
  56. File: octave.info,  Node: The for Statement,  Next: The break Statement,  Prev: The while Statement,  Up: Statements
  57. The `for' Statement
  58. ===================
  59.    The `for' statement makes it more convenient to count iterations of a
  60. loop.  The general form of the `for' statement looks like this:
  61.      for VAR = EXPRESSION
  62.        BODY
  63.      endfor
  64. The assignment expression in the `for' statement works a bit
  65. differently than Octave's normal assignment statement.  Instead of
  66. assigning the complete result of the expression, it assigns each column
  67. of the expression to VAR in turn.  If EXPRESSION is either a row vector
  68. or a scalar, the value of VAR will be a scalar each time the loop body
  69. is executed.  If VAR is a column vector or a matrix, VAR will be a
  70. column vector each time the loop body is executed.
  71.    The following example shows another way to create a vector containing
  72. the first ten elements of the Fibonacci sequence, this time using the
  73. `for' statement:
  74.      fib = ones (1, 10);
  75.      for i = 3:10
  76.        fib (i) = fib (i-1) + fib (i-2);
  77.      endfor
  78. This code works by first evaluating the expression `3:10', to produce a
  79. range of values from 3 to 10 inclusive.  Then the variable `i' is
  80. assigned the first element of the range and the body of the loop is
  81. executed once.  When the end of the loop body is reached, the next
  82. value in the range is assigned to the variable `i', and the loop body
  83. is executed again.  This process continues until there are no more
  84. elements to assign.
  85.    In the `for' statement, BODY stands for any statement or list of
  86. statements.
  87.    Although it is possible to rewrite all `for' loops as `while' loops,
  88. the Octave language has both statements because often a `for' loop is
  89. both less work to type and more natural to think of.  Counting the
  90. number of iterations is very common in loops and it can be easier to
  91. think of this counting as part of looping rather than as something to
  92. do inside the loop.
  93. File: octave.info,  Node: The break Statement,  Next: The continue Statement,  Prev: The for Statement,  Up: Statements
  94. The `break' Statement
  95. =====================
  96.    The `break' statement jumps out of the innermost `for' or `while'
  97. loop that encloses it.  The `break' statement may only be used within
  98. the body of a loop.  The following example finds the smallest divisor
  99. of a given integer, and also identifies prime numbers:
  100.      num = 103;
  101.      div = 2;
  102.      while (div*div <= num)
  103.        if (rem (num, div) == 0)
  104.          break;
  105.        endif
  106.        div++;
  107.      endwhile
  108.      if (rem (num, div) == 0)
  109.        printf ("Smallest divisor of %d is %d\n", num, div)
  110.      else
  111.        printf ("%d is prime\n", num);
  112.      endif
  113.    When the remainder is zero in the first `while' statement, Octave
  114. immediately "breaks out" of the loop.  This means that Octave proceeds
  115. immediately to the statement following the loop and continues
  116. processing.  (This is very different from the `exit' statement which
  117. stops the entire Octave program.)
  118.    Here is another program equivalent to the previous one.  It
  119. illustrates how the CONDITION of a `while' statement could just as well
  120. be replaced with a `break' inside an `if':
  121.      num = 103;
  122.      div = 2;
  123.      while (1)
  124.        if (rem (num, div) == 0)
  125.          printf ("Smallest divisor of %d is %d\n", num, div);
  126.          break;
  127.        endif
  128.        div++;
  129.        if (div*div > num)
  130.          printf ("%d is prime\n", num);
  131.          break;
  132.        endif
  133.      endwhile
  134. File: octave.info,  Node: The continue Statement,  Next: The unwind_protect Statement,  Prev: The break Statement,  Up: Statements
  135. The `continue' Statement
  136. ========================
  137.    The `continue' statement, like `break', is used only inside `for' or
  138. `while' loops.  It skips over the rest of the loop body, causing the
  139. next cycle around the loop to begin immediately.  Contrast this with
  140. `break', which jumps out of the loop altogether.  Here is an example:
  141.      # print elements of a vector of random
  142.      # integers that are even.
  143.      
  144.      # first, create a row vector of 10 random
  145.      # integers with values between 0 and 100:
  146.      
  147.      vec = round (rand (1, 10) * 100);
  148.      
  149.      # print what we're interested in:
  150.      
  151.      for x = vec
  152.        if (rem (x, 2) != 0)
  153.          continue;
  154.        endif
  155.        printf ("%d\n", x);
  156.      endfor
  157.    If one of the elements of VEC is an odd number, this example skips
  158. the print statement for that element, and continues back to the first
  159. statement in the loop.
  160.    This is not a practical example of the `continue' statement, but it
  161. should give you a clear understanding of how it works.  Normally, one
  162. would probably write the loop like this:
  163.      for x = vec
  164.        if (rem (x, 2) == 0)
  165.          printf ("%d\n", x);
  166.        endif
  167.      endfor
  168. File: octave.info,  Node: The unwind_protect Statement,  Next: Continuation Lines,  Prev: The continue Statement,  Up: Statements
  169. The `unwind_protect' Statement
  170. ==============================
  171.    Octave supports a limited form of exception handling modelled after
  172. the unwind-protect form of Lisp.
  173.    The general form of an `unwind_protect' block looks like this:
  174.      unwind_protect
  175.        BODY
  176.      unwind_protect_cleanup
  177.        CLEANUP
  178.      end_unwind_protect
  179. Where BODY and CLEANUP are both optional and may contain any Octave
  180. expressions or commands.  The statements in CLEANUP are guaranteed to
  181. be executed regardless of how control exits BODY.
  182.    This is useful to protect temporary changes to global variables from
  183. possible errors.  For example, the following code will always restore
  184. the original value of the built-in variable `do_fortran_indexing' even
  185. if an error occurs while performing the indexing operation.
  186.      save_do_fortran_indexing = do_fortran_indexing;
  187.      unwind_protect
  188.        do_fortran_indexing = "true";
  189.        elt = a (idx)
  190.      unwind_protect_cleanup
  191.        do_fortran_indexing = save_do_fortran_indexing;
  192.      end_unwind_protect
  193.    Without `unwind_protect', the value of DO_FORTRAN_INDEXING would not
  194. be restored if an error occurs while performing the indexing operation
  195. because evaluation would stop at the point of the error and the
  196. statement to restore the value would not be executed.
  197. File: octave.info,  Node: Continuation Lines,  Prev: The unwind_protect Statement,  Up: Statements
  198. Continuation Lines
  199. ==================
  200.    In the Octave language, most statements end with a newline character
  201. and you must tell Octave to ignore the newline character in order to
  202. continue a statement from one line to the next.  Lines that end with the
  203. characters `...' or `\' are joined with the following line before they
  204. are divided into tokens by Octave's parser.  For example, the lines
  205.      x = long_variable_name ...
  206.          + longer_variable_name \
  207.          - 42
  208. form a single statement.  The backslash character on the second line
  209. above is interpreted a continuation character, *not* as a division
  210. operator.
  211.    For continuation lines that do not occur inside string constants,
  212. whitespace and comments may appear between the continuation marker and
  213. the newline character.  For example, the statement
  214.      x = long_variable_name ...     % comment one
  215.          + longer_variable_name \   % comment two
  216.          - 42                       % last comment
  217. is equivalent to the one shown above.
  218.    In some cases, Octave will allow you to continue lines without
  219. having to specify continuation characters.  For example, it is possible
  220. to write statements like
  221.      if (big_long_variable_name == other_long_variable_name
  222.          || not_so_short_variable_name > 4
  223.          && y > x)
  224.        some (code, here);
  225.      endif
  226. without having to clutter up the if statement with continuation
  227. characters.
  228. File: octave.info,  Node: Functions and Scripts,  Next: Built-in Variables,  Prev: Statements,  Up: Top
  229. Functions and Script Files
  230. **************************
  231.    Complicated Octave programs can often be simplified by defining
  232. functions.  Functions can be defined directly on the command line during
  233. interactive Octave sessions, or in external files, and can be called
  234. just like built-in ones.
  235. * Menu:
  236. * Defining Functions::
  237. * Multiple Return Values::
  238. * Variable-length Argument Lists::
  239. * Variable-length Return Lists::
  240. * Returning From a Function::
  241. * Function Files::
  242. * Script Files::
  243. * Dynamically Linked Functions::
  244. * Organization of Functions::
  245. File: octave.info,  Node: Defining Functions,  Next: Multiple Return Values,  Prev: Functions and Scripts,  Up: Functions and Scripts
  246. Defining Functions
  247. ==================
  248.    In its simplest form, the definition of a function named NAME looks
  249. like this:
  250.      function NAME
  251.        BODY
  252.      endfunction
  253. A valid function name is like a valid variable name: a sequence of
  254. letters, digits and underscores, not starting with a digit.  Functions
  255. share the same pool of names as variables.
  256.    The function BODY consists of Octave statements.  It is the most
  257. important part of the definition, because it says what the function
  258. should actually *do*.
  259.    For example, here is a function that, when executed, will ring the
  260. bell on your terminal (assuming that it is possible to do so):
  261.      function wakeup
  262.        printf ("\a");
  263.      endfunction
  264.    The `printf' statement (*note Input and Output::.) simply tells
  265. Octave to print the string `"\a"'.  The special character `\a' stands
  266. for the alert character (ASCII 7).  *Note String Constants::.
  267.    Once this function is defined, you can ask Octave to evaluate it by
  268. typing the name of the function.
  269.    Normally, you will want to pass some information to the functions you
  270. define.  The syntax for passing parameters to a function in Octave is
  271.      function NAME (ARG-LIST)
  272.        BODY
  273.      endfunction
  274. where ARG-LIST is a comma-separated list of the function's arguments.
  275. When the function is called, the argument names are used to hold the
  276. argument values given in the call.  The list of arguments may be empty,
  277. in which case this form is equivalent to the one shown above.
  278.    To print a message along with ringing the bell, you might modify the
  279. `beep' to look like this:
  280.      function wakeup (message)
  281.        printf ("\a%s\n", message);
  282.      endfunction
  283.    Calling this function using a statement like this
  284.      wakeup ("Rise and shine!");
  285. will cause Octave to ring your terminal's bell and print the message
  286. `Rise and shine!', followed by a newline character (the `\n' in the
  287. first argument to the `printf' statement).
  288.    In most cases, you will also want to get some information back from
  289. the functions you define.  Here is the syntax for writing a function
  290. that returns a single value:
  291.      function RET-VAR = NAME (ARG-LIST)
  292.        BODY
  293.      endfunction
  294. The symbol RET-VAR is the name of the variable that will hold the value
  295. to be returned by the function.  This variable must be defined before
  296. the end of the function body in order for the function to return a
  297. value.
  298.    For example, here is a function that computes the average of the
  299. elements of a vector:
  300.      function retval = avg (v)
  301.        retval = sum (v) / length (v);
  302.      endfunction
  303.    If we had written `avg' like this instead,
  304.      function retval = avg (v)
  305.        if (is_vector (v))
  306.          retval = sum (v) / length (v);
  307.        endif
  308.      endfunction
  309. and then called the function with a matrix instead of a vector as the
  310. argument, Octave would have printed an error message like this:
  311.      error: `retval' undefined near line 1 column 10
  312.      error: evaluating index expression near line 7, column 1
  313. because the body of the `if' statement was never executed, and `retval'
  314. was never defined.  To prevent obscure errors like this, it is a good
  315. idea to always make sure that the return variables will always have
  316. values, and to produce meaningful error messages when problems are
  317. encountered.  For example, `avg' could have been written like this:
  318.      function retval = avg (v)
  319.        retval = 0;
  320.        if (is_vector (v))
  321.          retval = sum (v) / length (v);
  322.        else
  323.          error ("avg: expecting vector argument");
  324.        endif
  325.      endfunction
  326.    There is still one additional problem with this function.  What if
  327. it is called without an argument?  Without additional error checking,
  328. Octave will probably print an error message that won't really help you
  329. track down the source of the error.  To allow you to catch errors like
  330. this, Octave provides each function with an automatic variable called
  331. `nargin'.  Each time a function is called, `nargin' is automatically
  332. initialized to the number of arguments that have actually been passed
  333. to the function.  For example, we might rewrite the `avg' function like
  334. this:
  335.      function retval = avg (v)
  336.        retval = 0;
  337.        if (nargin != 1)
  338.          error ("usage: avg (vector)");
  339.        endif
  340.        if (is_vector (v))
  341.          retval = sum (v) / length (v);
  342.        else
  343.          error ("avg: expecting vector argument");
  344.        endif
  345.      endfunction
  346.    Although Octave does not consider it an error if you call a function
  347. with more arguments than were expected, doing so is probably an error,
  348. so we check for that possibility too, and issue the error message if
  349. either too few or too many arguments have been provided.
  350.    The body of a user-defined function can contain a `return'
  351. statement.  This statement returns control to the rest of the Octave
  352. program.  A `return' statement is assumed at the end of every function
  353. definition.
  354. File: octave.info,  Node: Multiple Return Values,  Next: Variable-length Argument Lists,  Prev: Defining Functions,  Up: Functions and Scripts
  355. Multiple Return Values
  356. ======================
  357.    Unlike many other computer languages, Octave allows you to define
  358. functions that return more than one value.  The syntax for defining
  359. functions that return multiple values is
  360.      function [RET-LIST] = NAME (ARG-LIST)
  361.        BODY
  362.      endfunction
  363. where NAME, ARG-LIST, and BODY have the same meaning as before, and
  364. RET-LIST is a comma-separated list of variable names that will hold the
  365. values returned from the function.  The list of return values must have
  366. at least one element.  If RET-LIST has only one element, this form of
  367. the `function' statement is equivalent to the form described in the
  368. previous section.
  369.    Here is an example of a function that returns two values, the maximum
  370. element of a vector and the index of its first occurrence in the vector.
  371.      function [max, idx] = vmax (v)
  372.        idx = 1;
  373.        max = v (idx);
  374.        for i = 2:length (v)
  375.          if (v (i) > max)
  376.            max = v (i);
  377.            idx = i;
  378.          endif
  379.        endfor
  380.      endfunction
  381.    In this particular case, the two values could have been returned as
  382. elements of a single array, but that is not always possible or
  383. convenient.  The values to be returned may not have compatible
  384. dimensions, and it is often desirable to give the individual return
  385. values distinct names.
  386.    In addition to setting `nargin' each time a function is called,
  387. Octave also automatically initializes `nargout' to the number of values
  388. that are expected to be returned.  This allows you to write functions
  389. that behave differently depending on the number of values that the user
  390. of the function has requested.  The implicit assignment to the built-in
  391. variable `ans' does not figure in the count of output arguments, so the
  392. value of `nargout' may be zero.
  393.    The `svd' and `lu' functions are examples of built-in functions that
  394. behave differently depending on the value of `nargout'.
  395.    It is possible to write functions that only set some return values.
  396. For example, calling the function
  397.      function [x, y, z] = f ()
  398.        x = 1;
  399.        z = 2;
  400.      endfunction
  401.      [a, b, c] = f ()
  402. produces:
  403.      a = 1
  404.      
  405.      b = [](0x0)
  406.      
  407.      c = 2
  408. File: octave.info,  Node: Variable-length Argument Lists,  Next: Variable-length Return Lists,  Prev: Multiple Return Values,  Up: Functions and Scripts
  409. Variable-length Argument Lists
  410. ==============================
  411.    Octave has a real mechanism for handling functions that take an
  412. unspecified number of arguments, so it is not necessary to place an
  413. upper bound on the number of optional arguments that a function can
  414. accept.
  415.    Here is an example of a function that uses the new syntax to print a
  416. header followed by an unspecified number of values:
  417.      function foo (heading, ...)
  418.        disp (heading);
  419.        va_start ();
  420.        while (--nargin)
  421.          disp (va_arg ());
  422.        endwhile
  423.      endfunction
  424.    The ellipsis that marks the variable argument list may only appear
  425. once and must be the last element in the list of arguments.
  426.    Calling `va_start()' positions an internal pointer to the first
  427. unnamed argument and allows you to cycle through the arguments more than
  428. once.  It is not necessary to call `va_start()' if you do not plan to
  429. cycle through the arguments more than once.
  430.    The function `va_arg()' returns the value of the next available
  431. argument and moves the internal pointer to the next argument.  It is an
  432. error to call `va_arg()' when there are no more arguments available.
  433.    Sometimes it is useful to be able to pass all unnamed arguments to
  434. another function.  The keyword ALL_VA_ARGS makes this very easy to do.
  435. For example, given the functions
  436.      function f (...)
  437.        while (nargin--)
  438.          disp (va_arg ())
  439.        endwhile
  440.      endfunction
  441.      function g (...)
  442.        f ("begin", all_va_args, "end")
  443.      endfunction
  444. the statement
  445.      g (1, 2, 3)
  446. prints
  447.      begin
  448.      1
  449.      2
  450.      3
  451.      end
  452.    The keyword `all_va_args' always stands for the entire list of
  453. optional argument, so it is possible to use it more than once within the
  454. same function without having to call `var_start ()'.  It can only be
  455. used within functions that take a variable number of arguments.  It is
  456. an error to use it in other contexts.
  457. File: octave.info,  Node: Variable-length Return Lists,  Next: Returning From a Function,  Prev: Variable-length Argument Lists,  Up: Functions and Scripts
  458. Variable-length Return Lists
  459. ============================
  460.    Octave also has a real mechanism for handling functions that return
  461. an unspecified number of values, so it is no longer necessary to place
  462. an upper bound on the number of outputs that a function can produce.
  463.    Here is an example of a function that uses the new syntax to produce
  464. N values:
  465.      function [...] = foo (n, x)
  466.        for i = 1:n
  467.          vr_val (i * x);
  468.        endfor
  469.      endfunction
  470.    Each time `vr_val()' is called, it places the value of its argument
  471. at the end of the list of values to return from the function.  Once
  472. `vr_val()' has been called, there is no way to go back to the beginning
  473. of the list and rewrite any of the return values.
  474.    As with variable argument lists, the ellipsis that marks the variable
  475. return list may only appear once and must be the last element in the
  476. list of returned values.
  477. File: octave.info,  Node: Returning From a Function,  Next: Function Files,  Prev: Variable-length Return Lists,  Up: Functions and Scripts
  478. Returning From a Function
  479. =========================
  480.    The body of a user-defined function can contain a `return' statement.
  481. This statement returns control to the rest of the Octave program.  It
  482. looks like this:
  483.      return
  484.    Unlike the `return' statement in C, Octave's `return' statement
  485. cannot be used to return a value from a function.  Instead, you must
  486. assign values to the list of return variables that are part of the
  487. `function' statement.  The `return' statement simply makes it easier to
  488. exit a function from a deeply nested loop or conditional statement.
  489.    Here is an example of a function that checks to see if any elements
  490. of a vector are nonzero.
  491.      function retval = any_nonzero (v)
  492.        retval = 0;
  493.        for i = 1:length (v)
  494.          if (v (i) != 0)
  495.            retval = 1;
  496.            return;
  497.          endif
  498.        endfor
  499.        printf ("no nonzero elements found\n");
  500.      endfunction
  501.    Note that this function could not have been written using the
  502. `break' statement to exit the loop once a nonzero value is found
  503. without adding extra logic to avoid printing the message if the vector
  504. does contain a nonzero element.
  505. File: octave.info,  Node: Function Files,  Next: Script Files,  Prev: Returning From a Function,  Up: Functions and Scripts
  506. Function Files
  507. ==============
  508.    Except for simple one-shot programs, it is not practical to have to
  509. define all the functions you need each time you need them.  Instead, you
  510. will normally want to save them in a file so that you can easily edit
  511. them, and save them for use at a later time.
  512.    Octave does not require you to load function definitions from files
  513. before using them.  You simply need to put the function definitions in a
  514. place where Octave can find them.
  515.    When Octave encounters an identifier that is undefined, it first
  516. looks for variables or functions that are already compiled and currently
  517. listed in its symbol table.  If it fails to find a definition there, it
  518. searches the list of directories specified by the built-in variable
  519. `LOADPATH' for files ending in `.m' that have the same base name as the
  520. undefined identifier.(1)  *Note User Preferences:: for a description of
  521. `LOADPATH'.  Once Octave finds a file with a name that matches, the
  522. contents of the file are read.  If it defines a *single* function, it
  523. is compiled and executed.  *Note Script Files::, for more information
  524. about how you can define more than one function in a single file.
  525.    When Octave defines a function from a function file, it saves the
  526. full name of the file it read and the time stamp on the file.  After
  527. that, it checks the time stamp on the file every time it needs the
  528. function.  If the time stamp indicates that the file has changed since
  529. the last time it was read, Octave reads it again.
  530.    Checking the time stamp allows you to edit the definition of a
  531. function while Octave is running, and automatically use the new function
  532. definition without having to restart your Octave session.  Checking the
  533. time stamp every time a function is used is rather inefficient, but it
  534. has to be done to ensure that the correct function definition is used.
  535.    Octave assumes that function files in the
  536. `/usr/local/lib/octave/1.1.1' directory tree will not change, so it
  537. doesn't have to check their time stamps every time the functions
  538. defined in those files are used.  This is normally a very good
  539. assumption and provides a significant improvement in performance for the
  540. function files that are distributed with Octave.
  541.    If you know that your own function files will not change while you
  542. are running Octave, you can improve performance by setting the variable
  543. `ignore_function_time_stamp' to `"all"', so that Octave will ignore the
  544. time stamps for all function files.  Setting it to `"system"' gives the
  545. default behavior.  If you set it to anything else, Octave will check
  546. the time stamps on all function files.
  547.    ---------- Footnotes ----------
  548.    (1)  The `.m' suffix was chosen for compatibility with MATLAB.
  549. File: octave.info,  Node: Script Files,  Next: Dynamically Linked Functions,  Prev: Function Files,  Up: Functions and Scripts
  550. Script Files
  551. ============
  552.    A script file is a file containing (almost) any sequence of Octave
  553. commands.  It is read and evaluated just as if you had typed each
  554. command at the Octave prompt, and provides a convenient way to perform a
  555. sequence of commands that do not logically belong inside a function.
  556.    Unlike a function file, a script file must *not* begin with the
  557. keyword `function'.  If it does, Octave will assume that it is a
  558. function file, and that it defines a single function that should be
  559. evaluated as soon as it is defined.
  560.    A script file also differs from a function file in that the variables
  561. named in a script file are not local variables, but are in the same
  562. scope as the other variables that are visible on the command line.
  563.    Even though a script file may not begin with the `function' keyword,
  564. it is possible to define more than one function in a single script file
  565. and load (but not execute) all of them at once.  To do this, the first
  566. token in the file (ignoring comments and other white space) must be
  567. something other than `function'.  If you have no other statements to
  568. evaluate, you can use a statement that has no effect, like this:
  569.      # Prevent Octave from thinking that this
  570.      # is a function file:
  571.      
  572.      1;
  573.      
  574.      # Define function one:
  575.      
  576.      function one ()
  577.        ...
  578.    To have Octave read and compile these functions into an internal
  579. form, you need to make sure that the file is in Octave's `LOADPATH',
  580. then simply type the base name of the file that contains the commands.
  581. (Octave uses the same rules to search for script files as it does to
  582. search for function files.)
  583.    If the first token in a file (ignoring comments) is `function',
  584. Octave will compile the function and try to execute it, printing a
  585. message warning about any non-whitespace characters that appear after
  586. the function definition.
  587.    Note that Octave does not try to lookup the definition of any
  588. identifier until it needs to evaluate it.  This means that Octave will
  589. compile the following statements if they appear in a script file, or
  590. are typed at the command line,
  591.      # not a function file:
  592.      1;
  593.      function foo ()
  594.        do_something ();
  595.      endfunction
  596.      function do_something ()
  597.        do_something_else ();
  598.      endfunction
  599. even though the function `do_something' is not defined before it is
  600. referenced in the function `foo'.  This is not an error because the
  601. Octave does not need to resolve all symbols that are referenced by a
  602. function until the function is actually evaluated.
  603.    Since Octave doesn't look for definitions until they are needed, the
  604. following code will always print `bar = 3' whether it is typed directly
  605. on the command line, read from a script file, or is part of a function
  606. body, even if there is a function or script file called `bar.m' in
  607. Octave's `LOADPATH'.
  608.      eval ("bar = 3");
  609.      bar
  610.    Code like this appearing within a function body could fool Octave if
  611. definitions were resolved as the function was being compiled.  It would
  612. be virtually impossible to make Octave clever enough to evaluate this
  613. code in a consistent fashion.  The parser would have to be able to
  614. perform the `eval ()' statement at compile time, and that would be
  615. impossible unless all the references in the string to be evaluated could
  616. also be resolved, and requiring that would be too restrictive (the
  617. string might come from user input, or depend on things that are not
  618. known until the function is evaluated).
  619. File: octave.info,  Node: Dynamically Linked Functions,  Next: Organization of Functions,  Prev: Script Files,  Up: Functions and Scripts
  620. Dynamically Linked Functions
  621. ============================
  622.    On some systems, Octave can dynamically load and execute functions
  623. written in C++ or other compiled languages.  This currently only works
  624. on systems that have a working version of the GNU dynamic linker,
  625. `dld'. Unfortunately, `dld' does not work on very many systems, but
  626. someone is working on making `dld' use the GNU Binary File Descriptor
  627. library, `BFD', so that may soon change.  In any case, it should not be
  628. too hard to make Octave's dynamic linking features work on other
  629. systems using system-specific dynamic linking facilities.
  630.    Here is an example of how to write a C++ function that Octave can
  631. load.
  632.      #include <iostream.h>
  633.      
  634.      #include "defun-dld.h"
  635.      #include "tree-const.h"
  636.      
  637.      DEFUN_DLD ("hello", Fhello, Shello, -1, -1,
  638.        "hello (...)\n\
  639.      \n\
  640.      Print greeting followed by the values of all the arguments passed.\n\
  641.      Returns all the arguments passed.")
  642.      {
  643.        Octave_object retval;
  644.        cerr << "Hello, world!\n";
  645.        int nargin = args.length ();
  646.        for (int i = 1; i < nargin; i++)
  647.          retval (nargin-i-1) = args(i).eval (1);
  648.        return retval;
  649.      }
  650.    Octave's dynamic linking features currently have the following
  651. limitations.
  652.    * Dynamic linking only works on systems that support the GNU dynamic
  653.      linker, `dld'.
  654.    * Clearing dynamically linked functions doesn't work.
  655.    * Configuring Octave with `--enable-lite-kernel' seems to mostly work
  656.      to make nonessential built-in functions dynamically loaded, but
  657.      there also seem to be some problems.  For example, fsolve seems to
  658.      always return `info == 3'.  This is difficult to debug since `gdb'
  659.      won't seem to allow breakpoints to be set inside dynamically loaded
  660.      functions.
  661.    * Octave uses a lot of memory if the dynamically linked functions are
  662.      compiled to include debugging symbols.  This appears to be a
  663.      limitation with `dld', and can be avoided by not using `-g' to
  664.      compile functions that will be linked dynamically.
  665.    If you would like to volunteer to help improve Octave's ability to
  666. dynamically link externally compiled functions, please contact
  667. `bug-octave@che.utexas.edu'.
  668. File: octave.info,  Node: Organization of Functions,  Prev: Dynamically Linked Functions,  Up: Functions and Scripts
  669. Organization of Functions Distributed with Octave
  670. =================================================
  671.    Many of Octave's standard functions are distributed as function
  672. files.  They are loosely organized by topic, in subdirectories of
  673. `OCTAVE_HOME/lib/octave/VERSION/m', to make it easier to find them.
  674.    The following is a list of all the function file subdirectories, and
  675. the types of functions you will find there.
  676. `control'
  677.      Functions for design and simulation of automatic control systems.
  678. `elfun'
  679.      Elementary functions.
  680. `general'
  681.      Miscellaneous matrix manipulations, like `flipud', `rot90', and
  682.      `triu', as well as other basic functions, like `is_matrix',
  683.      `nargchk', etc.
  684. `image'
  685.      Image processing tools.  These functions require the X Window
  686.      System.
  687. `linear-algebra'
  688.      Functions for linear algebra.
  689. `miscellaneous'
  690.      Functions that don't really belong anywhere else.
  691. `plot'
  692.      A set of functions that implement the MATLAB-like plotting
  693.      functions.
  694. `polynomial'
  695.      Functions for manipulating polynomials.
  696. `set'
  697.      Functions for creating and manipulating sets of unique values.
  698. `signal'
  699.      Functions for signal processing applications.
  700. `specfun'
  701.      Special functions.
  702. `special-matrix'
  703.      Functions that create special matrix forms.
  704. `startup'
  705.      Octave's system-wide startup file.
  706. `statistics'
  707.      Statistical functions.
  708. `strings'
  709.      Miscellaneous string-handling functions.
  710.    *Note User Preferences:: for an explanation of the built-in variable
  711. `LOADPATH', and *Note Function Files:: for a description of the way
  712. Octave resolves undefined variable and function names.
  713. File: octave.info,  Node: Built-in Variables,  Next: Arithmetic,  Prev: Functions and Scripts,  Up: Top
  714. Built-in Variables
  715. ******************
  716.    Most Octave variables are available for you to use for your own
  717. purposes; they never change except when your program assigns values to
  718. them, and never affect anything except when your program examines them.
  719.    A few variables have special built-in meanings.  Some of them, like
  720. `pi' and `eps' provide useful predefined constant values.  Others, like
  721. `do_fortran_indexing' and `page_screen_output' are examined
  722. automatically by Octave, so that you can to tell Octave how to do
  723. certain things.  There are also two special variables, `ans' and `PWD',
  724. that are set automatically by Octave and carry information from the
  725. internal workings of Octave to your program.
  726.    This chapter documents all the built-in variables of Octave.  Most
  727. of them are also documented in the chapters that describe functions
  728. that use them, or are affected by their values.
  729. * Menu:
  730. * Predefined Constants::
  731. * User Preferences::
  732. * Other Built-in Variables::
  733. * Summary of Preference Variables::
  734. File: octave.info,  Node: Predefined Constants,  Next: User Preferences,  Prev: Built-in Variables,  Up: Built-in Variables
  735. Predefined Constants
  736. ====================
  737. `I, i, J, j'
  738.      A pure imaginary number, defined as   `sqrt (-1)'.  The `I' and
  739.      `J' forms are true constants, and cannot be modified.  The `i' and
  740.      `j' forms are like ordinary variables, and may be used for other
  741.      purposes.  However, unlike other variables, they once again assume
  742.      their special predefined values if they are cleared *Note
  743.      Miscellaneous Utilities::.
  744. `Inf, inf'
  745.      Infinity.  This is the result of an operation like 1/0, or an
  746.      operation that results in a floating point overflow.
  747. `NaN, nan'
  748.      Not a number.  This is the result of an operation like `0/0', or
  749.      `Inf - Inf', or any operation with a NaN.
  750. `SEEK_SET'
  751. `SEEK_CUR'
  752. `SEEK_END'
  753.      These variables may be used as the optional third argument for the
  754.      function `fseek'.
  755. `eps'
  756.      The machine precision.  More precisely, `eps' is the smallest value
  757.      such that `1+eps' is not equal to 1.  This number is
  758.      system-dependent.  On machines that support 64 bit IEEE floating
  759.      point arithmetic, `eps' is approximately  2.2204e-16.
  760.      The ratio of the circumference of a circle to its diameter.
  761.      Internally, `pi' is computed as `4.0 * atan (1.0)'.
  762. `realmax'
  763.      The largest floating point number that is representable.  The
  764.      actual value is system-dependent.  On machines that support 64 bit
  765.      IEEE floating point arithmetic, `realmax' is approximately
  766.      1.7977e+308
  767. `realmin'
  768.      The smallest floating point number that is representable.  The
  769.      actual value is system-dependent.  On machines that support 64 bit
  770.      IEEE floating point arithmetic, `realmin' is approximately
  771.      2.2251e-308
  772. `stdin'
  773. `stdout'
  774. `stderr'
  775.      These variables are the file numbers corresponding to the standard
  776.      input, standard output, and standard error streams.  These streams
  777.      are preconnected and available when Octave starts.
  778.