home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / octa21fb.zip / octave / doc / octave.i04 (.txt) < prev    next >
GNU Info File  |  2000-01-15  |  48KB  |  1,029 lines

  1. This is Info file octave, produced by Makeinfo-1.64 from the input file
  2. octave.tex.
  3. START-INFO-DIR-ENTRY
  4. * Octave: (octave).    Interactive language for numerical computations.
  5. END-INFO-DIR-ENTRY
  6.    Copyright (C) 1996, 1997 John W. Eaton.
  7.    Permission is granted to make and distribute verbatim copies of this
  8. manual provided the copyright notice and this permission notice are
  9. preserved on all copies.
  10.    Permission is granted to copy and distribute modified versions of
  11. this manual under the conditions for verbatim copying, provided that
  12. the entire resulting derived work is distributed under the terms of a
  13. permission notice identical to this one.
  14.    Permission is granted to copy and distribute translations of this
  15. manual into another language, under the above conditions for modified
  16. versions.
  17. File: octave,  Node: Evaluation,  Next: Statements,  Prev: Expressions,  Up: Top
  18. Evaluation
  19. **********
  20.    Normally, you evaluate expressions simply by typing them at the
  21. Octave prompt, or by asking Octave to interpret commands that you have
  22. saved in a file.
  23.    Sometimes, you may find it necessary to evaluate an expression that
  24. has been computed and stored in a string, or use a string as the name
  25. of a function to call.  The `eval' and `feval' functions allow you to
  26. do just that, and are necessary in order to evaluate commands that are
  27. not known until run time, or to write functions that will need to call
  28. user-supplied functions.
  29.  - Built-in Function:  eval (TRY, CATCH)
  30.      Parse the string TRY and evaluate it as if it were an Octave
  31.      program, returning the last value computed.  If that fails,
  32.      evaluate the string CATCH.  The string TRY is evaluated in the
  33.      current context, so any results remain available after `eval'
  34.      returns.  For example,
  35.           eval ("a = 13")
  36.                -| a = 13
  37.                => 13
  38.      In this case, the value of the evaluated expression is printed and
  39.      it is also returned returned from `eval'.  Just as with any other
  40.      expression, you can turn printing off by ending the expression in a
  41.      semicolon.  For example,
  42.           eval ("a = 13;")
  43.                => 13
  44.      In this example, the variable `a' has been given the value 13, but
  45.      the value of the expression is not printed.  You can also turn off
  46.      automatic printing for all expressions executed by `eval' using the
  47.      variable `default_eval_print_flag'.
  48.  - Built-in Variable: default_eval_print_flag
  49.      If the value of this variable is nonzero, Octave prints the
  50.      results of commands executed by `eval' that do not end with
  51.      semicolons.  If it is zero, automatic printing is suppressed.  The
  52.      default value is 1.
  53.  - Built-in Function:  feval (NAME, ...)
  54.      Evaluate the function named NAME.  Any arguments after the first
  55.      are passed on to the named function.  For example,
  56.           feval ("acos", -1)
  57.                => 3.1416
  58.      calls the function `acos' with the argument `-1'.
  59.      The function `feval' is necessary in order to be able to write
  60.      functions that call user-supplied functions, because Octave does
  61.      not have a way to declare a pointer to a function (like C) or to
  62.      declare a special kind of variable that can be used to hold the
  63.      name of a function (like `EXTERNAL' in Fortran).  Instead, you
  64.      must refer to functions by name, and use `feval' to call them.
  65.    Here is a simple-minded function using `feval' that finds the root
  66. of a user-supplied function of one variable using Newton's method.
  67.      function result = newtroot (fname, x)
  68.      
  69.      # usage: newtroot (fname, x)
  70.      #
  71.      #   fname : a string naming a function f(x).
  72.      #   x     : initial guess
  73.      
  74.        delta = tol = sqrt (eps);
  75.        maxit = 200;
  76.        fx = feval (fname, x);
  77.        for i = 1:maxit
  78.          if (abs (fx) < tol)
  79.            result = x;
  80.            return;
  81.          else
  82.            fx_new = feval (fname, x + delta);
  83.            deriv = (fx_new - fx) / delta;
  84.            x = x - fx / deriv;
  85.            fx = fx_new;
  86.          endif
  87.        endfor
  88.      
  89.        result = x;
  90.      
  91.      endfunction
  92.    Note that this is only meant to be an example of calling
  93. user-supplied functions and should not be taken too seriously.  In
  94. addition to using a more robust algorithm, any serious code would check
  95. the number and type of all the arguments, ensure that the supplied
  96. function really was a function, etc.  See *Note Predicates for Numeric
  97. Objects::, for example, for a list of predicates for numeric objects,
  98. and *Note Status of Variables::, for a description of the `exist'
  99. function.
  100.    % DO NOT EDIT!  Generated automatically by munge-texi.
  101. File: octave,  Node: Statements,  Next: Functions and Scripts,  Prev: Evaluation,  Up: Top
  102. Statements
  103. **********
  104.    Statements may be a simple constant expression or a complicated list
  105. of nested loops and conditional statements.
  106.    "Control statements" such as `if', `while', and so on control the
  107. flow of execution in Octave programs.  All the control statements start
  108. with special keywords such as `if' and `while', to distinguish them
  109. from simple expressions.  Many control statements contain other
  110. statements; for example, the `if' statement contains another statement
  111. which may or may not be executed.
  112.    Each control statement has a corresponding "end" statement that
  113. marks the end of the end of the control statement.  For example, the
  114. keyword `endif' marks the end of an `if' statement, and `endwhile'
  115. marks the end of a `while' statement.  You can use the keyword `end'
  116. anywhere a more specific end keyword is expected, but using the more
  117. specific keywords is preferred because if you use them, Octave is able
  118. to provide better diagnostics for mismatched or missing end tokens.
  119.    The list of statements contained between keywords like `if' or
  120. `while' and the corresponding end statement is called the "body" of a
  121. control statement.
  122. * Menu:
  123. * The if Statement::
  124. * The switch Statement::
  125. * The while Statement::
  126. * The for Statement::
  127. * The break Statement::
  128. * The continue Statement::
  129. * The unwind_protect Statement::
  130. * The try Statement::
  131. * Continuation Lines::
  132. File: octave,  Node: The if Statement,  Next: The switch Statement,  Prev: Statements,  Up: Statements
  133. The `if' Statement
  134. ==================
  135.    The `if' statement is Octave's decision-making statement.  There are
  136. three basic forms of an `if' statement.  In its simplest form, it looks
  137. like this:
  138.      if (CONDITION)
  139.        THEN-BODY
  140.      endif
  141. CONDITION is an expression that controls what the rest of the statement
  142. will do.  The THEN-BODY is executed only if CONDITION is true.
  143.    The condition in an `if' statement is considered true if its value
  144. is non-zero, and false if its value is zero.  If the value of the
  145. conditional expression in an `if' statement is a vector or a matrix, it
  146. is considered true only if *all* of the elements are non-zero.
  147.    The second form of an if statement looks like this:
  148.      if (CONDITION)
  149.        THEN-BODY
  150.      else
  151.        ELSE-BODY
  152.      endif
  153. If CONDITION is true, THEN-BODY is executed; otherwise, ELSE-BODY is
  154. executed.
  155.    Here is an example:
  156.      if (rem (x, 2) == 0)
  157.        printf ("x is even\n");
  158.      else
  159.        printf ("x is odd\n");
  160.      endif
  161.    In this example, if the expression `rem (x, 2) == 0' is true (that
  162. is, the value of `x' is divisible by 2), then the first `printf'
  163. statement is evaluated, otherwise the second `printf' statement is
  164. evaluated.
  165.    The third and most general form of the `if' statement allows
  166. multiple decisions to be combined in a single statement.  It looks like
  167. this:
  168.      if (CONDITION)
  169.        THEN-BODY
  170.      elseif (CONDITION)
  171.        ELSEIF-BODY
  172.      else
  173.        ELSE-BODY
  174.      endif
  175. Any number of `elseif' clauses may appear.  Each condition is tested in
  176. turn, and if one is found to be true, its corresponding BODY is
  177. executed.  If none of the conditions are true and the `else' clause is
  178. present, its body is executed.  Only one `else' clause may appear, and
  179. it must be the last part of the statement.
  180.    In the following example, if the first condition is true (that is,
  181. the value of `x' is divisible by 2), then the first `printf' statement
  182. is executed.  If it is false, then the second condition is tested, and
  183. if it is true (that is, the value of `x' is divisible by 3), then the
  184. second `printf' statement is executed.  Otherwise, the third `printf'
  185. statement is performed.
  186.      if (rem (x, 2) == 0)
  187.        printf ("x is even\n");
  188.      elseif (rem (x, 3) == 0)
  189.        printf ("x is odd and divisible by 3\n");
  190.      else
  191.        printf ("x is odd\n");
  192.      endif
  193.    Note that the `elseif' keyword must not be spelled `else if', as is
  194. allowed in Fortran.  If it is, the space between the `else' and `if'
  195. will tell Octave to treat this as a new `if' statement within another
  196. `if' statement's `else' clause.  For example, if you write
  197.      if (C1)
  198.        BODY-1
  199.      else if (C2)
  200.        BODY-2
  201.      endif
  202. Octave will expect additional input to complete the first `if'
  203. statement.  If you are using Octave interactively, it will continue to
  204. prompt you for additional input.  If Octave is reading this input from a
  205. file, it may complain about missing or mismatched `end' statements, or,
  206. if you have not used the more specific `end' statements (`endif',
  207. `endfor', etc.), it may simply produce incorrect results, without
  208. producing any warning messages.
  209.    It is much easier to see the error if we rewrite the statements above
  210. like this,
  211.      if (C1)
  212.        BODY-1
  213.      else
  214.        if (C2)
  215.          BODY-2
  216.        endif
  217. using the indentation to show how Octave groups the statements.  *Note
  218. Functions and Scripts::.
  219.  - Built-in Variable: warn_assign_as_truth_value
  220.      If the value of `warn_assign_as_truth_value' is nonzero, a warning
  221.      is issued for statements like
  222.           if (s = t)
  223.             ...
  224.      since such statements are not common, and it is likely that the
  225.      intent was to write
  226.           if (s == t)
  227.             ...
  228.      instead.
  229.      There are times when it is useful to write code that contains
  230.      assignments within the condition of a `while' or `if' statement.
  231.      For example, statements like
  232.           while (c = getc())
  233.             ...
  234.      are common in C programming.
  235.      It is possible to avoid all warnings about such statements by
  236.      setting `warn_assign_as_truth_value' to 0, but that may also let
  237.      real errors like
  238.           if (x = 1)  # intended to test (x == 1)!
  239.             ...
  240.      slip by.
  241.      In such cases, it is possible suppress errors for specific
  242.      statements by writing them with an extra set of parentheses.  For
  243.      example, writing the previous example as
  244.           while ((c = getc()))
  245.             ...
  246.      will prevent the warning from being printed for this statement,
  247.      while allowing Octave to warn about other assignments used in
  248.      conditional contexts.
  249.      The default value of `warn_assign_as_truth_value' is 1.
  250. File: octave,  Node: The switch Statement,  Next: The while Statement,  Prev: The if Statement,  Up: Statements
  251. The `switch' Statement
  252. ======================
  253.    The `switch' statement was introduced in Octave 2.0.5.  It should be
  254. considered experimental, and details of the implementation may change
  255. slightly in future versions of Octave.  If you have comments or would
  256. like to share your experiences in trying to use this new command in real
  257. programs, please send them to (octave-maintainers@bevo.che.wisc.edu).
  258. (But if you think you've found a bug, please report it to
  259. (bug-octave@bevo.che.wisc.edu).
  260.    The general form of the `switch' statement is
  261.      switch EXPRESSION
  262.        case LABEL
  263.          COMMAND_LIST
  264.        case LABEL
  265.          COMMAND_LIST
  266.        ...
  267.      
  268.        otherwise
  269.          COMMAND_LIST
  270.      endswitch
  271.    * The identifiers `switch', `case', `otherwise', and `endswitch' are
  272.      now keywords.
  273.    * The LABEL may be any expression.
  274.    * Duplicate LABEL values are not detected.  The COMMAND_LIST
  275.      corresponding to the first match will be executed.
  276.    * You must have at least one `case LABEL COMMAND_LIST' clause.
  277.    * The `otherwise COMMAND_LIST' clause is optional.
  278.    * As with all other specific `end' keywords, `endswitch' may be
  279.      replaced by `end', but you can get better diagnostics if you use
  280.      the specific forms.
  281.    * Cases are exclusive, so they don't `fall through' as do the cases
  282.      in the switch statement of the C language.
  283.    * The COMMAND_LIST elements are not optional.  Making the list
  284.      optional would have meant requiring a separator between the label
  285.      and the command list.  Otherwise, things like
  286.           switch (foo)
  287.             case (1) -2
  288.             ...
  289.      would produce surprising results, as would
  290.           switch (foo)
  291.             case (1)
  292.             case (2)
  293.               doit ();
  294.             ...
  295.      particularly for C programmers.
  296.    * The implementation is simple-minded and currently offers no real
  297.      performance improvement over an equivalent `if' block, even if all
  298.      the labels are integer constants.  Perhaps a future variation on
  299.      this could detect all constant integer labels and improve
  300.      performance by using a jump table.
  301.  - Built-in Variable: warn_variable_switch_label
  302.      If the value of this variable is nonzero, Octave will print a
  303.      warning if a switch label is not a constant or constant expression
  304. File: octave,  Node: The while Statement,  Next: The for Statement,  Prev: The switch Statement,  Up: Statements
  305. The `while' Statement
  306. =====================
  307.    In programming, a "loop" means a part of a program that is (or at
  308. least can be) executed two or more times in succession.
  309.    The `while' statement is the simplest looping statement in Octave.
  310. It repeatedly executes a statement as long as a condition is true.  As
  311. with the condition in an `if' statement, the condition in a `while'
  312. statement is considered true if its value is non-zero, and false if its
  313. value is zero.  If the value of the conditional expression in a `while'
  314. statement is a vector or a matrix, it is considered true only if *all*
  315. of the elements are non-zero.
  316.    Octave's `while' statement looks like this:
  317.      while (CONDITION)
  318.        BODY
  319.      endwhile
  320. Here BODY is a statement or list of statements that we call the "body"
  321. of the loop, and CONDITION is an expression that controls how long the
  322. loop keeps running.
  323.    The first thing the `while' statement does is test CONDITION.  If
  324. CONDITION is true, it executes the statement BODY.  After BODY has been
  325. executed, CONDITION is tested again, and if it is still true, BODY is
  326. executed again.  This process repeats until CONDITION is no longer
  327. true.  If CONDITION is initially false, the body of the loop is never
  328. executed.
  329.    This example creates a variable `fib' that contains the first ten
  330. elements of the Fibonacci sequence.
  331.      fib = ones (1, 10);
  332.      i = 3;
  333.      while (i <= 10)
  334.        fib (i) = fib (i-1) + fib (i-2);
  335.        i++;
  336.      endwhile
  337. Here the body of the loop contains two statements.
  338.    The loop works like this: first, the value of `i' is set to 3.
  339. Then, the `while' tests whether `i' is less than or equal to 10.  This
  340. is the case when `i' equals 3, so the value of the `i'-th element of
  341. `fib' is set to the sum of the previous two values in the sequence.
  342. Then the `i++' increments the value of `i' and the loop repeats.  The
  343. loop terminates when `i' reaches 11.
  344.    A newline is not required between the condition and the body; but
  345. using one makes the program clearer unless the body is very simple.
  346.    *Note The if Statement:: for a description of the variable
  347. `warn_assign_as_truth_value'.
  348. File: octave,  Node: The for Statement,  Next: The break Statement,  Prev: The while Statement,  Up: Statements
  349. The `for' Statement
  350. ===================
  351.    The `for' statement makes it more convenient to count iterations of a
  352. loop.  The general form of the `for' statement looks like this:
  353.      for VAR = EXPRESSION
  354.        BODY
  355.      endfor
  356. where BODY stands for any statement or list of statements, EXPRESSION
  357. is any valid expression, and VAR may take several forms.  Usually it is
  358. a simple variable name or an indexed variable.  If the value of
  359. EXPRESSION is a structure, VAR may also be a list.  *Note Looping Over
  360. Structure Elements::, below.
  361.    The assignment expression in the `for' statement works a bit
  362. differently than Octave's normal assignment statement.  Instead of
  363. assigning the complete result of the expression, it assigns each column
  364. of the expression to VAR in turn.  If EXPRESSION is a range, a row
  365. vector, or a scalar, the value of VAR will be a scalar each time the
  366. loop body is executed.  If VAR is a column vector or a matrix, VAR will
  367. be a column vector each time the loop body is executed.
  368.    The following example shows another way to create a vector containing
  369. the first ten elements of the Fibonacci sequence, this time using the
  370. `for' statement:
  371.      fib = ones (1, 10);
  372.      for i = 3:10
  373.        fib (i) = fib (i-1) + fib (i-2);
  374.      endfor
  375. This code works by first evaluating the expression `3:10', to produce a
  376. range of values from 3 to 10 inclusive.  Then the variable `i' is
  377. assigned the first element of the range and the body of the loop is
  378. executed once.  When the end of the loop body is reached, the next
  379. value in the range is assigned to the variable `i', and the loop body
  380. is executed again.  This process continues until there are no more
  381. elements to assign.
  382.    Although it is possible to rewrite all `for' loops as `while' loops,
  383. the Octave language has both statements because often a `for' loop is
  384. both less work to type and more natural to think of.  Counting the
  385. number of iterations is very common in loops and it can be easier to
  386. think of this counting as part of looping rather than as something to
  387. do inside the loop.
  388. * Menu:
  389. * Looping Over Structure Elements::
  390. File: octave,  Node: Looping Over Structure Elements,  Prev: The for Statement,  Up: The for Statement
  391. Looping Over Structure Elements
  392. -------------------------------
  393.    A special form of the `for' statement allows you to loop over all
  394. the elements of a structure:
  395.      for [ VAL, KEY ] = EXPRESSION
  396.        BODY
  397.      endfor
  398. In this form of the `for' statement, the value of EXPRESSION must be a
  399. structure.  If it is, KEY and VAL are set to the name of the element
  400. and the corresponding value in turn, until there are no more elements.
  401. For example,
  402.      x.a = 1
  403.      x.b = [1, 2; 3, 4]
  404.      x.c = "string"
  405.      for [val, key] = x
  406.        key
  407.        val
  408.      endfor
  409.      
  410.           -| key = a
  411.           -| val = 1
  412.           -| key = b
  413.           -| val =
  414.           -|
  415.           -|   1  2
  416.           -|   3  4
  417.           -|
  418.           -| key = c
  419.           -| val = string
  420.    The elements are not accessed in any particular order.  If you need
  421. to cycle through the list in a particular way, you will have to use the
  422. function `struct_elements' and sort the list yourself.
  423.    The KEY variable may also be omitted.  If it is, the brackets are
  424. also optional.  This is useful for cycling through the values of all the
  425. structure elements when the names of the elements do not need to be
  426. known.
  427. File: octave,  Node: The break Statement,  Next: The continue Statement,  Prev: The for Statement,  Up: Statements
  428. The `break' Statement
  429. =====================
  430.    The `break' statement jumps out of the innermost `for' or `while'
  431. loop that encloses it.  The `break' statement may only be used within
  432. the body of a loop.  The following example finds the smallest divisor
  433. of a given integer, and also identifies prime numbers:
  434.      num = 103;
  435.      div = 2;
  436.      while (div*div <= num)
  437.        if (rem (num, div) == 0)
  438.          break;
  439.        endif
  440.        div++;
  441.      endwhile
  442.      if (rem (num, div) == 0)
  443.        printf ("Smallest divisor of %d is %d\n", num, div)
  444.      else
  445.        printf ("%d is prime\n", num);
  446.      endif
  447.    When the remainder is zero in the first `while' statement, Octave
  448. immediately "breaks out" of the loop.  This means that Octave proceeds
  449. immediately to the statement following the loop and continues
  450. processing.  (This is very different from the `exit' statement which
  451. stops the entire Octave program.)
  452.    Here is another program equivalent to the previous one.  It
  453. illustrates how the CONDITION of a `while' statement could just as well
  454. be replaced with a `break' inside an `if':
  455.      num = 103;
  456.      div = 2;
  457.      while (1)
  458.        if (rem (num, div) == 0)
  459.          printf ("Smallest divisor of %d is %d\n", num, div);
  460.          break;
  461.        endif
  462.        div++;
  463.        if (div*div > num)
  464.          printf ("%d is prime\n", num);
  465.          break;
  466.        endif
  467.      endwhile
  468. File: octave,  Node: The continue Statement,  Next: The unwind_protect Statement,  Prev: The break Statement,  Up: Statements
  469. The `continue' Statement
  470. ========================
  471.    The `continue' statement, like `break', is used only inside `for' or
  472. `while' loops.  It skips over the rest of the loop body, causing the
  473. next cycle around the loop to begin immediately.  Contrast this with
  474. `break', which jumps out of the loop altogether.  Here is an example:
  475.      # print elements of a vector of random
  476.      # integers that are even.
  477.      
  478.      # first, create a row vector of 10 random
  479.      # integers with values between 0 and 100:
  480.      
  481.      vec = round (rand (1, 10) * 100);
  482.      
  483.      # print what we're interested in:
  484.      
  485.      for x = vec
  486.        if (rem (x, 2) != 0)
  487.          continue;
  488.        endif
  489.        printf ("%d\n", x);
  490.      endfor
  491.    If one of the elements of VEC is an odd number, this example skips
  492. the print statement for that element, and continues back to the first
  493. statement in the loop.
  494.    This is not a practical example of the `continue' statement, but it
  495. should give you a clear understanding of how it works.  Normally, one
  496. would probably write the loop like this:
  497.      for x = vec
  498.        if (rem (x, 2) == 0)
  499.          printf ("%d\n", x);
  500.        endif
  501.      endfor
  502. File: octave,  Node: The unwind_protect Statement,  Next: The try Statement,  Prev: The continue Statement,  Up: Statements
  503. The `unwind_protect' Statement
  504. ==============================
  505.    Octave supports a limited form of exception handling modelled after
  506. the unwind-protect form of Lisp.
  507.    The general form of an `unwind_protect' block looks like this:
  508.      unwind_protect
  509.        BODY
  510.      unwind_protect_cleanup
  511.        CLEANUP
  512.      end_unwind_protect
  513. Where BODY and CLEANUP are both optional and may contain any Octave
  514. expressions or commands.  The statements in CLEANUP are guaranteed to
  515. be executed regardless of how control exits BODY.
  516.    This is useful to protect temporary changes to global variables from
  517. possible errors.  For example, the following code will always restore
  518. the original value of the built-in variable `do_fortran_indexing' even
  519. if an error occurs while performing the indexing operation.
  520.      save_do_fortran_indexing = do_fortran_indexing;
  521.      unwind_protect
  522.        do_fortran_indexing = 1;
  523.        elt = a (idx)
  524.      unwind_protect_cleanup
  525.        do_fortran_indexing = save_do_fortran_indexing;
  526.      end_unwind_protect
  527.    Without `unwind_protect', the value of DO_FORTRAN_INDEXING would not
  528. be restored if an error occurs while performing the indexing operation
  529. because evaluation would stop at the point of the error and the
  530. statement to restore the value would not be executed.
  531. File: octave,  Node: The try Statement,  Next: Continuation Lines,  Prev: The unwind_protect Statement,  Up: Statements
  532. The `try' Statement
  533. ===================
  534.    In addition to unwind_protect, Octave supports another limited form
  535. of exception handling.
  536.    The general form of a `try' block looks like this:
  537.      try
  538.        BODY
  539.      catch
  540.        CLEANUP
  541.      end_try_catch
  542.    Where BODY and CLEANUP are both optional and may contain any Octave
  543. expressions or commands.  The statements in CLEANUP are only executed
  544. if an error occurs in BODY.
  545.    No warnings or error messages are printed while BODY is executing.
  546. If an error does occur during the execution of BODY, CLEANUP can access
  547. the text of the message that would have been printed in the builtin
  548. constant `__error_text__'.  This is the same as `eval (TRY, CATCH)'
  549. (which may now also use `__error_text__') but it is more efficient
  550. since the commands do not need to be parsed each time the TRY and CATCH
  551. statements are evaluated.  *Note Error Handling::, for more information
  552. about the `__error_text__' variable.
  553.    Octave's TRY block is a very limited variation on the Lisp
  554. condition-case form (limited because it cannot handle different classes
  555. of errors separately).  Perhaps at some point Octave can have some sort
  556. of classification of errors and try-catch can be improved to be as
  557. powerful as condition-case in Lisp.
  558. File: octave,  Node: Continuation Lines,  Prev: The try Statement,  Up: Statements
  559. Continuation Lines
  560. ==================
  561.    In the Octave language, most statements end with a newline character
  562. and you must tell Octave to ignore the newline character in order to
  563. continue a statement from one line to the next.  Lines that end with the
  564. characters `...' or `\' are joined with the following line before they
  565. are divided into tokens by Octave's parser.  For example, the lines
  566.      x = long_variable_name ...
  567.          + longer_variable_name \
  568.          - 42
  569. form a single statement.  The backslash character on the second line
  570. above is interpreted a continuation character, *not* as a division
  571. operator.
  572.    For continuation lines that do not occur inside string constants,
  573. whitespace and comments may appear between the continuation marker and
  574. the newline character.  For example, the statement
  575.      x = long_variable_name ...     # comment one
  576.          + longer_variable_name \   # comment two
  577.          - 42                       # last comment
  578. is equivalent to the one shown above.  Inside string constants, the
  579. continuation marker must appear at the end of the line just before the
  580. newline character.
  581.    Input that occurs inside parentheses can be continued to the next
  582. line without having to use a continuation marker.  For example, it is
  583. possible to write statements like
  584.      if (fine_dining_destination == on_a_boat
  585.          || fine_dining_destination == on_a_train)
  586.        suess (i, will, not, eat, them, sam, i, am, i,
  587.               will, not, eat, green, eggs, and, ham);
  588.      endif
  589. without having to add to the clutter with continuation markers.
  590.    % DO NOT EDIT!  Generated automatically by munge-texi.
  591. File: octave,  Node: Functions and Scripts,  Next: Error Handling,  Prev: Statements,  Up: Top
  592. Functions and Script Files
  593. **************************
  594.    Complicated Octave programs can often be simplified by defining
  595. functions.  Functions can be defined directly on the command line during
  596. interactive Octave sessions, or in external files, and can be called
  597. just like built-in functions.
  598. * Menu:
  599. * Defining Functions::
  600. * Multiple Return Values::
  601. * Variable-length Argument Lists::
  602. * Variable-length Return Lists::
  603. * Returning From a Function::
  604. * Function Files::
  605. * Script Files::
  606. * Dynamically Linked Functions::
  607. * Organization of Functions::
  608. File: octave,  Node: Defining Functions,  Next: Multiple Return Values,  Prev: Functions and Scripts,  Up: Functions and Scripts
  609. Defining Functions
  610. ==================
  611.    In its simplest form, the definition of a function named NAME looks
  612. like this:
  613.      function NAME
  614.        BODY
  615.      endfunction
  616. A valid function name is like a valid variable name: a sequence of
  617. letters, digits and underscores, not starting with a digit.  Functions
  618. share the same pool of names as variables.
  619.    The function BODY consists of Octave statements.  It is the most
  620. important part of the definition, because it says what the function
  621. should actually *do*.
  622.    For example, here is a function that, when executed, will ring the
  623. bell on your terminal (assuming that it is possible to do so):
  624.      function wakeup
  625.        printf ("\a");
  626.      endfunction
  627.    The `printf' statement (*note Input and Output::.) simply tells
  628. Octave to print the string `"\a"'.  The special character `\a' stands
  629. for the alert character (ASCII 7).  *Note Strings::.
  630.    Once this function is defined, you can ask Octave to evaluate it by
  631. typing the name of the function.
  632.    Normally, you will want to pass some information to the functions you
  633. define.  The syntax for passing parameters to a function in Octave is
  634.      function NAME (ARG-LIST)
  635.        BODY
  636.      endfunction
  637. where ARG-LIST is a comma-separated list of the function's arguments.
  638. When the function is called, the argument names are used to hold the
  639. argument values given in the call.  The list of arguments may be empty,
  640. in which case this form is equivalent to the one shown above.
  641.    To print a message along with ringing the bell, you might modify the
  642. `beep' to look like this:
  643.      function wakeup (message)
  644.        printf ("\a%s\n", message);
  645.      endfunction
  646.    Calling this function using a statement like this
  647.      wakeup ("Rise and shine!");
  648. will cause Octave to ring your terminal's bell and print the message
  649. `Rise and shine!', followed by a newline character (the `\n' in the
  650. first argument to the `printf' statement).
  651.    In most cases, you will also want to get some information back from
  652. the functions you define.  Here is the syntax for writing a function
  653. that returns a single value:
  654.      function RET-VAR = NAME (ARG-LIST)
  655.        BODY
  656.      endfunction
  657. The symbol RET-VAR is the name of the variable that will hold the value
  658. to be returned by the function.  This variable must be defined before
  659. the end of the function body in order for the function to return a
  660. value.
  661.    Variables used in the body of a function are local to the function.
  662. Variables named in ARG-LIST and RET-VAR are also local to the function.
  663. *Note Global Variables::, for information about how to access global
  664. variables inside a function.
  665.    For example, here is a function that computes the average of the
  666. elements of a vector:
  667.      function retval = avg (v)
  668.        retval = sum (v) / length (v);
  669.      endfunction
  670.    If we had written `avg' like this instead,
  671.      function retval = avg (v)
  672.        if (is_vector (v))
  673.          retval = sum (v) / length (v);
  674.        endif
  675.      endfunction
  676. and then called the function with a matrix instead of a vector as the
  677. argument, Octave would have printed an error message like this:
  678.      error: `retval' undefined near line 1 column 10
  679.      error: evaluating index expression near line 7, column 1
  680. because the body of the `if' statement was never executed, and `retval'
  681. was never defined.  To prevent obscure errors like this, it is a good
  682. idea to always make sure that the return variables will always have
  683. values, and to produce meaningful error messages when problems are
  684. encountered.  For example, `avg' could have been written like this:
  685.      function retval = avg (v)
  686.        retval = 0;
  687.        if (is_vector (v))
  688.          retval = sum (v) / length (v);
  689.        else
  690.          error ("avg: expecting vector argument");
  691.        endif
  692.      endfunction
  693.    There is still one additional problem with this function.  What if
  694. it is called without an argument?  Without additional error checking,
  695. Octave will probably print an error message that won't really help you
  696. track down the source of the error.  To allow you to catch errors like
  697. this, Octave provides each function with an automatic variable called
  698. `nargin'.  Each time a function is called, `nargin' is automatically
  699. initialized to the number of arguments that have actually been passed
  700. to the function.  For example, we might rewrite the `avg' function like
  701. this:
  702.      function retval = avg (v)
  703.        retval = 0;
  704.        if (nargin != 1)
  705.          usage ("avg (vector)");
  706.        endif
  707.        if (is_vector (v))
  708.          retval = sum (v) / length (v);
  709.        else
  710.          error ("avg: expecting vector argument");
  711.        endif
  712.      endfunction
  713.    Although Octave does not automatically report an error if you call a
  714. function with more arguments than expected, doing so probably indicates
  715. that something is wrong.  Octave also does not automatically report an
  716. error if a function is called with too few arguments, but any attempt to
  717. use a variable that has not been given a value will result in an error.
  718. To avoid such problems and to provide useful messages, we check for both
  719. possibilities and issue our own error message.
  720.  - Automatic Variable: nargin
  721.      When a function is called, this local variable is automatically
  722.      initialized to the number of arguments passed to the function.  At
  723.      the top level, `nargin' holds the number of command line arguments
  724.      that were passed to Octave.
  725.  - Built-in Variable: silent_functions
  726.      If the value of `silent_functions' is nonzero, internal output
  727.      from a function is suppressed.  Otherwise, the results of
  728.      expressions within a function body that are not terminated with a
  729.      semicolon will have their values printed.  The default value is 0.
  730.      For example, if the function
  731.           function f ()
  732.             2 + 2
  733.           endfunction
  734.      is executed, Octave will either print `ans = 4' or nothing
  735.      depending on the value of `silent_functions'.
  736.  - Built-in Variable: warn_missing_semicolon
  737.      If the value of this variable is nonzero, Octave will warn when
  738.      statements in function definitions don't end in semicolons.  The
  739.      default value is 0.
  740. File: octave,  Node: Multiple Return Values,  Next: Variable-length Argument Lists,  Prev: Defining Functions,  Up: Functions and Scripts
  741. Multiple Return Values
  742. ======================
  743.    Unlike many other computer languages, Octave allows you to define
  744. functions that return more than one value.  The syntax for defining
  745. functions that return multiple values is
  746.      function [RET-LIST] = NAME (ARG-LIST)
  747.        BODY
  748.      endfunction
  749. where NAME, ARG-LIST, and BODY have the same meaning as before, and
  750. RET-LIST is a comma-separated list of variable names that will hold the
  751. values returned from the function.  The list of return values must have
  752. at least one element.  If RET-LIST has only one element, this form of
  753. the `function' statement is equivalent to the form described in the
  754. previous section.
  755.    Here is an example of a function that returns two values, the maximum
  756. element of a vector and the index of its first occurrence in the vector.
  757.      function [max, idx] = vmax (v)
  758.        idx = 1;
  759.        max = v (idx);
  760.        for i = 2:length (v)
  761.          if (v (i) > max)
  762.            max = v (i);
  763.            idx = i;
  764.          endif
  765.        endfor
  766.      endfunction
  767.    In this particular case, the two values could have been returned as
  768. elements of a single array, but that is not always possible or
  769. convenient.  The values to be returned may not have compatible
  770. dimensions, and it is often desirable to give the individual return
  771. values distinct names.
  772.    In addition to setting `nargin' each time a function is called,
  773. Octave also automatically initializes `nargout' to the number of values
  774. that are expected to be returned.  This allows you to write functions
  775. that behave differently depending on the number of values that the user
  776. of the function has requested.  The implicit assignment to the built-in
  777. variable `ans' does not figure in the count of output arguments, so the
  778. value of `nargout' may be zero.
  779.    The `svd' and `lu' functions are examples of built-in functions that
  780. behave differently depending on the value of `nargout'.
  781.    It is possible to write functions that only set some return values.
  782. For example, calling the function
  783.      function [x, y, z] = f ()
  784.        x = 1;
  785.        z = 2;
  786.      endfunction
  787.      [a, b, c] = f ()
  788. produces:
  789.      a = 1
  790.      
  791.      b = [](0x0)
  792.      
  793.      c = 2
  794. provided that the built-in variable `define_all_return_values' is
  795. nonzero and the value of `default_return_value' is `[]'.  *Note Summary
  796. of Built-in Variables::.
  797.  - Automatic Variable: nargout
  798.      When a function is called, this local variable is automatically
  799.      initialized to the number of arguments expected to be returned.
  800.      For example,
  801.           f ()
  802.      will result in `nargout' being set to 0 inside the function `f' and
  803.           [s, t] = f ()
  804.      will result in `nargout' being set to 2 inside the function `f'.
  805.      At the top level, `nargout' is undefined.
  806.  - Built-in Variable: default_return_value
  807.      The value given to otherwise uninitialized return values if
  808.      `define_all_return_values' is nonzero.  The default value is `[]'.
  809.  - Built-in Variable: define_all_return_values
  810.      If the value of `define_all_return_values' is nonzero, Octave will
  811.      substitute the value specified by `default_return_value' for any
  812.      return values that remain undefined when a function returns.  The
  813.      default value is 0.
  814.  - Function File:  nargchk (NARGIN_MIN, NARGIN_MAX, N)
  815.      If N is in the range NARGIN_MIN through NARGIN_MAX  inclusive,
  816.      return the empty matrix.  Otherwise, return a message  indicating
  817.      whether N is too large or too small.
  818.      This is useful for checking to see that the number of arguments
  819.      supplied  to a function is within an acceptable range.
  820. File: octave,  Node: Variable-length Argument Lists,  Next: Variable-length Return Lists,  Prev: Multiple Return Values,  Up: Functions and Scripts
  821. Variable-length Argument Lists
  822. ==============================
  823.    Octave has a real mechanism for handling functions that take an
  824. unspecified number of arguments, so it is not necessary to place an
  825. upper bound on the number of optional arguments that a function can
  826. accept.
  827.    Here is an example of a function that uses the new syntax to print a
  828. header followed by an unspecified number of values:
  829.      function foo (heading, ...)
  830.        disp (heading);
  831.        va_start ();
  832.        ## Pre-decrement to skip `heading' arg.
  833.        while (--nargin)
  834.          disp (va_arg ());
  835.        endwhile
  836.      endfunction
  837.    The ellipsis that marks the variable argument list may only appear
  838. once and must be the last element in the list of arguments.
  839.    va_arg (): return next argument in a function that takes a variable
  840. number of parameters
  841.    va_start (): reset the pointer to the list of optional arguments to
  842. the beginning
  843.    Sometimes it is useful to be able to pass all unnamed arguments to
  844. another function.  The keyword ALL_VA_ARGS makes this very easy to do.
  845. For example,
  846.      function f (...)
  847.        while (nargin--)
  848.          disp (va_arg ())
  849.        endwhile
  850.      endfunction
  851.      
  852.      function g (...)
  853.        f ("begin", all_va_args, "end")
  854.      endfunction
  855.      
  856.      g (1, 2, 3)
  857.      
  858.           -| begin
  859.           -| 1
  860.           -| 2
  861.           -| 3
  862.           -| end
  863.  - Keyword: all_va_args
  864.      This keyword stands for the entire list of optional argument, so
  865.      it is possible to use it more than once within the same function
  866.      without having to call `va_start'.  It can only be used within
  867.      functions that take a variable number of arguments.  It is an
  868.      error to use it in other contexts.
  869. File: octave,  Node: Variable-length Return Lists,  Next: Returning From a Function,  Prev: Variable-length Argument Lists,  Up: Functions and Scripts
  870. Variable-length Return Lists
  871. ============================
  872.    Octave also has a real mechanism for handling functions that return
  873. an unspecified number of values, so it is no longer necessary to place
  874. an upper bound on the number of outputs that a function can produce.
  875.    Here is an example of a function that uses a variable-length return
  876. list to produce N values:
  877.      function [...] = f (n, x)
  878.        for i = 1:n
  879.          vr_val (i * x);
  880.        endfor
  881.      endfunction
  882.      
  883.      [dos, quatro] = f (2, 2)
  884.           => dos = 2
  885.           => quatro = 4
  886.    As with variable argument lists, the ellipsis that marks the variable
  887. return list may only appear once and must be the last element in the
  888. list of returned values.
  889.    vr_val (X): append X to the list of optional return values for a
  890. function that allows a variable number of return values
  891. File: octave,  Node: Returning From a Function,  Next: Function Files,  Prev: Variable-length Return Lists,  Up: Functions and Scripts
  892. Returning From a Function
  893. =========================
  894.    The body of a user-defined function can contain a `return' statement.
  895. This statement returns control to the rest of the Octave program.  It
  896. looks like this:
  897.      return
  898.    Unlike the `return' statement in C, Octave's `return' statement
  899. cannot be used to return a value from a function.  Instead, you must
  900. assign values to the list of return variables that are part of the
  901. `function' statement.  The `return' statement simply makes it easier to
  902. exit a function from a deeply nested loop or conditional statement.
  903.    Here is an example of a function that checks to see if any elements
  904. of a vector are nonzero.
  905.      function retval = any_nonzero (v)
  906.        retval = 0;
  907.        for i = 1:length (v)
  908.          if (v (i) != 0)
  909.            retval = 1;
  910.            return;
  911.          endif
  912.        endfor
  913.        printf ("no nonzero elements found\n");
  914.      endfunction
  915.    Note that this function could not have been written using the
  916. `break' statement to exit the loop once a nonzero value is found
  917. without adding extra logic to avoid printing the message if the vector
  918. does contain a nonzero element.
  919.  - Keyword: return
  920.      When Octave encounters the keyword `return' inside a function or
  921.      script, it returns control to be caller immediately.  At the top
  922.      level, the return statement is ignored.  A `return' statement is
  923.      assumed at the end of every function definition.
  924.  - Built-in Variable: return_last_computed_value
  925.      If the value of `return_last_computed_value' is true, and a
  926.      function is defined without explicitly specifying a return value,
  927.      the function will return the value of the last expression.
  928.      Otherwise, no value will be returned.  The default value is 0.
  929.      For example, the function
  930.           function f ()
  931.             2 + 2;
  932.           endfunction
  933.      will either return nothing, if the value of
  934.      `return_last_computed_value' is 0, or 4, if the value of
  935.      `return_last_computed_value' is nonzero.
  936. File: octave,  Node: Function Files,  Next: Script Files,  Prev: Returning From a Function,  Up: Functions and Scripts
  937. Function Files
  938. ==============
  939.    Except for simple one-shot programs, it is not practical to have to
  940. define all the functions you need each time you need them.  Instead, you
  941. will normally want to save them in a file so that you can easily edit
  942. them, and save them for use at a later time.
  943.    Octave does not require you to load function definitions from files
  944. before using them.  You simply need to put the function definitions in a
  945. place where Octave can find them.
  946.    When Octave encounters an identifier that is undefined, it first
  947. looks for variables or functions that are already compiled and currently
  948. listed in its symbol table.  If it fails to find a definition there, it
  949. searches the list of directories specified by the built-in variable
  950. `LOADPATH' for files ending in `.m' that have the same base name as the
  951. undefined identifier.(1)  Once Octave finds a file with a name that
  952. matches, the contents of the file are read.  If it defines a *single*
  953. function, it is compiled and executed.  *Note Script Files::, for more
  954. information about how you can define more than one function in a single
  955. file.
  956.    When Octave defines a function from a function file, it saves the
  957. full name of the file it read and the time stamp on the file.  After
  958. that, it checks the time stamp on the file every time it needs the
  959. function.  If the time stamp indicates that the file has changed since
  960. the last time it was read, Octave reads it again.
  961.    Checking the time stamp allows you to edit the definition of a
  962. function while Octave is running, and automatically use the new function
  963. definition without having to restart your Octave session.  Checking the
  964. time stamp every time a function is used is rather inefficient, but it
  965. has to be done to ensure that the correct function definition is used.
  966.    To avoid degrading performance unnecessarily by checking the time
  967. stamps on functions that are not likely to change, Octave assumes that
  968. function files in the directory tree
  969. `OCTAVE-HOME/share/octave/VERSION/m' will not change, so it doesn't
  970. have to check their time stamps every time the functions defined in
  971. those files are used.  This is normally a very good assumption and
  972. provides a significant improvement in performance for the function
  973. files that are distributed with Octave.
  974.    If you know that your own function files will not change while you
  975. are running Octave, you can improve performance by setting the variable
  976. `ignore_function_time_stamp' to `"all"', so that Octave will ignore the
  977. time stamps for all function files.  Setting it to `"system"' gives the
  978. default behavior.  If you set it to anything else, Octave will check
  979. the time stamps on all function files.
  980.  - Built-in Variable: DEFAULT_LOADPATH
  981.      A colon separated list of directories in which to search for
  982.      function files by default.  The value of this variable is also
  983.      automatically substituted for leading, trailing, or doubled colons
  984.      that appear in the built-in variable `LOADPATH'.
  985.  - Built-in Variable: LOADPATH
  986.      A colon separated list of directories in which to search for
  987.      function files.  *Note Functions and Scripts::.  The value of
  988.      `LOADPATH' overrides the environment variable `OCTAVE_PATH'.
  989.      *Note Installation::.
  990.      `LOADPATH' is now handled in the same way as TeX handles
  991.      `TEXINPUTS'.  Leading, trailing, or doubled colons that appear in
  992.      `LOADPATH' are replaced by the value of `DEFAULT_LOADPATH'.  The
  993.      default value of `LOADPATH' is `":"', which tells Octave to search
  994.      in the directories specified by `DEFAULT_LOADPATH'.
  995.      In addition, if any path element ends in `//', that directory and
  996.      all subdirectories it contains are searched recursively for
  997.      function files.  This can result in a slight delay as Octave
  998.      caches the lists of files found in the `LOADPATH' the first time
  999.      Octave searches for a function.  After that, searching is usually
  1000.      much faster because Octave normally only needs to search its
  1001.      internal cache for files.
  1002.      To improve performance of recursive directory searching, it is
  1003.      best for each directory that is to be searched recursively to
  1004.      contain *either* additional subdirectories *or* function files, but
  1005.      not a mixture of both.
  1006.      *Note Organization of Functions:: for a description of the
  1007.      function file directories that are distributed with Octave.
  1008.  - Built-in Variable: ignore_function_time_stamp
  1009.      This variable can be used to prevent Octave from making the system
  1010.      call `stat' each time it looks up functions defined in function
  1011.      files.  If `ignore_function_time_stamp' to `"system"', Octave will
  1012.      not automatically recompile function files in subdirectories of
  1013.      `OCTAVE-HOME/lib/VERSION' if they have changed since they were
  1014.      last compiled, but will recompile other function files in the
  1015.      `LOADPATH' if they change.  If set to `"all"', Octave will not
  1016.      recompile any function files unless their definitions are removed
  1017.      with `clear'.  For any other value of `ignore_function_time_stamp',
  1018.      Octave will always check to see if functions defined in function
  1019.      files need to recompiled.  The default value of
  1020.      `ignore_function_time_stamp' is `"system"'.
  1021.  - Built-in Variable: warn_function_name_clash
  1022.      If the value of `warn_function_name_clash' is nonzero, a warning is
  1023.      issued when Octave finds that the name of a function defined in a
  1024.      function file differs from the name of the file.  (If the names
  1025.      disagree, the name declared inside the file is ignored.)  If the
  1026.      value is 0, the warning is omitted.  The default value is 1.
  1027.    ---------- Footnotes ----------
  1028.    (1)  The `.m' suffix was chosen for compatibility with MATLAB.
  1029.