1This is octave.info, produced by makeinfo version 6.7 from octave.texi.
2
3INFO-DIR-SECTION Math
4START-INFO-DIR-ENTRY
5* Octave: (octave).             Interactive language for numerical computations.
6END-INFO-DIR-ENTRY
7
8Copyright © 1996-2020 John W. Eaton.
9
10   Permission is granted to make and distribute verbatim copies of this
11manual provided the copyright notice and this permission notice are
12preserved on all copies.
13
14   Permission is granted to copy and distribute modified versions of
15this manual under the conditions for verbatim copying, provided that the
16entire resulting derived work is distributed under the terms of a
17permission notice identical to this one.
18
19   Permission is granted to copy and distribute translations of this
20manual into another language, under the above conditions for modified
21versions.
22
23
24File: octave.info,  Node: Cell Arrays of Strings,  Next: Processing Data in Cell Arrays,  Prev: Indexing Cell Arrays,  Up: Cell Arrays
25
266.3.4 Cell Arrays of Strings
27----------------------------
28
29One common use of cell arrays is to store multiple strings in the same
30variable.  It is also possible to store multiple strings in a character
31matrix by letting each row be a string.  This, however, introduces the
32problem that all strings must be of equal length.  Therefore, it is
33recommended to use cell arrays to store multiple strings.  For cases,
34where the character matrix representation is required for an operation,
35there are several functions that convert a cell array of strings to a
36character array and back.  ‘char’ and ‘strvcat’ convert cell arrays to a
37character array (*note Concatenating Strings::), while the function
38‘cellstr’ converts a character array to a cell array of strings:
39
40     a = ["hello"; "world"];
41     c = cellstr (a)
42          ⇒ c =
43              {
44                [1,1] = hello
45                [2,1] = world
46              }
47
48 -- : CSTR = cellstr (STRMAT)
49     Create a new cell array object from the elements of the string
50     array STRMAT.
51
52     Each row of STRMAT becomes an element of CSTR.  Any trailing spaces
53     in a row are deleted before conversion.
54
55     To convert back from a cellstr to a character array use ‘char’.
56
57     See also: *note cell: XREFcell, *note char: XREFchar.
58
59   One further advantage of using cell arrays to store multiple strings
60is that most functions for string manipulations included with Octave
61support this representation.  As an example, it is possible to compare
62one string with many others using the ‘strcmp’ function.  If one of the
63arguments to this function is a string and the other is a cell array of
64strings, each element of the cell array will be compared to the string
65argument:
66
67     c = {"hello", "world"};
68     strcmp ("hello", c)
69          ⇒ ans =
70             1   0
71
72The following string functions support cell arrays of strings: ‘char’,
73‘strvcat’, ‘strcat’ (*note Concatenating Strings::), ‘strcmp’,
74‘strncmp’, ‘strcmpi’, ‘strncmpi’ (*note Comparing Strings::),
75‘str2double’, ‘deblank’, ‘strtrim’, ‘strtrunc’, ‘strfind’, ‘strmatch’, ,
76‘regexp’, ‘regexpi’ (*note Manipulating Strings::) and ‘str2double’
77(*note String Conversions::).
78
79   The function ‘iscellstr’ can be used to test if an object is a cell
80array of strings.
81
82 -- : iscellstr (CELL)
83     Return true if every element of the cell array CELL is a character
84     string.
85
86     See also: *note ischar: XREFischar, *note isstring: XREFisstring.
87
88
89File: octave.info,  Node: Processing Data in Cell Arrays,  Prev: Cell Arrays of Strings,  Up: Cell Arrays
90
916.3.5 Processing Data in Cell Arrays
92------------------------------------
93
94Data that is stored in a cell array can be processed in several ways
95depending on the actual data.  The simplest way to process that data is
96to iterate through it using one or more ‘for’ loops.  The same idea can
97be implemented more easily through the use of the ‘cellfun’ function
98that calls a user-specified function on all elements of a cell array.
99*Note cellfun: XREFcellfun.
100
101   An alternative is to convert the data to a different container, such
102as a matrix or a data structure.  Depending on the data this is possible
103using the ‘cell2mat’ and ‘cell2struct’ functions.
104
105 -- : M = cell2mat (C)
106     Convert the cell array C into a matrix by concatenating all
107     elements of C into a hyperrectangle.
108
109     Elements of C must be numeric, logical, or char matrices; or cell
110     arrays; or structs; and ‘cat’ must be able to concatenate them
111     together.
112
113     See also: *note mat2cell: XREFmat2cell, *note num2cell:
114     XREFnum2cell.
115
116 -- : cell2struct (CELL, FIELDS)
117 -- : cell2struct (CELL, FIELDS, DIM)
118     Convert CELL to a structure.
119
120     The number of fields in FIELDS must match the number of elements in
121     CELL along dimension DIM, that is ‘numel (FIELDS) == size (CELL,
122     DIM)’.  If DIM is omitted, a value of 1 is assumed.
123
124          A = cell2struct ({"Peter", "Hannah", "Robert";
125                             185, 170, 168},
126                           {"Name","Height"}, 1);
127          A(1)
128129                {
130                  Name   = Peter
131                  Height = 185
132                }
133
134
135     See also: *note struct2cell: XREFstruct2cell, *note cell2mat:
136     XREFcell2mat, *note struct: XREFstruct.
137
138
139File: octave.info,  Node: Comma Separated Lists,  Prev: Cell Arrays,  Up: Data Containers
140
1416.4 Comma Separated Lists
142=========================
143
144Comma separated lists (1) are the basic argument type to all Octave
145functions - both for input and return arguments.  In the example
146
147     max (A, B)
148
149‘A, B’ is a comma separated list.  Comma separated lists can appear on
150both the right and left hand side of an assignment.  For example
151
152     x = [1 0 1 0 0 1 1; 0 0 0 0 0 0 7];
153     [I, J] = find (X, 2, "last");
154
155Here, ‘X, 2, "last"’ is a comma separated list constituting the input
156arguments of ‘find’.  ‘find’ returns a comma separated list of output
157arguments which is assigned element by element to the comma separated
158list ‘I, J’.
159
160   Another example of where comma separated lists are used is in the
161creation of a new array with ‘[]’ (*note Matrices::) or the creation of
162a cell array with ‘{}’ (*note Basic Usage of Cell Arrays::).  In the
163expressions
164
165     a = [1, 2, 3, 4];
166     c = {4, 5, 6, 7};
167
168both ‘1, 2, 3, 4’ and ‘4, 5, 6, 7’ are comma separated lists.
169
170   Comma separated lists cannot be directly manipulated by the user.
171However, both structure arrays and cell arrays can be converted into
172comma separated lists, and thus used in place of explicitly written
173comma separated lists.  This feature is useful in many ways, as will be
174shown in the following subsections.
175
176* Menu:
177
178* Comma Separated Lists Generated from Cell Arrays::
179* Comma Separated Lists Generated from Structure Arrays::
180
181   ---------- Footnotes ----------
182
183   (1) Comma-separated lists are also sometimes informally referred to
184as “cs-lists”.
185
186
187File: octave.info,  Node: Comma Separated Lists Generated from Cell Arrays,  Next: Comma Separated Lists Generated from Structure Arrays,  Up: Comma Separated Lists
188
1896.4.1 Comma Separated Lists Generated from Cell Arrays
190------------------------------------------------------
191
192As has been mentioned above (*note Indexing Cell Arrays::), elements of
193a cell array can be extracted into a comma separated list with the ‘{’
194and ‘}’ operators.  By surrounding this list with ‘[’ and ‘]’, it can be
195concatenated into an array.  For example:
196
197     a = {1, [2, 3], 4, 5, 6};
198     b = [a{1:4}]
199          ⇒ b =
200              1   2   3   4   5
201
202   Similarly, it is possible to create a new cell array containing cell
203elements selected with ‘{}’.  By surrounding the list with ‘{’ and ‘}’ a
204new cell array will be created, as the following example illustrates:
205
206     a = {1, rand(2, 2), "three"};
207     b = { a{ [1, 3] } }
208          ⇒ b =
209              {
210                [1,1] =  1
211                [1,2] = three
212              }
213
214   Furthermore, cell elements (accessed by ‘{}’) can be passed directly
215to a function.  The list of elements from the cell array will be passed
216as an argument list to a given function as if it is called with the
217elements as individual arguments.  The two calls to ‘printf’ in the
218following example are identical but the latter is simpler and can handle
219cell arrays of an arbitrary size:
220
221     c = {"GNU", "Octave", "is", "Free", "Software"};
222     printf ("%s ", c{1}, c{2}, c{3}, c{4}, c{5});
223          ⊣ GNU Octave is Free Software
224     printf ("%s ", c{:});
225          ⊣ GNU Octave is Free Software
226
227   If used on the left-hand side of an assignment, a comma separated
228list generated with ‘{}’ can be assigned to.  An example is
229
230     in{1} = [10, 20, 30];
231     in{2} = inf;
232     in{3} = "last";
233     in{4} = "first";
234     out = cell (4, 1);
235     [out{1:3}] = in{1 : 3};
236     [out{4:6}] = in{[1, 2, 4]})
237          ⇒ out =
238             {
239                [1,1] =
240
241                   10   20   30
242
243                [2,1] = Inf
244                [3,1] = last
245                [4,1] =
246
247                   10   20   30
248
249                [5,1] = Inf
250                [6,1] = first
251             }
252
253
254File: octave.info,  Node: Comma Separated Lists Generated from Structure Arrays,  Prev: Comma Separated Lists Generated from Cell Arrays,  Up: Comma Separated Lists
255
2566.4.2 Comma Separated Lists Generated from Structure Arrays
257-----------------------------------------------------------
258
259Structure arrays can equally be used to create comma separated lists.
260This is done by addressing one of the fields of a structure array.  For
261example:
262
263     x = ceil (randn (10, 1));
264     in = struct ("call1", {x, 3, "last"},
265                  "call2", {x, inf, "first"});
266     out = struct ("call1", cell (2, 1), "call2", cell (2, 1));
267     [out.call1] = find (in.call1);
268     [out.call2] = find (in.call2);
269
270
271File: octave.info,  Node: Variables,  Next: Expressions,  Prev: Data Containers,  Up: Top
272
2737 Variables
274***********
275
276Variables let you give names to values and refer to them later.  You
277have already seen variables in many of the examples.  The name of a
278variable must be a sequence of letters, digits and underscores, but it
279may not begin with a digit.  Octave does not enforce a limit on the
280length of variable names, but it is seldom useful to have variables with
281names longer than about 30 characters.  The following are all valid
282variable names
283
284     x
285     x15
286     __foo_bar_baz__
287     fucnrdthsucngtagdjb
288
289However, names like ‘__foo_bar_baz__’ that begin and end with two
290underscores are understood to be reserved for internal use by Octave.
291You should not use them in code you write, except to access Octave’s
292documented internal variables and built-in symbolic constants.
293
294   Case is significant in variable names.  The symbols ‘a’ and ‘A’ are
295distinct variables.
296
297   A variable name is a valid expression by itself.  It represents the
298variable’s current value.  Variables are given new values with
299“assignment operators” and “increment operators”.  *Note Assignment
300Expressions: Assignment Ops.
301
302   There is one automatically created variable with a special meaning.
303The ‘ans’ variable always contains the result of the last computation,
304where the output wasn’t assigned to any variable.  The code ‘a = cos
305(pi)’ will assign the value -1 to the variable ‘a’, but will not change
306the value of ‘ans’.  However, the code ‘cos (pi)’ will set the value of
307‘ans’ to -1.
308
309   Variables in Octave do not have fixed types, so it is possible to
310first store a numeric value in a variable and then to later use the same
311name to hold a string value in the same program.  Variables may not be
312used before they have been given a value.  Doing so results in an error.
313
314 -- Automatic Variable: ans
315     The most recently computed result that was not explicitly assigned
316     to a variable.
317
318     For example, after the expression
319
320          3^2 + 4^2
321
322     is evaluated, the value returned by ‘ans’ is 25.
323
324 -- : isvarname (NAME)
325     Return true if NAME is a valid variable name.
326
327     A valid variable name is composed of letters, digits, and
328     underscores ("_"), and the first character must not be a digit.
329
330     See also: *note iskeyword: XREFiskeyword, *note exist: XREFexist,
331     *note who: XREFwho.
332
333 -- : VARNAME = matlab.lang.makeValidName (STR)
334 -- : VARNAME = matlab.lang.makeValidName (..., "ReplacementStyle", RS)
335 -- : VARNAME = matlab.lang.makeValidName (..., "Prefix", PFX)
336 -- : [VARNAME, ISMODIFIED] = matlab.lang.makeValidName (...)
337
338     Create valid variable name VARNAME from STR.
339
340     The input STR must be a string or a cell array of strings.  The
341     output VARNAME will be of the same type.
342
343     A valid variable name is a sequence of letters, digits, and
344     underscores that does not begin with a digit.
345
346     The "ReplacementStyle" option specifies how invalid characters are
347     handled.  Acceptable values are
348
349     "underscore" (default)
350          Replace all invalid characters with an underscore ("_").
351
352     "delete"
353          Remove any invalid character.
354
355     "hex"
356          Replace all invalid characters with their hexadecimal
357          representation.
358
359     Whitespace characters are always removed *prior* to the application
360     of the "ReplacementStyle".  Lowercase letters following a
361     whitespace will be changed to uppercase.
362
363     The "Prefix" option specifies the string PFX to add as a prefix to
364     the input if it begins with a digit.  PFX must be a valid variable
365     name itself.  The default prefix is "x".
366
367     The optional output ISMODIFIED is a logical array indicating
368     whether the respective element in STR was a valid name or not.
369
370     See also: *note iskeyword: XREFiskeyword, *note isvarname:
371     XREFisvarname, *note matlab.lang.makeUniqueStrings:
372     XREFmatlab_lang_makeUniqueStrings.
373
374 -- : UNIQSTR = matlab.lang.makeUniqueStrings (STR)
375 -- : UNIQSTR = matlab.lang.makeUniqueStrings (STR, EX)
376 -- : UNIQSTR = matlab.lang.makeUniqueStrings (STR, EX, MAXLENGTH)
377 -- : [UNIQSTR, ISMODIFIED] = matlab.lang.makeUniqueStrings (...)
378
379     Construct a list of unique strings from a list of strings.
380
381     The input STR must be a string or a cell array of strings.  The
382     output UNIQSTR will be of the same type.
383
384     The algorithm makes two strings unique by appending an underscore
385     ("_" and a numeric count to the second string.
386
387     If EX is a string or a cell array of strings, UNIQSTR will contain
388     elements that are unique between themselves and with respect to EX.
389
390     If EX is an index array or a logical array for STR then it selects
391     the subset of STR that are made unique.  Unselected elements are
392     not modified.
393
394     The optional input MAXLENGTH specifies the maximum length of any
395     string in UNIQSTR.  If an input string cannot be made unique
396     without exceeding MAXLENGTH an error is emitted.
397
398     The optional output ISMODIFIED is a logical array indicating
399     whether each element in STR was modified to make it unique.
400
401     See also: *note unique: XREFunique, *note
402     matlab.lang.makeValidName: XREFmatlab_lang_makeValidName.
403
404 -- : namelengthmax ()
405     Return the MATLAB compatible maximum variable name length.
406
407     Octave is capable of storing strings up to 2^{31} - 1 in length.
408     However for MATLAB compatibility all variable, function, and
409     structure field names should be shorter than the length returned by
410     ‘namelengthmax’.  In particular, variables stored to a MATLAB file
411     format (‘*.mat’) will have their names truncated to this length.
412
413* Menu:
414
415* Global Variables::
416* Persistent Variables::
417* Status of Variables::
418
419
420File: octave.info,  Node: Global Variables,  Next: Persistent Variables,  Up: Variables
421
4227.1 Global Variables
423====================
424
425A “global” variable is one that may be accessed anywhere within Octave.
426This is in contrast to a local variable which can only be accessed
427outside of its current context if it is passed explicitly, such as by
428including it as a parameter when calling a function (‘fcn (LOCAL_VAR1,
429LOCAL_VAR2)’).
430
431   A variable is declared global by using a ‘global’ declaration
432statement.  The following statements are all global declarations.
433
434     global a
435     global a b
436     global c = 2
437     global d = 3 e f = 5
438
439   Note that the ‘global’ qualifier extends only to the next
440end-of-statement indicator which could be a comma (‘,’), semicolon
441(‘;’), or newline (‘'\n'’).  For example, the following code declares
442one global variable, A, and one local variable B to which the value 1 is
443assigned.
444
445     global a, b = 1
446
447   A global variable may only be initialized once in a ‘global’
448statement.  For example, after executing the following code
449
450     global gvar = 1
451     global gvar = 2
452
453the value of the global variable ‘gvar’ is 1, not 2.  Issuing a ‘clear
454gvar’ command does not change the above behavior, but ‘clear all’ does.
455
456   It is necessary declare a variable as global within a function body
457in order to access the one universal variable.  For example,
458
459     global x
460     function f ()
461       x = 1;
462     endfunction
463     f ()
464
465does _not_ set the value of the global variable ‘x’ to 1.  Instead, a
466local variable, with name ‘x’, is created and assigned the value of 1.
467In order to change the value of the global variable ‘x’, you must also
468declare it to be global within the function body, like this
469
470     function f ()
471       global x;
472       x = 1;
473     endfunction
474
475   Passing a global variable in a function parameter list will make a
476local copy and _not_ modify the global value.  For example, given the
477function
478
479     function f (x)
480       x = 0
481     endfunction
482
483and the definition of ‘x’ as a global variable at the top level,
484
485     global x = 13
486
487the expression
488
489     f (x)
490
491will display the value of ‘x’ from inside the function as 0, but the
492value of ‘x’ at the top level remains unchanged, because the function
493works with a _copy_ of its argument.
494
495   Programming Note: While global variables occasionally are the right
496solution to a coding problem, modern best practice discourages their
497use.  Code which relies on global variables may behave unpredictably
498between different users and can be difficult to debug.  This is because
499global variables can introduce systemic changes so that localizing a bug
500to a particular function, or to a particular loop within a function,
501becomes difficult.
502
503 -- : isglobal (NAME)
504     Return true if NAME is a globally visible variable.
505
506     For example:
507
508          global x
509          isglobal ("x")
510             ⇒ 1
511
512     See also: *note isvarname: XREFisvarname, *note exist: XREFexist.
513
514
515File: octave.info,  Node: Persistent Variables,  Next: Status of Variables,  Prev: Global Variables,  Up: Variables
516
5177.2 Persistent Variables
518========================
519
520A variable that has been declared “persistent” within a function will
521retain its contents in memory between subsequent calls to the same
522function.  The difference between persistent variables and global
523variables is that persistent variables are local in scope to a
524particular function and are not visible elsewhere.
525
526   The following example uses a persistent variable to create a function
527that prints the number of times it has been called.
528
529     function count_calls ()
530       persistent calls = 0;
531       printf ("'count_calls' has been called %d times\n",
532               ++calls);
533     endfunction
534
535     for i = 1:3
536       count_calls ();
537     endfor
538
539     ⊣ 'count_calls' has been called 1 times
540     ⊣ 'count_calls' has been called 2 times
541     ⊣ 'count_calls' has been called 3 times
542
543   As the example shows, a variable may be declared persistent using a
544‘persistent’ declaration statement.  The following statements are all
545persistent declarations.
546
547     persistent a
548     persistent a b
549     persistent c = 2
550     persistent d = 3 e f = 5
551
552   The behavior of persistent variables is equivalent to the behavior of
553static variables in C.
554
555   One restriction for persistent variables is, that neither input nor
556output arguments of a function can be persistent:
557
558     function y = foo ()
559       persistent y = 0;  # Not allowed!
560     endfunction
561
562     foo ()
563     ⊣ error: can't make function parameter y persistent
564
565   Like global variables, a persistent variable may only be initialized
566once.  For example, after executing the following code
567
568     persistent pvar = 1
569     persistent pvar = 2
570
571the value of the persistent variable ‘pvar’ is 1, not 2.
572
573   If a persistent variable is declared but not initialized to a
574specific value, it will contain an empty matrix.  So, it is also
575possible to initialize a persistent variable by checking whether it is
576empty, as the following example illustrates.
577
578     function count_calls ()
579       persistent calls;
580       if (isempty (calls))
581         calls = 0;
582       endif
583       printf ("'count_calls' has been called %d times\n",
584               ++calls);
585     endfunction
586
587This implementation behaves in exactly the same way as the previous
588implementation of ‘count_calls’.
589
590   The value of a persistent variable is kept in memory until it is
591explicitly cleared.  Assuming that the implementation of ‘count_calls’
592is saved on disk, we get the following behavior.
593
594     for i = 1:2
595       count_calls ();
596     endfor
597     ⊣ 'count_calls' has been called 1 times
598     ⊣ 'count_calls' has been called 2 times
599
600     clear
601     for i = 1:2
602       count_calls ();
603     endfor
604     ⊣ 'count_calls' has been called 3 times
605     ⊣ 'count_calls' has been called 4 times
606
607     clear all
608     for i = 1:2
609       count_calls ();
610     endfor
611     ⊣ 'count_calls' has been called 1 times
612     ⊣ 'count_calls' has been called 2 times
613
614     clear count_calls
615     for i = 1:2
616       count_calls ();
617     endfor
618     ⊣ 'count_calls' has been called 1 times
619     ⊣ 'count_calls' has been called 2 times
620
621That is, the persistent variable is only removed from memory when the
622function containing the variable is removed.  Note that if the function
623definition is typed directly into the Octave prompt, the persistent
624variable will be cleared by a simple ‘clear’ command as the entire
625function definition will be removed from memory.  If you do not want a
626persistent variable to be removed from memory even if the function is
627cleared, you should use the ‘mlock’ function (*note Function Locking::).
628
629
630File: octave.info,  Node: Status of Variables,  Prev: Persistent Variables,  Up: Variables
631
6327.3 Status of Variables
633=======================
634
635When creating simple one-shot programs it can be very convenient to see
636which variables are available at the prompt.  The function ‘who’ and its
637siblings ‘whos’ and ‘whos_line_format’ will show different information
638about what is in memory, as the following shows.
639
640     str = "A random string";
641     who
642      ⊣ Variables in the current scope:
643644      ⊣ ans  str
645
646 -- : who
647 -- : who pattern ...
648 -- : who option pattern ...
649 -- : C = who ("pattern", ...)
650     List currently defined variables matching the given patterns.
651
652     Valid pattern syntax is the same as described for the ‘clear’
653     command.  If no patterns are supplied, all variables are listed.
654
655     By default, only variables visible in the local scope are
656     displayed.
657
658     The following are valid options, but may not be combined.
659
660     ‘global’
661          List variables in the global scope rather than the current
662          scope.
663
664     ‘-regexp’
665          The patterns are considered to be regular expressions when
666          matching the variables to display.  The same pattern syntax
667          accepted by the ‘regexp’ function is used.
668
669     ‘-file’
670          The next argument is treated as a filename.  All variables
671          found within the specified file are listed.  No patterns are
672          accepted when reading variables from a file.
673
674     If called as a function, return a cell array of defined variable
675     names matching the given patterns.
676
677     See also: *note whos: XREFwhos, *note isglobal: XREFisglobal, *note
678     isvarname: XREFisvarname, *note exist: XREFexist, *note regexp:
679     XREFregexp.
680
681 -- : whos
682 -- : whos pattern ...
683 -- : whos option pattern ...
684 -- : S = whos ("pattern", ...)
685     Provide detailed information on currently defined variables
686     matching the given patterns.
687
688     Options and pattern syntax are the same as for the ‘who’ command.
689
690     Extended information about each variable is summarized in a table
691     with the following default entries.
692
693     Attr
694          Attributes of the listed variable.  Possible attributes are:
695
696          blank
697               Variable in local scope
698
699          ‘c’
700               Variable of complex type.
701
702          ‘f’
703               Formal parameter (function argument).
704
705          ‘g’
706               Variable with global scope.
707
708          ‘p’
709               Persistent variable.
710
711     Name
712          The name of the variable.
713
714     Size
715          The logical size of the variable.  A scalar is 1x1, a vector
716          is 1xN or Nx1, a 2-D matrix is MxN.
717
718     Bytes
719          The amount of memory currently used to store the variable.
720
721     Class
722          The class of the variable.  Examples include double, single,
723          char, uint16, cell, and struct.
724
725     The table can be customized to display more or less information
726     through the function ‘whos_line_format’.
727
728     If ‘whos’ is called as a function, return a struct array of defined
729     variable names matching the given patterns.  Fields in the
730     structure describing each variable are: name, size, bytes, class,
731     global, sparse, complex, nesting, persistent.
732
733     See also: *note who: XREFwho, *note whos_line_format:
734     XREFwhos_line_format.
735
736 -- : VAL = whos_line_format ()
737 -- : OLD_VAL = whos_line_format (NEW_VAL)
738 -- : whos_line_format (NEW_VAL, "local")
739     Query or set the format string used by the command ‘whos’.
740
741     A full format string is:
742
743          %[modifier]<command>[:width[:left-min[:balance]]];
744
745     The following command sequences are available:
746
747     ‘%a’
748          Prints attributes of variables (g=global, p=persistent,
749          f=formal parameter).
750
751     ‘%b’
752          Prints number of bytes occupied by variables.
753
754     ‘%c’
755          Prints class names of variables.
756
757     ‘%e’
758          Prints elements held by variables.
759
760     ‘%n’
761          Prints variable names.
762
763     ‘%s’
764          Prints dimensions of variables.
765
766     ‘%t’
767          Prints type names of variables.
768
769     Every command may also have an alignment modifier:
770
771     ‘l’
772          Left alignment.
773
774     ‘r’
775          Right alignment (default).
776
777     ‘c’
778          Column-aligned (only applicable to command %s).
779
780     The ‘width’ parameter is a positive integer specifying the minimum
781     number of columns used for printing.  No maximum is needed as the
782     field will auto-expand as required.
783
784     The parameters ‘left-min’ and ‘balance’ are only available when the
785     column-aligned modifier is used with the command ‘%s’.  ‘balance’
786     specifies the column number within the field width which will be
787     aligned between entries.  Numbering starts from 0 which indicates
788     the leftmost column.  ‘left-min’ specifies the minimum field width
789     to the left of the specified balance column.
790
791     The default format is:
792
793     " %a:4; %ln:6; %cs:16:6:1; %rb:12; %lc:-1;\n"
794
795     When called from inside a function with the "local" option, the
796     variable is changed locally for the function and any subroutines it
797     calls.  The original variable value is restored when exiting the
798     function.
799
800     See also: *note whos: XREFwhos.
801
802   Instead of displaying which variables are in memory, it is possible
803to determine if a given variable is available.  That way it is possible
804to alter the behavior of a program depending on the existence of a
805variable.  The following example illustrates this.
806
807     if (! exist ("meaning", "var"))
808       disp ("The program has no 'meaning'");
809     endif
810
811 -- : C = exist (NAME)
812 -- : C = exist (NAME, TYPE)
813     Check for the existence of NAME as a variable, function, file,
814     directory, or class.
815
816     The return code C is one of
817
818     1
819          NAME is a variable.
820
821     2
822          NAME is an absolute filename, an ordinary file in Octave’s
823          ‘path’, or (after appending ‘.m’) a function file in Octave’s
824          ‘path’.
825
826     3
827          NAME is a ‘.oct’ or ‘.mex’ file in Octave’s ‘path’.
828
829     5
830          NAME is a built-in function.
831
832     7
833          NAME is a directory.
834
835     8
836          NAME is a class.  (Note: not currently implemented)
837
838     103
839          NAME is a function not associated with a file (entered on the
840          command line).
841
842     0
843          NAME does not exist.
844
845     If the optional argument TYPE is supplied, check only for symbols
846     of the specified type.  Valid types are
847
848     "var"
849          Check only for variables.
850
851     "builtin"
852          Check only for built-in functions.
853
854     "dir"
855          Check only for directories.
856
857     "file"
858          Check only for files and directories.
859
860     "class"
861          Check only for classes.  (Note: This option is accepted, but
862          not currently implemented)
863
864     If no type is given, and there are multiple possible matches for
865     name, ‘exist’ will return a code according to the following
866     priority list: variable, built-in function, oct-file, directory,
867     file, class.
868
869     ‘exist’ returns 2 if a regular file called NAME is present in
870     Octave’s search path.  For information about other types of files
871     not on the search path use some combination of the functions
872     ‘file_in_path’ and ‘stat’ instead.
873
874     Programming Note: If NAME is implemented by a buggy .oct/.mex file,
875     calling EXIST may cause Octave to crash.  To maintain high
876     performance, Octave trusts .oct/.mex files instead of sandboxing
877     them.
878
879     See also: *note file_in_loadpath: XREFfile_in_loadpath, *note
880     file_in_path: XREFfile_in_path, *note dir_in_loadpath:
881     XREFdir_in_loadpath, *note stat: XREFstat.
882
883   Usually Octave will manage the memory, but sometimes it can be
884practical to remove variables from memory manually.  This is usually
885needed when working with large variables that fill a substantial part of
886the memory.  On a computer that uses the IEEE floating point format, the
887following program allocates a matrix that requires around 128 MB memory.
888
889     large_matrix = zeros (4000, 4000);
890
891Since having this variable in memory might slow down other computations,
892it can be necessary to remove it manually from memory.  The ‘clear’ or
893‘clearvars’ functions do this.
894
895 -- : clear
896 -- : clear PATTERN ...
897 -- : clear OPTIONS PATTERN ...
898     Delete the names matching the given PATTERNs thereby freeing
899     memory.
900
901     The PATTERN may contain the following special characters:
902
903     ‘?’
904          Match any single character.
905
906     ‘*’
907          Match zero or more characters.
908
909     ‘[ LIST ]’
910          Match the list of characters specified by LIST.  If the first
911          character is ‘!’ or ‘^’, match all characters except those
912          specified by LIST.  For example, the pattern ‘[a-zA-Z]’ will
913          match all lowercase and uppercase alphabetic characters.
914
915     For example, the command
916
917          clear foo b*r
918
919     clears the name ‘foo’ and all names that begin with the letter ‘b’
920     and end with the letter ‘r’.
921
922     If ‘clear’ is called without any arguments, all user-defined
923     variables are cleared from the current workspace (i.e., local
924     variables).  Any global variables present will no longer be visible
925     in the current workspace, but they will continue to exist in the
926     global workspace.  Functions are unaffected by this form of
927     ‘clear’.
928
929     The following options are available in both long and short form
930
931     ‘all, -all, -a’
932          Clear all local and global user-defined variables, and all
933          functions from the symbol table.
934
935     ‘-exclusive, -x’
936          Clear variables that do *not* match the following pattern.
937
938     ‘functions, -functions, -f’
939          Clear function names from the function symbol table.
940          Persistent variables will be re-initialized to their default
941          value unless the function has been locked in memory with
942          ‘mlock’.
943
944     ‘global, -global, -g’
945          Clear global variable names.
946
947     ‘variables, -variables, -v’
948          Clear local variable names.
949
950     ‘classes, -classes, -c’
951          Clear the class structure table and all objects.
952
953     ‘-regexp, -r’
954          The PATTERN arguments are treated as regular expressions and
955          any matches will be cleared.
956
957     With the exception of ‘-exclusive’ and ‘-regexp’, all long options
958     can be used without the dash as well.  Note that, aside from
959     ‘-exclusive’, only one other option may appear.  All options must
960     appear before any patterns.
961
962     Programming Notes: The command ‘clear NAME’ only clears the
963     variable NAME when both a variable and a (shadowed) function named
964     NAME are currently defined.  For example, suppose you have defined
965     a function ‘foo’, and then hidden it by performing the assignment
966     ‘foo = 2’.  Executing the command ‘clear foo’ once will clear the
967     variable definition and restore the definition of ‘foo’ as a
968     function.  Executing ‘clear foo’ a second time will clear the
969     function definition.
970
971     When a local variable name, which is linked to a global variable,
972     is cleared only the local copy of the variable is removed.  The
973     global copy is untouched and can be restored with ‘global
974     GLOBAL_VARNAME’.  Conversely, ‘clear -g GLOBAL_VARNAME’ will remove
975     both the local and global variables.
976
977     See also: *note clearvars: XREFclearvars, *note who: XREFwho, *note
978     whos: XREFwhos, *note exist: XREFexist, *note mlock: XREFmlock.
979
980 -- : clearvars
981 -- : clearvars PATTERN ...
982 -- : clearvars -regexp PATTERN ...
983 -- : clearvars ... -except PATTERN ...
984 -- : clearvars ... -except -regexp PATTERN ...
985 -- : clearvars -global ...
986     Delete the variables matching the given PATTERNs from memory.
987
988     The PATTERN may contain the following special characters:
989
990     ‘?’
991          Match any single character.
992
993     ‘*’
994          Match zero or more characters.
995
996     ‘[ LIST ]’
997          Match the list of characters specified by LIST.  If the first
998          character is ‘!’ or ‘^’, match all characters except those
999          specified by LIST.  For example, the pattern ‘[a-zA-Z]’ will
1000          match all lowercase and uppercase alphabetic characters.
1001
1002     If the ‘-regexp’ option is given then subsequent patterns are
1003     treated as regular expressions and any matches will be cleared.
1004
1005     If the ‘-except’ option is given then subsequent patterns select
1006     variables that will *not* be cleared.
1007
1008     If the ‘-global’ option is given then all patterns will be applied
1009     to global variables rather than local variables.
1010
1011     When called with no arguments, ‘clearvars’ deletes all local
1012     variables.
1013
1014     Example Code:
1015
1016     Clear all variables starting with ’x’ and the specific variable
1017     "foobar"
1018
1019          clearvars x* foobar
1020
1021     Clear the specific variable "foobar" and use regular expressions to
1022     clear all variables starting with ’x’ or ’y’.
1023
1024          clearvars foobar -regexp ^x ^y
1025
1026     Clear all variables except for "foobar"
1027
1028          clearvars -except foobar
1029
1030     Clear all variables beginning with "foo", except for those ending
1031     in "bar"
1032
1033          clearvars foo* -except -regexp bar$
1034
1035     See also: *note clear: XREFclear, *note who: XREFwho, *note whos:
1036     XREFwhos, *note exist: XREFexist.
1037
1038 -- : pack ()
1039     Consolidate workspace memory in MATLAB.
1040
1041     This function is provided for compatibility, but does nothing in
1042     Octave.
1043
1044     See also: *note clear: XREFclear.
1045
1046   Information about a function or variable such as its location in the
1047file system can also be acquired from within Octave.  This is usually
1048only useful during development of programs, and not within a program.
1049
1050 -- : type NAME ...
1051 -- : type -q NAME ...
1052 -- : text = type ("NAME", ...)
1053     Display the contents of NAME which may be a file, function
1054     (m-file), variable, operator, or keyword.
1055
1056     ‘type’ normally prepends a header line describing the category of
1057     NAME such as function or variable; The ‘-q’ option suppresses this
1058     behavior.
1059
1060     If no output variable is used the contents are displayed on screen.
1061     Otherwise, a cell array of strings is returned, where each element
1062     corresponds to the contents of each requested function.
1063
1064 -- : which name ...
1065     Display the type of each NAME.
1066
1067     If NAME is defined from a function file, the full name of the file
1068     is also displayed.
1069
1070     See also: *note help: XREFhelp, *note lookfor: XREFlookfor.
1071
1072 -- : what
1073 -- : what DIR
1074 -- : w = what (DIR)
1075     List the Octave specific files in directory DIR.
1076
1077     If DIR is not specified then the current directory is used.
1078
1079     If a return argument is requested, the files found are returned in
1080     the structure W.  The structure contains the following fields:
1081
1082     path
1083          Full path to directory DIR
1084
1085     m
1086          Cell array of m-files
1087
1088     mat
1089          Cell array of mat files
1090
1091     mex
1092          Cell array of mex files
1093
1094     oct
1095          Cell array of oct files
1096
1097     mdl
1098          Cell array of mdl files
1099
1100     slx
1101          Cell array of slx files
1102
1103     p
1104          Cell array of p-files
1105
1106     classes
1107          Cell array of class directories (‘@CLASSNAME/’)
1108
1109     packages
1110          Cell array of package directories (‘+PKGNAME/’)
1111
1112     Compatibility Note: Octave does not support mdl, slx, and p files.
1113     ‘what’ will always return an empty list for these categories.
1114
1115     See also: *note which: XREFwhich, *note ls: XREFls, *note exist:
1116     XREFexist.
1117
1118
1119File: octave.info,  Node: Expressions,  Next: Evaluation,  Prev: Variables,  Up: Top
1120
11218 Expressions
1122*************
1123
1124Expressions are the basic building block of statements in Octave.  An
1125expression evaluates to a value, which you can print, test, store in a
1126variable, pass to a function, or assign a new value to a variable with
1127an assignment operator.
1128
1129   An expression can serve as a statement on its own.  Most other kinds
1130of statements contain one or more expressions which specify data to be
1131operated on.  As in other languages, expressions in Octave include
1132variables, array references, constants, and function calls, as well as
1133combinations of these with various operators.
1134
1135* Menu:
1136
1137* Index Expressions::
1138* Calling Functions::
1139* Arithmetic Ops::
1140* Comparison Ops::
1141* Boolean Expressions::
1142* Assignment Ops::
1143* Increment Ops::
1144* Operator Precedence::
1145
1146
1147File: octave.info,  Node: Index Expressions,  Next: Calling Functions,  Up: Expressions
1148
11498.1 Index Expressions
1150=====================
1151
1152An “index expression” allows you to reference or extract selected
1153elements of a vector, a matrix (2-D), or a higher-dimensional array.
1154
1155   Indices may be scalars, vectors, ranges, or the special operator ‘:’,
1156which selects entire rows, columns, or higher-dimensional slices.
1157
1158   An index expression consists of a set of parentheses enclosing M
1159expressions separated by commas.  Each individual index value, or
1160component, is used for the respective dimension of the object that it is
1161applied to.  In other words, the first index component is used for the
1162first dimension (rows) of the object, the second index component is used
1163for the second dimension (columns) of the object, and so on.  The number
1164of index components M defines the dimensionality of the index
1165expression.  An index with two components would be referred to as a 2-D
1166index because it has two dimensions.
1167
1168   In the simplest case, 1) all components are scalars, and 2) the
1169dimensionality of the index expression M is equal to the dimensionality
1170of the object it is applied to.  For example:
1171
1172     A = reshape (1:8, 2, 2, 2)  # Create 3-D array
1173     A =
1174
1175     ans(:,:,1) =
1176
1177        1   3
1178        2   4
1179
1180     ans(:,:,2) =
1181
1182        5   7
1183        6   8
1184
1185     A(2, 1, 2)   # second row, first column of second slice
1186                  # in third dimension: ans = 6
1187
1188   The size of the returned object in a specific dimension is equal to
1189the number of elements in the corresponding component of the index
1190expression.  When all components are scalars, the result is a single
1191output value.  However, if any component is a vector or range then the
1192returned values are the Cartesian product of the indices in the
1193respective dimensions.  For example:
1194
1195     A([1, 2], 1, 2) ≡ [A(1,1,2); A(2,1,2)]
11961197     ans =
1198        5
1199        6
1200
1201   The total number of returned values is the product of the number of
1202elements returned for each index component.  In the example above, the
1203total is 2*1*1 = 2 elements.
1204
1205   Notice that the size of the returned object in a given dimension is
1206equal to the number of elements in the index expression for that
1207dimension.  In the code above, the first index component (‘[1, 2]’) was
1208specified as a row vector, but its shape is unimportant.  The important
1209fact is that the component specified two values, and hence the result
1210must have a size of two in the first dimension; and because the first
1211dimension corresponds to rows, the overall result is a column vector.
1212
1213     A(1, [2, 1, 1], 1)    # result is a row vector: ans = [3, 1, 1]
1214     A(ones (2, 2), 1, 1)  # result is a column vector: ans = [1; 1; 1; 1]
1215
1216   The first line demonstrates again that the size of the output in a
1217given dimension is equal to the number of elements in the respective
1218indexing component.  In this case, the output has three elements in the
1219second dimension (which corresponds to columns), so the result is a row
1220vector.  The example also shows how repeating entries in the index
1221expression can be used to replicate elements in the output.  The last
1222example further proves that the shape of the indexing component is
1223irrelevant, it is only the number of elements (2x2 = 4) which is
1224important.
1225
1226   The above rules apply whenever the dimensionality of the index
1227expression is greater than one (M > 1).  However, for one-dimensional
1228index expressions special rules apply and the shape of the output *is*
1229determined by the shape of the indexing component.  For example:
1230
1231     A([1, 2])  # result is a row vector: ans = [1, 2]
1232     A([1; 2])  # result is a column vector: ans = [1; 2]
1233
1234   Note that it is permissible to use a 1-D index with a
1235multi-dimensional object (also called linear indexing).  In this case,
1236the elements of the multi-dimensional array are taken in column-first
1237order like Fortran.  That is, the columns of the array are imagined to
1238be stacked on top of each other to form a column vector and then the
1239single linear index is applied to this vector.
1240
1241     A(5)    # linear indexing into three-dimensional array: ans = 5
1242     A(3:5)  # result has shape of index component: ans = [3, 4, 5]
1243
1244   A colon (‘:’) may be used as an index component to select all of the
1245elements in a specified dimension.  Given the matrix,
1246
1247     A = [1, 2; 3, 4]
1248
1249all of the following expressions are equivalent and select the first row
1250of the matrix.
1251
1252     A(1, [1, 2])  # row 1, columns 1 and 2
1253     A(1, 1:2)     # row 1, columns in range 1-2
1254     A(1, :)       # row 1, all columns
1255
1256   When a colon is used in the special case of 1-D indexing the result
1257is always a column vector.  Creating column vectors with a colon index
1258is a very frequently encountered code idiom and is faster and generally
1259clearer than calling ‘reshape’ for this case.
1260
1261     A(:)    # result is column vector: ans = [1; 2; 3; 4]
1262     A(:)'   # result is row vector: ans = [1, 2, 3, 4]
1263
1264   In index expressions the keyword ‘end’ automatically refers to the
1265last entry for a particular dimension.  This magic index can also be
1266used in ranges and typically eliminates the needs to call ‘size’ or
1267‘length’ to gather array bounds before indexing.  For example:
1268
1269     A(1:end/2)        # first half of A => [1, 2]
1270     A(end + 1) = 5;   # append element
1271     A(end) = [];      # delete element
1272     A(1:2:end)        # odd elements of A => [1, 3]
1273     A(2:2:end)        # even elements of A => [2, 4]
1274     A(end:-1:1)       # reversal of A => [4, 3, 2, 1]
1275
1276* Menu:
1277
1278* Advanced Indexing::
1279
1280
1281File: octave.info,  Node: Advanced Indexing,  Up: Index Expressions
1282
12838.1.1 Advanced Indexing
1284-----------------------
1285
1286When it is necessary to extract subsets of entries out of an array whose
1287indices cannot be written as a Cartesian product of components, linear
1288indexing together with the function ‘sub2ind’ can be used.  For example:
1289
1290     A = reshape (1:8, 2, 2, 2)  # Create 3-D array
1291     A =
1292
1293     ans(:,:,1) =
1294
1295        1   3
1296        2   4
1297
1298     ans(:,:,2) =
1299
1300        5   7
1301        6   8
1302
1303     A(sub2ind (size (A), [1, 2, 1], [1, 1, 2], [1, 2, 1]))
1304        ⇒ ans = [A(1, 1, 1), A(2, 1, 2), A(1, 2, 1)]
1305
1306   An array with ‘nd’ dimensions can be indexed by an index expression
1307which has from 1 to ‘nd’ components.  For the ordinary and most common
1308case, the number of components ‘M’ matches the number of dimensions
1309‘nd’.  In this case the ordinary indexing rules apply and each component
1310corresponds to the respective dimension of the array.
1311
1312   However, if the number of indexing components exceeds the number of
1313dimensions (‘M > nd’) then the excess components must all be singletons
1314(‘1’).  Moreover, if ‘M < nd’, the behavior is equivalent to reshaping
1315the input object so as to merge the trailing ‘nd - M’ dimensions into
1316the last index dimension ‘M’.  Thus, the result will have the
1317dimensionality of the index expression, and not the original object.
1318This is the case whenever dimensionality of the index is greater than
1319one (‘M > 1’), so that the special rules for linear indexing are not
1320applied.  This is easiest to understand with an example:
1321
1322     A = reshape (1:8, 2, 2, 2)  # Create 3-D array
1323     A =
1324
1325     ans(:,:,1) =
1326
1327        1   3
1328        2   4
1329
1330     ans(:,:,2) =
1331
1332        5   7
1333        6   8
1334
1335     ## 2-D indexing causes third dimension to be merged into second dimension.
1336     ## Equivalent array for indexing, Atmp, is now 2x4.
1337     Atmp = reshape (A, 2, 4)
1338     Atmp =
1339
1340        1   3   5   7
1341        2   4   6   8
1342
1343
1344     A(2,1)   # Reshape to 2x4 matrix, second entry of first column: ans = 2
1345     A(2,4)   # Reshape to 2x4 matrix, second entry of fourth column: ans = 8
1346     A(:,:)   # Reshape to 2x4 matrix, select all rows & columns, ans = Atmp
1347
1348Note here the elegant use of the double colon to replace the call to the
1349‘reshape’ function.
1350
1351   Another advanced use of linear indexing is to create arrays filled
1352with a single value.  This can be done by using an index of ones on a
1353scalar value.  The result is an object with the dimensions of the index
1354expression and every element equal to the original scalar.  For example,
1355the following statements
1356
1357     a = 13;
1358     a(ones (1, 4))
1359
1360produce a row vector whose four elements are all equal to 13.
1361
1362   Similarly, by indexing a scalar with two vectors of ones it is
1363possible to create a matrix.  The following statements
1364
1365     a = 13;
1366     a(ones (1, 2), ones (1, 3))
1367
1368create a 2x3 matrix with all elements equal to 13.  This could also have
1369been written as
1370
1371     13(ones (2, 3))
1372
1373   It is more efficient to use indexing rather than the code
1374construction ‘scalar * ones (M, N, ...)’ because it avoids the
1375unnecessary multiplication operation.  Moreover, multiplication may not
1376be defined for the object to be replicated whereas indexing an array is
1377always defined.  The following code shows how to create a 2x3 cell array
1378from a base unit which is not itself a scalar.
1379
1380     {"Hello"}(ones (2, 3))
1381
1382   It should be noted that ‘ones (1, n)’ (a row vector of ones) results
1383in a range object (with zero increment).  A range is stored internally
1384as a starting value, increment, end value, and total number of values;
1385hence, it is more efficient for storage than a vector or matrix of ones
1386whenever the number of elements is greater than 4.  In particular, when
1387‘r’ is a row vector, the expressions
1388
1389       r(ones (1, n), :)
1390
1391       r(ones (n, 1), :)
1392
1393will produce identical results, but the first one will be significantly
1394faster, at least for ‘r’ and ‘n’ large enough.  In the first case the
1395index is held in compressed form as a range which allows Octave to
1396choose a more efficient algorithm to handle the expression.
1397
1398   A general recommendation for users unfamiliar with these techniques
1399is to use the function ‘repmat’ for replicating smaller arrays into
1400bigger ones, which uses such tricks.
1401
1402   A second use of indexing is to speed up code.  Indexing is a fast
1403operation and judicious use of it can reduce the requirement for looping
1404over individual array elements, which is a slow operation.
1405
1406   Consider the following example which creates a 10-element row vector
1407a containing the values a(i) = sqrt (i).
1408
1409     for i = 1:10
1410       a(i) = sqrt (i);
1411     endfor
1412
1413It is quite inefficient to create a vector using a loop like this.  In
1414this case, it would have been much more efficient to use the expression
1415
1416     a = sqrt (1:10);
1417
1418which avoids the loop entirely.
1419
1420   In cases where a loop cannot be avoided, or a number of values must
1421be combined to form a larger matrix, it is generally faster to set the
1422size of the matrix first (pre-allocate storage), and then insert
1423elements using indexing commands.  For example, given a matrix ‘a’,
1424
1425     [nr, nc] = size (a);
1426     x = zeros (nr, n * nc);
1427     for i = 1:n
1428       x(:,(i-1)*nc+1:i*nc) = a;
1429     endfor
1430
1431is considerably faster than
1432
1433     x = a;
1434     for i = 1:n-1
1435       x = [x, a];
1436     endfor
1437
1438because Octave does not have to repeatedly resize the intermediate
1439result.
1440
1441 -- : IND = sub2ind (DIMS, I, J)
1442 -- : IND = sub2ind (DIMS, S1, S2, ..., SN)
1443     Convert subscripts to linear indices.
1444
1445     The input DIMS is a dimension vector where each element is the size
1446     of the array in the respective dimension (*note size: XREFsize.).
1447     The remaining inputs are scalars or vectors of subscripts to be
1448     converted.
1449
1450     The output vector IND contains the converted linear indices.
1451
1452     Background: Array elements can be specified either by a linear
1453     index which starts at 1 and runs through the number of elements in
1454     the array, or they may be specified with subscripts for the row,
1455     column, page, etc.  The functions ‘ind2sub’ and ‘sub2ind’
1456     interconvert between the two forms.
1457
1458     The linear index traverses dimension 1 (rows), then dimension 2
1459     (columns), then dimension 3 (pages), etc. until it has numbered all
1460     of the elements.  Consider the following 3-by-3 matrices:
1461
1462          [(1,1), (1,2), (1,3)]     [1, 4, 7]
1463          [(2,1), (2,2), (2,3)] ==> [2, 5, 8]
1464          [(3,1), (3,2), (3,3)]     [3, 6, 9]
1465
1466     The left matrix contains the subscript tuples for each matrix
1467     element.  The right matrix shows the linear indices for the same
1468     matrix.
1469
1470     The following example shows how to convert the two-dimensional
1471     indices ‘(2,1)’ and ‘(2,3)’ of a 3-by-3 matrix to linear indices
1472     with a single call to ‘sub2ind’.
1473
1474          s1 = [2, 2];
1475          s2 = [1, 3];
1476          ind = sub2ind ([3, 3], s1, s2)
1477              ⇒ ind =  2   8
1478
1479     See also: *note ind2sub: XREFind2sub, *note size: XREFsize.
1480
1481 -- : [S1, S2, ..., SN] = ind2sub (DIMS, IND)
1482     Convert linear indices to subscripts.
1483
1484     The input DIMS is a dimension vector where each element is the size
1485     of the array in the respective dimension (*note size: XREFsize.).
1486     The second input IND contains linear indies to be converted.
1487
1488     The outputs S1, ..., SN contain the converted subscripts.
1489
1490     Background: Array elements can be specified either by a linear
1491     index which starts at 1 and runs through the number of elements in
1492     the array, or they may be specified with subscripts for the row,
1493     column, page, etc.  The functions ‘ind2sub’ and ‘sub2ind’
1494     interconvert between the two forms.
1495
1496     The linear index traverses dimension 1 (rows), then dimension 2
1497     (columns), then dimension 3 (pages), etc. until it has numbered all
1498     of the elements.  Consider the following 3-by-3 matrices:
1499
1500          [1, 4, 7]     [(1,1), (1,2), (1,3)]
1501          [2, 5, 8] ==> [(2,1), (2,2), (2,3)]
1502          [3, 6, 9]     [(3,1), (3,2), (3,3)]
1503
1504     The left matrix contains the linear indices for each matrix
1505     element.  The right matrix shows the subscript tuples for the same
1506     matrix.
1507
1508     The following example shows how to convert the two-dimensional
1509     indices ‘(2,1)’ and ‘(2,3)’ of a 3-by-3 matrix to linear indices
1510     with a single call to ‘sub2ind’.
1511
1512     The following example shows how to convert the linear indices ‘2’
1513     and ‘8’ in a 3-by-3 matrix into subscripts.
1514
1515          ind = [2, 8];
1516          [r, c] = ind2sub ([3, 3], ind)
1517              ⇒ r =  2   2
1518              ⇒ c =  1   3
1519
1520     If the number of output subscripts exceeds the number of
1521     dimensions, the exceeded dimensions are set to ‘1’.  On the other
1522     hand, if fewer subscripts than dimensions are provided, the
1523     exceeding dimensions are merged into the final requested dimension.
1524     For clarity, consider the following examples:
1525
1526          ind  = [2, 8];
1527          dims = [3, 3];
1528          ## same as dims = [3, 3, 1]
1529          [r, c, s] = ind2sub (dims, ind)
1530              ⇒ r =  2   2
1531              ⇒ c =  1   3
1532              ⇒ s =  1   1
1533          ## same as dims = [9]
1534          r = ind2sub (dims, ind)
1535              ⇒ r =  2   8
1536
1537     See also: *note sub2ind: XREFsub2ind, *note size: XREFsize.
1538
1539 -- : isindex (IND)
1540 -- : isindex (IND, N)
1541     Return true if IND is a valid index.
1542
1543     Valid indices are either positive integers (although possibly of
1544     real data type), or logical arrays.
1545
1546     If present, N specifies the maximum extent of the dimension to be
1547     indexed.  When possible the internal result is cached so that
1548     subsequent indexing using IND will not perform the check again.
1549
1550     Implementation Note: Strings are first converted to double values
1551     before the checks for valid indices are made.  Unless a string
1552     contains the NULL character "\0", it will always be a valid index.
1553
1554
1555File: octave.info,  Node: Calling Functions,  Next: Arithmetic Ops,  Prev: Index Expressions,  Up: Expressions
1556
15578.2 Calling Functions
1558=====================
1559
1560A “function” is a name for a particular calculation.  Because it has a
1561name, you can ask for it by name at any point in the program.  For
1562example, the function ‘sqrt’ computes the square root of a number.
1563
1564   A fixed set of functions are “built-in”, which means they are
1565available in every Octave program.  The ‘sqrt’ function is one of these.
1566In addition, you can define your own functions.  *Note Functions and
1567Scripts::, for information about how to do this.
1568
1569   The way to use a function is with a “function call” expression, which
1570consists of the function name followed by a list of “arguments” in
1571parentheses.  The arguments are expressions which give the raw materials
1572for the calculation that the function will do.  When there is more than
1573one argument, they are separated by commas.  If there are no arguments,
1574you can omit the parentheses, but it is a good idea to include them
1575anyway, to clearly indicate that a function call was intended.  Here are
1576some examples:
1577
1578     sqrt (x^2 + y^2)      # One argument
1579     ones (n, m)           # Two arguments
1580     rand ()               # No arguments
1581
1582   Each function expects a particular number of arguments.  For example,
1583the ‘sqrt’ function must be called with a single argument, the number to
1584take the square root of:
1585
1586     sqrt (ARGUMENT)
1587
1588   Some of the built-in functions take a variable number of arguments,
1589depending on the particular usage, and their behavior is different
1590depending on the number of arguments supplied.
1591
1592   Like every other expression, the function call has a value, which is
1593computed by the function based on the arguments you give it.  In this
1594example, the value of ‘sqrt (ARGUMENT)’ is the square root of the
1595argument.  A function can also have side effects, such as assigning the
1596values of certain variables or doing input or output operations.
1597
1598   Unlike most languages, functions in Octave may return multiple
1599values.  For example, the following statement
1600
1601     [u, s, v] = svd (a)
1602
1603computes the singular value decomposition of the matrix ‘a’ and assigns
1604the three result matrices to ‘u’, ‘s’, and ‘v’.
1605
1606   The left side of a multiple assignment expression is itself a list of
1607expressions, that is, a list of variable names potentially qualified by
1608index expressions.  See also *note Index Expressions::, and *note
1609Assignment Ops::.
1610
1611* Menu:
1612
1613* Call by Value::
1614* Recursion::
1615* Access via Handle::
1616
1617
1618File: octave.info,  Node: Call by Value,  Next: Recursion,  Up: Calling Functions
1619
16208.2.1 Call by Value
1621-------------------
1622
1623In Octave, unlike Fortran, function arguments are passed by value, which
1624means that each argument in a function call is evaluated and assigned to
1625a temporary location in memory before being passed to the function.
1626There is currently no way to specify that a function parameter should be
1627passed by reference instead of by value.  This means that it is
1628impossible to directly alter the value of a function parameter in the
1629calling function.  It can only change the local copy within the function
1630body.  For example, the function
1631
1632     function f (x, n)
1633       while (n-- > 0)
1634         disp (x);
1635       endwhile
1636     endfunction
1637
1638displays the value of the first argument N times.  In this function, the
1639variable N is used as a temporary variable without having to worry that
1640its value might also change in the calling function.  Call by value is
1641also useful because it is always possible to pass constants for any
1642function parameter without first having to determine that the function
1643will not attempt to modify the parameter.
1644
1645   The caller may use a variable as the expression for the argument, but
1646the called function does not know this: it only knows what value the
1647argument had.  For example, given a function called as
1648
1649     foo = "bar";
1650     fcn (foo)
1651
1652you should not think of the argument as being “the variable ‘foo’.”
1653Instead, think of the argument as the string value, "bar".
1654
1655   Even though Octave uses pass-by-value semantics for function
1656arguments, values are not copied unnecessarily.  For example,
1657
1658     x = rand (1000);
1659     f (x);
1660
1661does not actually force two 1000 by 1000 element matrices to exist
1662_unless_ the function ‘f’ modifies the value of its argument.  Then
1663Octave must create a copy to avoid changing the value outside the scope
1664of the function ‘f’, or attempting (and probably failing!)  to modify
1665the value of a constant or the value of a temporary result.
1666
1667
1668File: octave.info,  Node: Recursion,  Next: Access via Handle,  Prev: Call by Value,  Up: Calling Functions
1669
16708.2.2 Recursion
1671---------------
1672
1673With some restrictions(1), recursive function calls are allowed.  A
1674“recursive function” is one which calls itself, either directly or
1675indirectly.  For example, here is an inefficient(2) way to compute the
1676factorial of a given integer:
1677
1678     function retval = fact (n)
1679       if (n > 0)
1680         retval = n * fact (n-1);
1681       else
1682         retval = 1;
1683       endif
1684     endfunction
1685
1686This function is recursive because it calls itself directly.  It
1687eventually terminates because each time it calls itself, it uses an
1688argument that is one less than was used for the previous call.  Once the
1689argument is no longer greater than zero, it does not call itself, and
1690the recursion ends.
1691
1692   The function ‘max_recursion_depth’ may be used to specify a limit to
1693the recursion depth and prevents Octave from recursing infinitely.
1694Similarly, the function ‘max_stack_depth’ may be used to specify limit
1695to the depth of function calls, whether recursive or not.  These limits
1696help prevent stack overflow on the computer Octave is running on, so
1697that instead of exiting with a signal, the interpreter will throw an
1698error and return to the command prompt.
1699
1700 -- : VAL = max_recursion_depth ()
1701 -- : OLD_VAL = max_recursion_depth (NEW_VAL)
1702 -- : max_recursion_depth (NEW_VAL, "local")
1703     Query or set the internal limit on the number of times a function
1704     may be called recursively.
1705
1706     If the limit is exceeded, an error message is printed and control
1707     returns to the top level.
1708
1709     When called from inside a function with the "local" option, the
1710     variable is changed locally for the function and any subroutines it
1711     calls.  The original variable value is restored when exiting the
1712     function.
1713
1714     See also: *note max_stack_depth: XREFmax_stack_depth.
1715
1716 -- : VAL = max_stack_depth ()
1717 -- : OLD_VAL = max_stack_depth (NEW_VAL)
1718 -- : max_stack_depth (NEW_VAL, "local")
1719     Query or set the internal limit on the number of times a function
1720     may be called recursively.
1721
1722     If the limit is exceeded, an error message is printed and control
1723     returns to the top level.
1724
1725     When called from inside a function with the "local" option, the
1726     variable is changed locally for the function and any subroutines it
1727     calls.  The original variable value is restored when exiting the
1728     function.
1729
1730     See also: *note max_recursion_depth: XREFmax_recursion_depth.
1731
1732   ---------- Footnotes ----------
1733
1734   (1) Some of Octave’s functions are implemented in terms of functions
1735that cannot be called recursively.  For example, the ODE solver ‘lsode’
1736is ultimately implemented in a Fortran subroutine that cannot be called
1737recursively, so ‘lsode’ should not be called either directly or
1738indirectly from within the user-supplied function that ‘lsode’ requires.
1739Doing so will result in an error.
1740
1741   (2) It would be much better to use ‘prod (1:n)’, or ‘gamma (n+1)’
1742instead, after first checking to ensure that the value ‘n’ is actually a
1743positive integer.
1744
1745
1746File: octave.info,  Node: Access via Handle,  Prev: Recursion,  Up: Calling Functions
1747
17488.2.3 Access via Handle
1749-----------------------
1750
1751A function may be abstracted and referenced via a function handle
1752acquired using the special operator ‘@’.  For example,
1753
1754     f = @plus;
1755     f (2, 2)
1756     ⇒  4
1757
1758is equivalent to calling ‘plus (2, 2)’ directly.  Beyond abstraction for
1759general programming, function handles find use in callback methods for
1760figures and graphics by adding listeners to properties or assigning
1761pre-existing actions, such as in the following example:
1762
1763     function mydeletefcn (h, ~, msg)
1764       printf (msg);
1765     endfunction
1766     sombrero;
1767     set (gcf, "deletefcn", {@mydeletefcn, "Bye!\n"});
1768     close;
1769
1770The above will print "Bye!"  to the terminal upon the closing (deleting)
1771of the figure.  There are many graphics property actions for which a
1772callback function may be assigned, including, ‘buttondownfcn’,
1773‘windowscrollwheelfcn’, ‘createfcn’, ‘deletefcn’, ‘keypressfcn’, etc.
1774
1775   Note that the ‘@’ character also plays a role in defining class
1776functions, i.e., methods, but not as a syntactical element.  Rather it
1777begins a directory name containing methods for a class that shares the
1778directory name sans the ‘@’ character.  See *note Object Oriented
1779Programming::.
1780
1781
1782File: octave.info,  Node: Arithmetic Ops,  Next: Comparison Ops,  Prev: Calling Functions,  Up: Expressions
1783
17848.3 Arithmetic Operators
1785========================
1786
1787The following arithmetic operators are available, and work on scalars
1788and matrices.  The element-by-element operators and functions broadcast
1789(*note Broadcasting::).
1790
1791X + Y
1792     Addition.  If both operands are matrices, the number of rows and
1793     columns must both agree, or they must be broadcastable to the same
1794     shape.
1795
1796X .+ Y
1797     Element-by-element addition.  This operator is equivalent to ‘+’.
1798
1799X - Y
1800     Subtraction.  If both operands are matrices, the number of rows and
1801     columns of both must agree, or they must be broadcastable to the
1802     same shape.
1803
1804X .- Y
1805     Element-by-element subtraction.  This operator is equivalent to
1806     ‘-’.
1807
1808X * Y
1809     Matrix multiplication.  The number of columns of X must agree with
1810     the number of rows of Y.
1811
1812X .* Y
1813     Element-by-element multiplication.  If both operands are matrices,
1814     the number of rows and columns must both agree, or they must be
1815     broadcastable to the same shape.
1816
1817X / Y
1818     Right division.  This is conceptually equivalent to the expression
1819
1820          (inv (y') * x')'
1821
1822     but it is computed without forming the inverse of Y’.
1823
1824     If the system is not square, or if the coefficient matrix is
1825     singular, a minimum norm solution is computed.
1826
1827X ./ Y
1828     Element-by-element right division.
1829
1830X \ Y
1831     Left division.  This is conceptually equivalent to the expression
1832
1833          inv (x) * y
1834
1835     but it is computed without forming the inverse of X.
1836
1837     If the system is not square, or if the coefficient matrix is
1838     singular, a minimum norm solution is computed.
1839
1840X .\ Y
1841     Element-by-element left division.  Each element of Y is divided by
1842     each corresponding element of X.
1843
1844X ^ Y
1845X ** Y
1846     Power operator.  If X and Y are both scalars, this operator returns
1847     X raised to the power Y.  If X is a scalar and Y is a square
1848     matrix, the result is computed using an eigenvalue expansion.  If X
1849     is a square matrix, the result is computed by repeated
1850     multiplication if Y is an integer, and by an eigenvalue expansion
1851     if Y is not an integer.  An error results if both X and Y are
1852     matrices.
1853
1854     The implementation of this operator needs to be improved.
1855
1856X .^ Y
1857X .** Y
1858     Element-by-element power operator.  If both operands are matrices,
1859     the number of rows and columns must both agree, or they must be
1860     broadcastable to the same shape.  If several complex results are
1861     possible, the one with smallest non-negative argument (angle) is
1862     taken.  This rule may return a complex root even when a real root
1863     is also possible.  Use ‘realpow’, ‘realsqrt’, ‘cbrt’, or ‘nthroot’
1864     if a real result is preferred.
1865
1866-X
1867     Negation.
1868
1869+X
1870     Unary plus.  This operator has no effect on the operand.
1871
1872X’
1873     Complex conjugate transpose.  For real arguments, this operator is
1874     the same as the transpose operator.  For complex arguments, this
1875     operator is equivalent to the expression
1876
1877          conj (x.')
1878
1879X.’
1880     Transpose.
1881
1882   Note that because Octave’s element-by-element operators begin with a
1883‘.’, there is a possible ambiguity for statements like
1884
1885     1./m
1886
1887because the period could be interpreted either as part of the constant
1888or as part of the operator.  To resolve this conflict, Octave treats the
1889expression as if you had typed
1890
1891     (1) ./ m
1892
1893and not
1894
1895     (1.) / m
1896
1897Although this is inconsistent with the normal behavior of Octave’s
1898lexer, which usually prefers to break the input into tokens by
1899preferring the longest possible match at any given point, it is more
1900useful in this case.
1901
1902 -- : ctranspose (X)
1903     Return the complex conjugate transpose of X.
1904
1905     This function and X’ are equivalent.
1906
1907     See also: *note transpose: XREFtranspose.
1908
1909 -- : ldivide (X, Y)
1910     Return the element-by-element left division of X and Y.
1911
1912     This function and X .\ Y are equivalent.
1913
1914     See also: *note rdivide: XREFrdivide, *note mldivide: XREFmldivide,
1915     *note times: XREFtimes, *note plus: XREFplus.
1916
1917 -- : minus (X, Y)
1918     This function and X - Y are equivalent.
1919
1920     See also: *note plus: XREFplus, *note uminus: XREFuminus.
1921
1922 -- : mldivide (X, Y)
1923     Return the matrix left division of X and Y.
1924
1925     This function and X \ Y are equivalent.
1926
1927     If the system is not square, or if the coefficient matrix is
1928     singular, a minimum norm solution is computed.
1929
1930     See also: *note mrdivide: XREFmrdivide, *note ldivide: XREFldivide,
1931     *note rdivide: XREFrdivide, *note linsolve: XREFlinsolve.
1932
1933 -- : mpower (X, Y)
1934     Return the matrix power operation of X raised to the Y power.
1935
1936     This function and X ^ Y are equivalent.
1937
1938     See also: *note power: XREFpower, *note mtimes: XREFmtimes, *note
1939     plus: XREFplus, *note minus: XREFminus.
1940
1941 -- : mrdivide (X, Y)
1942     Return the matrix right division of X and Y.
1943
1944     This function and X / Y are equivalent.
1945
1946     If the system is not square, or if the coefficient matrix is
1947     singular, a minimum norm solution is computed.
1948
1949     See also: *note mldivide: XREFmldivide, *note rdivide: XREFrdivide,
1950     *note plus: XREFplus, *note minus: XREFminus.
1951
1952 -- : mtimes (X, Y)
1953 -- : mtimes (X1, X2, ...)
1954     Return the matrix multiplication product of inputs.
1955
1956     This function and X * Y are equivalent.  If more arguments are
1957     given, the multiplication is applied cumulatively from left to
1958     right:
1959
1960          (...((X1 * X2) * X3) * ...)
1961
1962     See also: *note times: XREFtimes, *note plus: XREFplus, *note
1963     minus: XREFminus, *note rdivide: XREFrdivide, *note mrdivide:
1964     XREFmrdivide, *note mldivide: XREFmldivide, *note mpower:
1965     XREFmpower.
1966
1967 -- : plus (X, Y)
1968 -- : plus (X1, X2, ...)
1969     This function and X + Y are equivalent.
1970
1971     If more arguments are given, the summation is applied cumulatively
1972     from left to right:
1973
1974          (...((X1 + X2) + X3) + ...)
1975
1976     See also: *note minus: XREFminus, *note uplus: XREFuplus.
1977
1978 -- : power (X, Y)
1979     Return the element-by-element operation of X raised to the Y power.
1980
1981     This function and X .^ Y are equivalent.
1982
1983     If several complex results are possible, returns the one with
1984     smallest non-negative argument (angle).  Use ‘realpow’, ‘realsqrt’,
1985     ‘cbrt’, or ‘nthroot’ if a real result is preferred.
1986
1987     See also: *note mpower: XREFmpower, *note realpow: XREFrealpow,
1988     *note realsqrt: XREFrealsqrt, *note cbrt: XREFcbrt, *note nthroot:
1989     XREFnthroot.
1990
1991 -- : rdivide (X, Y)
1992     Return the element-by-element right division of X and Y.
1993
1994     This function and X ./ Y are equivalent.
1995
1996     See also: *note ldivide: XREFldivide, *note mrdivide: XREFmrdivide,
1997     *note times: XREFtimes, *note plus: XREFplus.
1998
1999 -- : times (X, Y)
2000 -- : times (X1, X2, ...)
2001     Return the element-by-element multiplication product of inputs.
2002
2003     This function and X .* Y are equivalent.  If more arguments are
2004     given, the multiplication is applied cumulatively from left to
2005     right:
2006
2007          (...((X1 .* X2) .* X3) .* ...)
2008
2009     See also: *note mtimes: XREFmtimes, *note rdivide: XREFrdivide.
2010
2011 -- : transpose (X)
2012     Return the transpose of X.
2013
2014     This function and X.’ are equivalent.
2015
2016     See also: *note ctranspose: XREFctranspose.
2017
2018 -- : uminus (X)
2019     This function and - X are equivalent.
2020
2021     See also: *note uplus: XREFuplus, *note minus: XREFminus.
2022
2023 -- : uplus (X)
2024     This function and + X are equivalent.
2025
2026     See also: *note uminus: XREFuminus, *note plus: XREFplus.
2027
2028
2029File: octave.info,  Node: Comparison Ops,  Next: Boolean Expressions,  Prev: Arithmetic Ops,  Up: Expressions
2030
20318.4 Comparison Operators
2032========================
2033
2034“Comparison operators” compare numeric values for relationships such as
2035equality.  They are written using _relational operators_.
2036
2037   All of Octave’s comparison operators return a value of 1 if the
2038comparison is true, or 0 if it is false.  For matrix values, they all
2039work on an element-by-element basis.  Broadcasting rules apply.  *Note
2040Broadcasting::.  For example:
2041
2042     [1, 2; 3, 4] == [1, 3; 2, 4]
2043          ⇒  1  0
2044              0  1
2045
2046   According to broadcasting rules, if one operand is a scalar and the
2047other is a matrix, the scalar is compared to each element of the matrix
2048in turn, and the result is the same size as the matrix.
2049
2050‘X < Y’
2051     True if X is less than Y.
2052
2053‘X <= Y’
2054     True if X is less than or equal to Y.
2055
2056‘X == Y’
2057     True if X is equal to Y.
2058
2059‘X >= Y’
2060     True if X is greater than or equal to Y.
2061
2062‘X > Y’
2063     True if X is greater than Y.
2064
2065‘X != Y’
2066‘X ~= Y’
2067     True if X is not equal to Y.
2068
2069   For complex numbers, the following ordering is defined: Z1 < Z2 if
2070and only if
2071
2072       abs (Z1) < abs (Z2)
2073       || (abs (Z1) == abs (Z2) && arg (Z1) < arg (Z2))
2074
2075   This is consistent with the ordering used by “max”, “min” and “sort”,
2076but is not consistent with MATLAB, which only compares the real parts.
2077
2078   String comparisons may also be performed with the ‘strcmp’ function,
2079not with the comparison operators listed above.  *Note Strings::.
2080
2081 -- : eq (X, Y)
2082     Return true if the two inputs are equal.
2083
2084     This function is equivalent to ‘X == Y’.
2085
2086     See also: *note ne: XREFne, *note isequal: XREFisequal, *note le:
2087     XREFle, *note ge: XREFge, *note gt: XREFgt, *note ne: XREFne, *note
2088     lt: XREFlt.
2089
2090 -- : ge (X, Y)
2091     This function is equivalent to ‘X >= Y’.
2092
2093     See also: *note le: XREFle, *note eq: XREFeq, *note gt: XREFgt,
2094     *note ne: XREFne, *note lt: XREFlt.
2095
2096 -- : gt (X, Y)
2097     This function is equivalent to ‘X > Y’.
2098
2099     See also: *note le: XREFle, *note eq: XREFeq, *note ge: XREFge,
2100     *note ne: XREFne, *note lt: XREFlt.
2101
2102 -- : isequal (X1, X2, ...)
2103     Return true if all of X1, X2, ... are equal.
2104
2105     See also: *note isequaln: XREFisequaln.
2106
2107 -- : isequaln (X1, X2, ...)
2108     Return true if all of X1, X2, ... are equal under the additional
2109     assumption that NaN == NaN (no comparison of NaN placeholders in
2110     dataset).
2111
2112     See also: *note isequal: XREFisequal.
2113
2114 -- : le (X, Y)
2115     This function is equivalent to ‘X <= Y’.
2116
2117     See also: *note eq: XREFeq, *note ge: XREFge, *note gt: XREFgt,
2118     *note ne: XREFne, *note lt: XREFlt.
2119
2120 -- : lt (X, Y)
2121     This function is equivalent to ‘X < Y’.
2122
2123     See also: *note le: XREFle, *note eq: XREFeq, *note ge: XREFge,
2124     *note gt: XREFgt, *note ne: XREFne.
2125
2126 -- : ne (X, Y)
2127     Return true if the two inputs are not equal.
2128
2129     This function is equivalent to ‘X != Y’.
2130
2131     See also: *note eq: XREFeq, *note isequal: XREFisequal, *note le:
2132     XREFle, *note ge: XREFge, *note lt: XREFlt.
2133
2134
2135File: octave.info,  Node: Boolean Expressions,  Next: Assignment Ops,  Prev: Comparison Ops,  Up: Expressions
2136
21378.5 Boolean Expressions
2138=======================
2139
2140* Menu:
2141
2142* Element-by-element Boolean Operators::
2143* Short-circuit Boolean Operators::
2144
2145
2146File: octave.info,  Node: Element-by-element Boolean Operators,  Next: Short-circuit Boolean Operators,  Up: Boolean Expressions
2147
21488.5.1 Element-by-element Boolean Operators
2149------------------------------------------
2150
2151An “element-by-element boolean expression” is a combination of
2152comparison expressions using the boolean operators “or” (‘|’), “and”
2153(‘&’), and “not” (‘!’), along with parentheses to control nesting.  The
2154truth of the boolean expression is computed by combining the truth
2155values of the corresponding elements of the component expressions.  A
2156value is considered to be false if it is zero, and true otherwise.
2157
2158   Element-by-element boolean expressions can be used wherever
2159comparison expressions can be used.  They can be used in ‘if’ and
2160‘while’ statements.  However, a matrix value used as the condition in an
2161‘if’ or ‘while’ statement is only true if _all_ of its elements are
2162nonzero.
2163
2164   Like comparison operations, each element of an element-by-element
2165boolean expression also has a numeric value (1 if true, 0 if false) that
2166comes into play if the result of the boolean expression is stored in a
2167variable, or used in arithmetic.
2168
2169   Here are descriptions of the three element-by-element boolean
2170operators.
2171
2172‘BOOLEAN1 & BOOLEAN2’
2173     Elements of the result are true if both corresponding elements of
2174     BOOLEAN1 and BOOLEAN2 are true.
2175
2176‘BOOLEAN1 | BOOLEAN2’
2177     Elements of the result are true if either of the corresponding
2178     elements of BOOLEAN1 or BOOLEAN2 is true.
2179
2180‘! BOOLEAN’
2181‘~ BOOLEAN’
2182     Each element of the result is true if the corresponding element of
2183     BOOLEAN is false.
2184
2185   These operators work on an element-by-element basis.  For example,
2186the expression
2187
2188     [1, 0; 0, 1] & [1, 0; 2, 3]
2189
2190returns a two by two identity matrix.
2191
2192   For the binary operators, broadcasting rules apply.  *Note
2193Broadcasting::.  In particular, if one of the operands is a scalar and
2194the other a matrix, the operator is applied to the scalar and each
2195element of the matrix.
2196
2197   For the binary element-by-element boolean operators, both
2198subexpressions BOOLEAN1 and BOOLEAN2 are evaluated before computing the
2199result.  This can make a difference when the expressions have side
2200effects.  For example, in the expression
2201
2202     a & b++
2203
2204the value of the variable B is incremented even if the variable A is
2205zero.
2206
2207   This behavior is necessary for the boolean operators to work as
2208described for matrix-valued operands.
2209
2210 -- : Z = and (X, Y)
2211 -- : Z = and (X1, X2, ...)
2212     Return the logical AND of X and Y.
2213
2214     This function is equivalent to the operator syntax ‘X & Y’.  If
2215     more than two arguments are given, the logical AND is applied
2216     cumulatively from left to right:
2217
2218          (...((X1 & X2) & X3) & ...)
2219
2220     See also: *note or: XREFor, *note not: XREFnot, *note xor: XREFxor.
2221
2222 -- : Z = not (X)
2223     Return the logical NOT of X.
2224
2225     This function is equivalent to the operator syntax ‘! X’.
2226
2227     See also: *note and: XREFand, *note or: XREFor, *note xor: XREFxor.
2228
2229 -- : Z = or (X, Y)
2230 -- : Z = or (X1, X2, ...)
2231     Return the logical OR of X and Y.
2232
2233     This function is equivalent to the operator syntax ‘X | Y’.  If
2234     more than two arguments are given, the logical OR is applied
2235     cumulatively from left to right:
2236
2237          (...((X1 | X2) | X3) | ...)
2238
2239     See also: *note and: XREFand, *note not: XREFnot, *note xor:
2240     XREFxor.
2241
2242
2243File: octave.info,  Node: Short-circuit Boolean Operators,  Prev: Element-by-element Boolean Operators,  Up: Boolean Expressions
2244
22458.5.2 Short-circuit Boolean Operators
2246-------------------------------------
2247
2248Combined with the implicit conversion to scalar values in ‘if’ and
2249‘while’ conditions, Octave’s element-by-element boolean operators are
2250often sufficient for performing most logical operations.  However, it is
2251sometimes desirable to stop evaluating a boolean expression as soon as
2252the overall truth value can be determined.  Octave’s “short-circuit”
2253boolean operators work this way.
2254
2255‘BOOLEAN1 && BOOLEAN2’
2256     The expression BOOLEAN1 is evaluated and converted to a scalar
2257     using the equivalent of the operation ‘all (BOOLEAN1(:))’.  If it
2258     is false, the result of the overall expression is 0.  If it is
2259     true, the expression BOOLEAN2 is evaluated and converted to a
2260     scalar using the equivalent of the operation ‘all (BOOLEAN2(:))’.
2261     If it is true, the result of the overall expression is 1.
2262     Otherwise, the result of the overall expression is 0.
2263
2264     *Warning:* there is one exception to the rule of evaluating ‘all
2265     (BOOLEAN1(:))’, which is when ‘boolean1’ is the empty matrix.  The
2266     truth value of an empty matrix is always ‘false’ so ‘[] && true’
2267     evaluates to ‘false’ even though ‘all ([])’ is ‘true’.
2268
2269‘BOOLEAN1 || BOOLEAN2’
2270     The expression BOOLEAN1 is evaluated and converted to a scalar
2271     using the equivalent of the operation ‘all (BOOLEAN1(:))’.  If it
2272     is true, the result of the overall expression is 1.  If it is
2273     false, the expression BOOLEAN2 is evaluated and converted to a
2274     scalar using the equivalent of the operation ‘all (BOOLEAN2(:))’.
2275     If it is true, the result of the overall expression is 1.
2276     Otherwise, the result of the overall expression is 0.
2277
2278     *Warning:* the truth value of an empty matrix is always ‘false’,
2279     see the previous list item for details.
2280
2281   The fact that both operands may not be evaluated before determining
2282the overall truth value of the expression can be important.  For
2283example, in the expression
2284
2285     a && b++
2286
2287the value of the variable B is only incremented if the variable A is
2288nonzero.
2289
2290   This can be used to write somewhat more concise code.  For example,
2291it is possible write
2292
2293     function f (a, b, c)
2294       if (nargin > 2 && ischar (c))
2295         ...
2296
2297instead of having to use two ‘if’ statements to avoid attempting to
2298evaluate an argument that doesn’t exist.  For example, without the
2299short-circuit feature, it would be necessary to write
2300
2301     function f (a, b, c)
2302       if (nargin > 2)
2303         if (ischar (c))
2304           ...
2305
2306Writing
2307
2308     function f (a, b, c)
2309       if (nargin > 2 & ischar (c))
2310         ...
2311
2312would result in an error if ‘f’ were called with one or two arguments
2313because Octave would be forced to try to evaluate both of the operands
2314for the operator ‘&’.
2315
2316   MATLAB has special behavior that allows the operators ‘&’ and ‘|’ to
2317short-circuit when used in the truth expression for ‘if’ and ‘while’
2318statements.  Octave behaves the same way for compatibility, however, the
2319use of the ‘&’ and ‘|’ operators in this way is strongly discouraged and
2320a warning will be issued.  Instead, you should use the ‘&&’ and ‘||’
2321operators that always have short-circuit behavior.
2322
2323   Finally, the ternary operator (?:) is not supported in Octave.  If
2324short-circuiting is not important, it can be replaced by the ‘ifelse’
2325function.
2326
2327 -- : merge (MASK, TVAL, FVAL)
2328 -- : ifelse (MASK, TVAL, FVAL)
2329     Merge elements of TRUE_VAL and FALSE_VAL, depending on the value of
2330     MASK.
2331
2332     If MASK is a logical scalar, the other two arguments can be
2333     arbitrary values.  Otherwise, MASK must be a logical array, and
2334     TVAL, FVAL should be arrays of matching class, or cell arrays.  In
2335     the scalar mask case, TVAL is returned if MASK is true, otherwise
2336     FVAL is returned.
2337
2338     In the array mask case, both TVAL and FVAL must be either scalars
2339     or arrays with dimensions equal to MASK.  The result is constructed
2340     as follows:
2341
2342          result(mask) = tval(mask);
2343          result(! mask) = fval(! mask);
2344
2345     MASK can also be arbitrary numeric type, in which case it is first
2346     converted to logical.
2347
2348     See also: *note logical: XREFlogical, *note diff: XREFdiff.
2349
2350
2351File: octave.info,  Node: Assignment Ops,  Next: Increment Ops,  Prev: Boolean Expressions,  Up: Expressions
2352
23538.6 Assignment Expressions
2354==========================
2355
2356An “assignment” is an expression that stores a new value into a
2357variable.  For example, the following expression assigns the value 1 to
2358the variable ‘z’:
2359
2360     z = 1
2361
2362After this expression is executed, the variable ‘z’ has the value 1.
2363Whatever old value ‘z’ had before the assignment is forgotten.  The ‘=’
2364sign is called an “assignment operator”.
2365
2366   Assignments can store string values also.  For example, the following
2367expression would store the value "this food is good" in the variable
2368‘message’:
2369
2370     thing = "food"
2371     predicate = "good"
2372     message = [ "this " , thing , " is " , predicate ]
2373
2374(This also illustrates concatenation of strings.)
2375
2376   Most operators (addition, concatenation, and so on) have no effect
2377except to compute a value.  If you ignore the value, you might as well
2378not use the operator.  An assignment operator is different.  It does
2379produce a value, but even if you ignore the value, the assignment still
2380makes itself felt through the alteration of the variable.  We call this
2381a “side effect”.
2382
2383   The left-hand operand of an assignment need not be a variable (*note
2384Variables::).  It can also be an element of a matrix (*note Index
2385Expressions::) or a list of return values (*note Calling Functions::).
2386These are all called “lvalues”, which means they can appear on the
2387left-hand side of an assignment operator.  The right-hand operand may be
2388any expression.  It produces the new value which the assignment stores
2389in the specified variable, matrix element, or list of return values.
2390
2391   It is important to note that variables do _not_ have permanent types.
2392The type of a variable is simply the type of whatever value it happens
2393to hold at the moment.  In the following program fragment, the variable
2394‘foo’ has a numeric value at first, and a string value later on:
2395
2396     octave:13> foo = 1
2397     foo = 1
2398     octave:13> foo = "bar"
2399     foo = bar
2400
2401When the second assignment gives ‘foo’ a string value, the fact that it
2402previously had a numeric value is forgotten.
2403
2404   Assignment of a scalar to an indexed matrix sets all of the elements
2405that are referenced by the indices to the scalar value.  For example, if
2406‘a’ is a matrix with at least two columns,
2407
2408     a(:, 2) = 5
2409
2410sets all the elements in the second column of ‘a’ to 5.
2411
2412   Assigning an empty matrix ‘[]’ works in most cases to allow you to
2413delete rows or columns of matrices and vectors.  *Note Empty Matrices::.
2414For example, given a 4 by 5 matrix A, the assignment
2415
2416     A (3, :) = []
2417
2418deletes the third row of A, and the assignment
2419
2420     A (:, 1:2:5) = []
2421
2422deletes the first, third, and fifth columns.
2423
2424   An assignment is an expression, so it has a value.  Thus, ‘z = 1’ as
2425an expression has the value 1.  One consequence of this is that you can
2426write multiple assignments together:
2427
2428     x = y = z = 0
2429
2430stores the value 0 in all three variables.  It does this because the
2431value of ‘z = 0’, which is 0, is stored into ‘y’, and then the value of
2432‘y = z = 0’, which is 0, is stored into ‘x’.
2433
2434   This is also true of assignments to lists of values, so the following
2435is a valid expression
2436
2437     [a, b, c] = [u, s, v] = svd (a)
2438
2439that is exactly equivalent to
2440
2441     [u, s, v] = svd (a)
2442     a = u
2443     b = s
2444     c = v
2445
2446   In expressions like this, the number of values in each part of the
2447expression need not match.  For example, the expression
2448
2449     [a, b] = [u, s, v] = svd (a)
2450
2451is equivalent to
2452
2453     [u, s, v] = svd (a)
2454     a = u
2455     b = s
2456
2457The number of values on the left side of the expression can, however,
2458not exceed the number of values on the right side.  For example, the
2459following will produce an error.
2460
2461     [a, b, c, d] = [u, s, v] = svd (a);
2462     ⊣ error: element number 4 undefined in return list
2463
2464   The symbol ‘~’ may be used as a placeholder in the list of lvalues,
2465indicating that the corresponding return value should be ignored and not
2466stored anywhere:
2467
2468     [~, s, v] = svd (a);
2469
2470   This is cleaner and more memory efficient than using a dummy
2471variable.  The ‘nargout’ value for the right-hand side expression is not
2472affected.  If the assignment is used as an expression, the return value
2473is a comma-separated list with the ignored values dropped.
2474
2475   A very common programming pattern is to increment an existing
2476variable with a given value, like this
2477
2478     a = a + 2;
2479
2480This can be written in a clearer and more condensed form using the ‘+=’
2481operator
2482
2483     a += 2;
2484
2485Similar operators also exist for subtraction (‘-=’), multiplication
2486(‘*=’), and division (‘/=’).  An expression of the form
2487
2488     EXPR1 OP= EXPR2
2489
2490is evaluated as
2491
2492     EXPR1 = (EXPR1) OP (EXPR2)
2493
2494where OP can be either ‘+’, ‘-’, ‘*’, or ‘/’, as long as EXPR2 is a
2495simple expression with no side effects.  If EXPR2 also contains an
2496assignment operator, then this expression is evaluated as
2497
2498     TEMP = EXPR2
2499     EXPR1 = (EXPR1) OP TEMP
2500
2501where TEMP is a placeholder temporary value storing the computed result
2502of evaluating EXPR2.  So, the expression
2503
2504     a *= b+1
2505
2506is evaluated as
2507
2508     a = a * (b+1)
2509
2510and _not_
2511
2512     a = a * b + 1
2513
2514   You can use an assignment anywhere an expression is called for.  For
2515example, it is valid to write ‘x != (y = 1)’ to set ‘y’ to 1 and then
2516test whether ‘x’ equals 1.  But this style tends to make programs hard
2517to read.  Except in a one-shot program, you should rewrite it to get rid
2518of such nesting of assignments.  This is never very hard.
2519
2520
2521File: octave.info,  Node: Increment Ops,  Next: Operator Precedence,  Prev: Assignment Ops,  Up: Expressions
2522
25238.7 Increment Operators
2524=======================
2525
2526_Increment operators_ increase or decrease the value of a variable by 1.
2527The operator to increment a variable is written as ‘++’.  It may be used
2528to increment a variable either before or after taking its value.
2529
2530   For example, to pre-increment the variable X, you would write ‘++X’.
2531This would add one to X and then return the new value of X as the result
2532of the expression.  It is exactly the same as the expression ‘X = X +
25331’.
2534
2535   To post-increment a variable X, you would write ‘X++’.  This adds one
2536to the variable X, but returns the value that X had prior to
2537incrementing it.  For example, if X is equal to 2, the result of the
2538expression ‘X++’ is 2, and the new value of X is 3.
2539
2540   For matrix and vector arguments, the increment and decrement
2541operators work on each element of the operand.
2542
2543   Here is a list of all the increment and decrement expressions.
2544
2545‘++X’
2546     This expression increments the variable X.  The value of the
2547     expression is the _new_ value of X.  It is equivalent to the
2548     expression ‘X = X + 1’.
2549
2550‘--X’
2551     This expression decrements the variable X.  The value of the
2552     expression is the _new_ value of X.  It is equivalent to the
2553     expression ‘X = X - 1’.
2554
2555‘X++’
2556     This expression causes the variable X to be incremented.  The value
2557     of the expression is the _old_ value of X.
2558
2559‘X--’
2560     This expression causes the variable X to be decremented.  The value
2561     of the expression is the _old_ value of X.
2562
2563
2564File: octave.info,  Node: Operator Precedence,  Prev: Increment Ops,  Up: Expressions
2565
25668.8 Operator Precedence
2567=======================
2568
2569“Operator precedence” determines how operators are grouped, when
2570different operators appear close by in one expression.  For example, ‘*’
2571has higher precedence than ‘+’.  Thus, the expression ‘a + b * c’ means
2572to multiply ‘b’ and ‘c’, and then add ‘a’ to the product (i.e., ‘a + (b
2573* c)’).
2574
2575   You can overrule the precedence of the operators by using
2576parentheses.  You can think of the precedence rules as saying where the
2577parentheses are assumed if you do not write parentheses yourself.  In
2578fact, it is wise to use parentheses whenever you have an unusual
2579combination of operators, because other people who read the program may
2580not remember what the precedence is in this case.  You might forget as
2581well, and then you too could make a mistake.  Explicit parentheses will
2582help prevent any such mistake.
2583
2584   When operators of equal precedence are used together, the leftmost
2585operator groups first, except for the assignment operators, which group
2586in the opposite order.  Thus, the expression ‘a - b + c’ groups as ‘(a -
2587b) + c’, but the expression ‘a = b = c’ groups as ‘a = (b = c)’.
2588
2589   The precedence of prefix unary operators is important when another
2590operator follows the operand.  For example, ‘-x^2’ means ‘-(x^2)’,
2591because ‘-’ has lower precedence than ‘^’.
2592
2593   Here is a table of the operators in Octave, in order of decreasing
2594precedence.  Unless noted, all operators group left to right.
2595
2596‘function call and array indexing, cell array indexing, and structure element indexing’
2597     ‘()’ ‘{}’ ‘.’
2598
2599‘postfix increment, and postfix decrement’
2600     ‘++’ ‘--’
2601
2602     These operators group right to left.
2603
2604‘transpose and exponentiation’
2605     ‘'’ ‘.'’  ‘^’ ‘**’ ‘.^’ ‘.**’
2606
2607‘unary plus, unary minus, prefix increment, prefix decrement, and logical "not"’
2608     ‘+’ ‘-’ ‘++’ ‘--’ ‘~’ ‘!’
2609
2610‘multiply and divide’
2611     ‘*’ ‘/’ ‘\’ ‘.\’ ‘.*’ ‘./’
2612
2613‘add, subtract’
2614     ‘+’ ‘-’
2615
2616‘colon’
2617     ‘:’
2618
2619‘relational’
2620     ‘<’ ‘<=’ ‘==’ ‘>=’ ‘>’ ‘!=’ ‘~=’
2621
2622‘element-wise "and"’
2623     ‘&’
2624
2625‘element-wise "or"’
2626     ‘|’
2627
2628‘logical "and"’
2629     ‘&&’
2630
2631‘logical "or"’
2632     ‘||’
2633
2634‘assignment’
2635     ‘=’ ‘+=’ ‘-=’ ‘*=’ ‘/=’ ‘\=’ ‘^=’ ‘.*=’ ‘./=’ ‘.\=’ ‘.^=’ ‘|=’ ‘&=’
2636
2637     These operators group right to left.
2638
2639
2640File: octave.info,  Node: Evaluation,  Next: Statements,  Prev: Expressions,  Up: Top
2641
26429 Evaluation
2643************
2644
2645Normally, you evaluate expressions simply by typing them at the Octave
2646prompt, or by asking Octave to interpret commands that you have saved in
2647a file.
2648
2649   Sometimes, you may find it necessary to evaluate an expression that
2650has been computed and stored in a string, which is exactly what the
2651‘eval’ function lets you do.
2652
2653 -- : eval (TRY)
2654 -- : eval (TRY, CATCH)
2655     Parse the string TRY and evaluate it as if it were an Octave
2656     program.
2657
2658     If execution fails, evaluate the optional string CATCH.
2659
2660     The string TRY is evaluated in the current context, so any results
2661     remain available after ‘eval’ returns.
2662
2663     The following example creates the variable A with the approximate
2664     value of 3.1416 in the current workspace.
2665
2666          eval ("A = acos(-1);");
2667
2668     If an error occurs during the evaluation of TRY then the CATCH
2669     string is evaluated, as the following example shows:
2670
2671          eval ('error ("This is a bad example");',
2672                'printf ("This error occurred:\n%s\n", lasterr ());');
2673               ⊣ This error occurred:
2674                  This is a bad example
2675
2676     Programming Note: if you are only using ‘eval’ as an
2677     error-capturing mechanism, rather than for the execution of
2678     arbitrary code strings, Consider using try/catch blocks or
2679     unwind_protect/unwind_protect_cleanup blocks instead.  These
2680     techniques have higher performance and don’t introduce the security
2681     considerations that the evaluation of arbitrary code does.
2682
2683     See also: *note evalin: XREFevalin, *note evalc: XREFevalc, *note
2684     assignin: XREFassignin, *note feval: XREFfeval.
2685
2686   The ‘evalc’ function additionally captures any console output
2687produced by the evaluated expression.
2688
2689 -- : S = evalc (TRY)
2690 -- : S = evalc (TRY, CATCH)
2691     Parse and evaluate the string TRY as if it were an Octave program,
2692     while capturing the output into the return variable S.
2693
2694     If execution fails, evaluate the optional string CATCH.
2695
2696     This function behaves like ‘eval’, but any output or warning
2697     messages which would normally be written to the console are
2698     captured and returned in the string S.
2699
2700     The ‘diary’ is disabled during the execution of this function.
2701     When ‘system’ is used, any output produced by external programs is
2702     _not_ captured, unless their output is captured by the ‘system’
2703     function itself.
2704
2705          s = evalc ("t = 42"), t
2706            ⇒ s = t =  42
2707
2708            ⇒ t =  42
2709
2710     See also: *note eval: XREFeval, *note diary: XREFdiary.
2711
2712* Menu:
2713
2714* Calling a Function by its Name::
2715* Evaluation in a Different Context::
2716
2717
2718File: octave.info,  Node: Calling a Function by its Name,  Next: Evaluation in a Different Context,  Up: Evaluation
2719
27209.1 Calling a Function by its Name
2721==================================
2722
2723The ‘feval’ function allows you to call a function from a string
2724containing its name.  This is useful when writing a function that needs
2725to call user-supplied functions.  The ‘feval’ function takes the name of
2726the function to call as its first argument, and the remaining arguments
2727are given to the function.
2728
2729   The following example is a simple-minded function using ‘feval’ that
2730finds the root of a user-supplied function of one variable using
2731Newton’s method.
2732
2733     function result = newtroot (fname, x)
2734
2735     # usage: newtroot (fname, x)
2736     #
2737     #   fname : a string naming a function f(x).
2738     #   x     : initial guess
2739
2740       delta = tol = sqrt (eps);
2741       maxit = 200;
2742       fx = feval (fname, x);
2743       for i = 1:maxit
2744         if (abs (fx) < tol)
2745           result = x;
2746           return;
2747         else
2748           fx_new = feval (fname, x + delta);
2749           deriv = (fx_new - fx) / delta;
2750           x = x - fx / deriv;
2751           fx = fx_new;
2752         endif
2753       endfor
2754
2755       result = x;
2756
2757     endfunction
2758
2759   Note that this is only meant to be an example of calling
2760user-supplied functions and should not be taken too seriously.  In
2761addition to using a more robust algorithm, any serious code would check
2762the number and type of all the arguments, ensure that the supplied
2763function really was a function, etc.  *Note Predicates for Numeric
2764Objects::, for a list of predicates for numeric objects, and *note
2765Status of Variables::, for a description of the ‘exist’ function.
2766
2767 -- : feval (NAME, ...)
2768     Evaluate the function named NAME.
2769
2770     Any arguments after the first are passed as inputs to the named
2771     function.  For example,
2772
2773          feval ("acos", -1)
2774               ⇒ 3.1416
2775
2776     calls the function ‘acos’ with the argument ‘-1’.
2777
2778     The function ‘feval’ can also be used with function handles of any
2779     sort (*note Function Handles::).  Historically, ‘feval’ was the
2780     only way to call user-supplied functions in strings, but function
2781     handles are now preferred due to the cleaner syntax they offer.
2782     For example,
2783
2784          F = @exp;
2785          feval (F, 1)
2786              ⇒ 2.7183
2787          F (1)
2788              ⇒ 2.7183
2789
2790     are equivalent ways to call the function referred to by F.  If it
2791     cannot be predicted beforehand whether F is a function handle,
2792     function name in a string, or inline function then ‘feval’ can be
2793     used instead.
2794
2795   A similar function ‘run’ exists for calling user script files, that
2796are not necessarily on the user path
2797
2798 -- : run SCRIPT
2799 -- : run ("SCRIPT")
2800     Run SCRIPT in the current workspace.
2801
2802     Scripts which reside in directories specified in Octave’s load
2803     path, and which end with the extension ‘.m’, can be run simply by
2804     typing their name.  For scripts not located on the load path, use
2805     ‘run’.
2806
2807     The filename SCRIPT can be a bare, fully qualified, or relative
2808     filename and with or without a file extension.  If no extension is
2809     specified, Octave will first search for a script with the ‘.m’
2810     extension before falling back to the script name without an
2811     extension.
2812
2813     Implementation Note: If SCRIPT includes a path component, then
2814     ‘run’ first changes the working directory to the directory where
2815     SCRIPT is found.  Next, the script is executed.  Finally, ‘run’
2816     returns to the original working directory _unless_ SCRIPT has
2817     specifically changed directories.
2818
2819     See also: *note path: XREFpath, *note addpath: XREFaddpath, *note
2820     source: XREFsource.
2821
2822
2823File: octave.info,  Node: Evaluation in a Different Context,  Prev: Calling a Function by its Name,  Up: Evaluation
2824
28259.2 Evaluation in a Different Context
2826=====================================
2827
2828Before you evaluate an expression you need to substitute the values of
2829the variables used in the expression.  These are stored in the symbol
2830table.  Whenever the interpreter starts a new function it saves the
2831current symbol table and creates a new one, initializing it with the
2832list of function parameters and a couple of predefined variables such as
2833‘nargin’.  Expressions inside the function use the new symbol table.
2834
2835   Sometimes you want to write a function so that when you call it, it
2836modifies variables in your own context.  This allows you to use a
2837pass-by-name style of function, which is similar to using a pointer in
2838programming languages such as C.
2839
2840   Consider how you might write ‘save’ and ‘load’ as m-files.  For
2841example:
2842
2843     function create_data
2844       x = linspace (0, 10, 10);
2845       y = sin (x);
2846       save mydata x y
2847     endfunction
2848
2849   With ‘evalin’, you could write ‘save’ as follows:
2850
2851     function save (file, name1, name2)
2852       f = open_save_file (file);
2853       save_var (f, name1, evalin ("caller", name1));
2854       save_var (f, name2, evalin ("caller", name2));
2855     endfunction
2856
2857Here, ‘caller’ is the ‘create_data’ function and ‘name1’ is the string
2858"x", which evaluates simply as the value of ‘x’.
2859
2860   You later want to load the values back from ‘mydata’ in a different
2861context:
2862
2863     function process_data
2864       load mydata
2865       ... do work ...
2866     endfunction
2867
2868With ‘assignin’, you could write ‘load’ as follows:
2869
2870     function load (file)
2871       f = open_load_file (file);
2872       [name, val] = load_var (f);
2873       assignin ("caller", name, val);
2874       [name, val] = load_var (f);
2875       assignin ("caller", name, val);
2876     endfunction
2877
2878Here, ‘caller’ is the ‘process_data’ function.
2879
2880   You can set and use variables at the command prompt using the context
2881‘base’ rather than ‘caller’.
2882
2883   These functions are rarely used in practice.  One example is the
2884‘fail (‘code’, ‘pattern’)’ function which evaluates ‘code’ in the
2885caller’s context and checks that the error message it produces matches
2886the given pattern.  Other examples such as ‘save’ and ‘load’ are written
2887in C++ where all Octave variables are in the ‘caller’ context and
2888‘evalin’ is not needed.
2889
2890 -- : evalin (CONTEXT, TRY)
2891 -- : evalin (CONTEXT, TRY, CATCH)
2892     Like ‘eval’, except that the expressions are evaluated in the
2893     context CONTEXT, which may be either "caller" or "base".
2894
2895     See also: *note eval: XREFeval, *note assignin: XREFassignin.
2896
2897 -- : assignin (CONTEXT, VARNAME, VALUE)
2898     Assign VALUE to VARNAME in context CONTEXT, which may be either
2899     "base" or "caller".
2900
2901     See also: *note evalin: XREFevalin.
2902
2903
2904File: octave.info,  Node: Statements,  Next: Functions and Scripts,  Prev: Evaluation,  Up: Top
2905
290610 Statements
2907*************
2908
2909Statements may be a simple constant expression or a complicated list of
2910nested loops and conditional statements.
2911
2912   “Control statements” such as ‘if’, ‘while’, and so on control the
2913flow of execution in Octave programs.  All the control statements start
2914with special keywords such as ‘if’ and ‘while’, to distinguish them from
2915simple expressions.  Many control statements contain other statements;
2916for example, the ‘if’ statement contains another statement which may or
2917may not be executed.
2918
2919   Each control statement has a corresponding “end” statement that marks
2920the end of the control statement.  For example, the keyword ‘endif’
2921marks the end of an ‘if’ statement, and ‘endwhile’ marks the end of a
2922‘while’ statement.  You can use the keyword ‘end’ anywhere a more
2923specific end keyword is expected, but using the more specific keywords
2924is preferred because if you use them, Octave is able to provide better
2925diagnostics for mismatched or missing end tokens.
2926
2927   The list of statements contained between keywords like ‘if’ or
2928‘while’ and the corresponding end statement is called the “body” of a
2929control statement.
2930
2931* Menu:
2932
2933* The if Statement::
2934* The switch Statement::
2935* The while Statement::
2936* The do-until Statement::
2937* The for Statement::
2938* The break Statement::
2939* The continue Statement::
2940* The unwind_protect Statement::
2941* The try Statement::
2942* Continuation Lines::
2943
2944
2945File: octave.info,  Node: The if Statement,  Next: The switch Statement,  Up: Statements
2946
294710.1 The if Statement
2948=====================
2949
2950The ‘if’ statement is Octave’s decision-making statement.  There are
2951three basic forms of an ‘if’ statement.  In its simplest form, it looks
2952like this:
2953
2954     if (CONDITION)
2955       THEN-BODY
2956     endif
2957
2958CONDITION is an expression that controls what the rest of the statement
2959will do.  The THEN-BODY is executed only if CONDITION is true.
2960
2961   The condition in an ‘if’ statement is considered true if its value is
2962nonzero, and false if its value is zero.  If the value of the
2963conditional expression in an ‘if’ statement is a vector or a matrix, it
2964is considered true only if it is non-empty and _all_ of the elements are
2965nonzero.  The conceptually equivalent code when CONDITION is a matrix is
2966shown below.
2967
2968     if (MATRIX) ≡ if (all (MATRIX(:)))
2969
2970The second form of an if statement looks like this:
2971
2972     if (CONDITION)
2973       THEN-BODY
2974     else
2975       ELSE-BODY
2976     endif
2977
2978If CONDITION is true, THEN-BODY is executed; otherwise, ELSE-BODY is
2979executed.
2980
2981   Here is an example:
2982
2983     if (rem (x, 2) == 0)
2984       printf ("x is even\n");
2985     else
2986       printf ("x is odd\n");
2987     endif
2988
2989   In this example, if the expression ‘rem (x, 2) == 0’ is true (that
2990is, the value of ‘x’ is divisible by 2), then the first ‘printf’
2991statement is evaluated, otherwise the second ‘printf’ statement is
2992evaluated.
2993
2994   The third and most general form of the ‘if’ statement allows multiple
2995decisions to be combined in a single statement.  It looks like this:
2996
2997     if (CONDITION)
2998       THEN-BODY
2999     elseif (CONDITION)
3000       ELSEIF-BODY
3001     else
3002       ELSE-BODY
3003     endif
3004
3005Any number of ‘elseif’ clauses may appear.  Each condition is tested in
3006turn, and if one is found to be true, its corresponding BODY is
3007executed.  If none of the conditions are true and the ‘else’ clause is
3008present, its body is executed.  Only one ‘else’ clause may appear, and
3009it must be the last part of the statement.
3010
3011   In the following example, if the first condition is true (that is,
3012the value of ‘x’ is divisible by 2), then the first ‘printf’ statement
3013is executed.  If it is false, then the second condition is tested, and
3014if it is true (that is, the value of ‘x’ is divisible by 3), then the
3015second ‘printf’ statement is executed.  Otherwise, the third ‘printf’
3016statement is performed.
3017
3018     if (rem (x, 2) == 0)
3019       printf ("x is even\n");
3020     elseif (rem (x, 3) == 0)
3021       printf ("x is odd and divisible by 3\n");
3022     else
3023       printf ("x is odd\n");
3024     endif
3025
3026   Note that the ‘elseif’ keyword must not be spelled ‘else if’, as is
3027allowed in Fortran.  If it is, the space between the ‘else’ and ‘if’
3028will tell Octave to treat this as a new ‘if’ statement within another
3029‘if’ statement’s ‘else’ clause.  For example, if you write
3030
3031     if (C1)
3032       BODY-1
3033     else if (C2)
3034       BODY-2
3035     endif
3036
3037Octave will expect additional input to complete the first ‘if’
3038statement.  If you are using Octave interactively, it will continue to
3039prompt you for additional input.  If Octave is reading this input from a
3040file, it may complain about missing or mismatched ‘end’ statements, or,
3041if you have not used the more specific ‘end’ statements (‘endif’,
3042‘endfor’, etc.), it may simply produce incorrect results, without
3043producing any warning messages.
3044
3045   It is much easier to see the error if we rewrite the statements above
3046like this,
3047
3048     if (C1)
3049       BODY-1
3050     else
3051       if (C2)
3052         BODY-2
3053       endif
3054
3055using the indentation to show how Octave groups the statements.  *Note
3056Functions and Scripts::.
3057
3058
3059File: octave.info,  Node: The switch Statement,  Next: The while Statement,  Prev: The if Statement,  Up: Statements
3060
306110.2 The switch Statement
3062=========================
3063
3064It is very common to take different actions depending on the value of
3065one variable.  This is possible using the ‘if’ statement in the
3066following way
3067
3068     if (X == 1)
3069       do_something ();
3070     elseif (X == 2)
3071       do_something_else ();
3072     else
3073       do_something_completely_different ();
3074     endif
3075
3076This kind of code can however be very cumbersome to both write and
3077maintain.  To overcome this problem Octave supports the ‘switch’
3078statement.  Using this statement, the above example becomes
3079
3080     switch (X)
3081       case 1
3082         do_something ();
3083       case 2
3084         do_something_else ();
3085       otherwise
3086         do_something_completely_different ();
3087     endswitch
3088
3089This code makes the repetitive structure of the problem more explicit,
3090making the code easier to read, and hence maintain.  Also, if the
3091variable ‘X’ should change its name, only one line would need changing
3092compared to one line per case when ‘if’ statements are used.
3093
3094   The general form of the ‘switch’ statement is
3095
3096     switch (EXPRESSION)
3097       case LABEL
3098         COMMAND_LIST
3099       case LABEL
3100         COMMAND_LIST
3101       ...
3102
3103       otherwise
3104         COMMAND_LIST
3105     endswitch
3106
3107where LABEL can be any expression.  However, duplicate LABEL values are
3108not detected, and only the COMMAND_LIST corresponding to the first match
3109will be executed.  For the ‘switch’ statement to be meaningful at least
3110one ‘case LABEL COMMAND_LIST’ clause must be present, while the
3111‘otherwise COMMAND_LIST’ clause is optional.
3112
3113   If LABEL is a cell array the corresponding COMMAND_LIST is executed
3114if _any_ of the elements of the cell array match EXPRESSION.  As an
3115example, the following program will print ‘Variable is either 6 or 7’.
3116
3117     A = 7;
3118     switch (A)
3119       case { 6, 7 }
3120         printf ("variable is either 6 or 7\n");
3121       otherwise
3122         printf ("variable is neither 6 nor 7\n");
3123     endswitch
3124
3125   As with all other specific ‘end’ keywords, ‘endswitch’ may be
3126replaced by ‘end’, but you can get better diagnostics if you use the
3127specific forms.
3128
3129   One advantage of using the ‘switch’ statement compared to using ‘if’
3130statements is that the LABELs can be strings.  If an ‘if’ statement is
3131used it is _not_ possible to write
3132
3133     if (X == "a string") # This is NOT valid
3134
3135since a character-to-character comparison between ‘X’ and the string
3136will be made instead of evaluating if the strings are equal.  This
3137special-case is handled by the ‘switch’ statement, and it is possible to
3138write programs that look like this
3139
3140     switch (X)
3141       case "a string"
3142         do_something
3143       ...
3144     endswitch
3145
3146* Menu:
3147
3148* Notes for the C Programmer::
3149
3150
3151File: octave.info,  Node: Notes for the C Programmer,  Up: The switch Statement
3152
315310.2.1 Notes for the C Programmer
3154---------------------------------
3155
3156The ‘switch’ statement is also available in the widely used C
3157programming language.  There are, however, some differences between the
3158statement in Octave and C
3159
3160   • Cases are exclusive, so they don’t ‘fall through’ as do the cases
3161     in the ‘switch’ statement of the C language.
3162
3163   • The COMMAND_LIST elements are not optional.  Making the list
3164     optional would have meant requiring a separator between the label
3165     and the command list.  Otherwise, things like
3166
3167          switch (foo)
3168            case (1) -2
3169            ...
3170
3171     would produce surprising results, as would
3172
3173          switch (foo)
3174            case (1)
3175            case (2)
3176              doit ();
3177            ...
3178
3179     particularly for C programmers.  If ‘doit()’ should be executed if
3180     FOO is either ‘1’ or ‘2’, the above code should be written with a
3181     cell array like this
3182
3183          switch (foo)
3184            case { 1, 2 }
3185              doit ();
3186            ...
3187
3188
3189File: octave.info,  Node: The while Statement,  Next: The do-until Statement,  Prev: The switch Statement,  Up: Statements
3190
319110.3 The while Statement
3192========================
3193
3194In programming, a “loop” means a part of a program that is (or at least
3195can be) executed two or more times in succession.
3196
3197   The ‘while’ statement is the simplest looping statement in Octave.
3198It repeatedly executes a statement as long as a condition is true.  As
3199with the condition in an ‘if’ statement, the condition in a ‘while’
3200statement is considered true if its value is nonzero, and false if its
3201value is zero.  If the value of the conditional expression in a ‘while’
3202statement is a vector or a matrix, it is considered true only if it is
3203non-empty and _all_ of the elements are nonzero.
3204
3205   Octave’s ‘while’ statement looks like this:
3206
3207     while (CONDITION)
3208       BODY
3209     endwhile
3210
3211Here BODY is a statement or list of statements that we call the “body”
3212of the loop, and CONDITION is an expression that controls how long the
3213loop keeps running.
3214
3215   The first thing the ‘while’ statement does is test CONDITION.  If
3216CONDITION is true, it executes the statement BODY.  After BODY has been
3217executed, CONDITION is tested again, and if it is still true, BODY is
3218executed again.  This process repeats until CONDITION is no longer true.
3219If CONDITION is initially false, the body of the loop is never executed.
3220
3221   This example creates a variable ‘fib’ that contains the first ten
3222elements of the Fibonacci sequence.
3223
3224     fib = ones (1, 10);
3225     i = 3;
3226     while (i <= 10)
3227       fib (i) = fib (i-1) + fib (i-2);
3228       i++;
3229     endwhile
3230
3231Here the body of the loop contains two statements.
3232
3233   The loop works like this: first, the value of ‘i’ is set to 3.  Then,
3234the ‘while’ tests whether ‘i’ is less than or equal to 10.  This is the
3235case when ‘i’ equals 3, so the value of the ‘i’-th element of ‘fib’ is
3236set to the sum of the previous two values in the sequence.  Then the
3237‘i++’ increments the value of ‘i’ and the loop repeats.  The loop
3238terminates when ‘i’ reaches 11.
3239
3240   A newline is not required between the condition and the body; but
3241using one makes the program clearer unless the body is very simple.
3242
3243
3244File: octave.info,  Node: The do-until Statement,  Next: The for Statement,  Prev: The while Statement,  Up: Statements
3245
324610.4 The do-until Statement
3247===========================
3248
3249The ‘do-until’ statement is similar to the ‘while’ statement, except
3250that it repeatedly executes a statement until a condition becomes true,
3251and the test of the condition is at the end of the loop, so the body of
3252the loop is always executed at least once.  As with the condition in an
3253‘if’ statement, the condition in a ‘do-until’ statement is considered
3254true if its value is nonzero, and false if its value is zero.  If the
3255value of the conditional expression in a ‘do-until’ statement is a
3256vector or a matrix, it is considered true only if it is non-empty and
3257_all_ of the elements are nonzero.
3258
3259   Octave’s ‘do-until’ statement looks like this:
3260
3261     do
3262       BODY
3263     until (CONDITION)
3264
3265Here BODY is a statement or list of statements that we call the “body”
3266of the loop, and CONDITION is an expression that controls how long the
3267loop keeps running.
3268
3269   This example creates a variable ‘fib’ that contains the first ten
3270elements of the Fibonacci sequence.
3271
3272     fib = ones (1, 10);
3273     i = 2;
3274     do
3275       i++;
3276       fib (i) = fib (i-1) + fib (i-2);
3277     until (i == 10)
3278
3279   A newline is not required between the ‘do’ keyword and the body; but
3280using one makes the program clearer unless the body is very simple.
3281
3282
3283File: octave.info,  Node: The for Statement,  Next: The break Statement,  Prev: The do-until Statement,  Up: Statements
3284
328510.5 The for Statement
3286======================
3287
3288The ‘for’ statement makes it more convenient to count iterations of a
3289loop.  The general form of the ‘for’ statement looks like this:
3290
3291     for VAR = EXPRESSION
3292       BODY
3293     endfor
3294
3295where BODY stands for any statement or list of statements, EXPRESSION is
3296any valid expression, and VAR may take several forms.  Usually it is a
3297simple variable name or an indexed variable.  If the value of EXPRESSION
3298is a structure, VAR may also be a vector with two elements.  *Note
3299Looping Over Structure Elements::, below.
3300
3301   The assignment expression in the ‘for’ statement works a bit
3302differently than Octave’s normal assignment statement.  Instead of
3303assigning the complete result of the expression, it assigns each column
3304of the expression to VAR in turn.  If EXPRESSION is a range, a row
3305vector, or a scalar, the value of VAR will be a scalar each time the
3306loop body is executed.  If VAR is a column vector or a matrix, VAR will
3307be a column vector each time the loop body is executed.
3308
3309   The following example shows another way to create a vector containing
3310the first ten elements of the Fibonacci sequence, this time using the
3311‘for’ statement:
3312
3313     fib = ones (1, 10);
3314     for i = 3:10
3315       fib(i) = fib(i-1) + fib(i-2);
3316     endfor
3317
3318This code works by first evaluating the expression ‘3:10’, to produce a
3319range of values from 3 to 10 inclusive.  Then the variable ‘i’ is
3320assigned the first element of the range and the body of the loop is
3321executed once.  When the end of the loop body is reached, the next value
3322in the range is assigned to the variable ‘i’, and the loop body is
3323executed again.  This process continues until there are no more elements
3324to assign.
3325
3326   Within Octave is it also possible to iterate over matrices or cell
3327arrays using the ‘for’ statement.  For example consider
3328
3329     disp ("Loop over a matrix")
3330     for i = [1,3;2,4]
3331       i
3332     endfor
3333     disp ("Loop over a cell array")
3334     for i = {1,"two";"three",4}
3335       i
3336     endfor
3337
3338In this case the variable ‘i’ takes on the value of the columns of the
3339matrix or cell matrix.  So the first loop iterates twice, producing two
3340column vectors ‘[1;2]’, followed by ‘[3;4]’, and likewise for the loop
3341over the cell array.  This can be extended to loops over
3342multi-dimensional arrays.  For example:
3343
3344     a = [1,3;2,4]; c = cat (3, a, 2*a);
3345     for i = c
3346       i
3347     endfor
3348
3349In the above case, the multi-dimensional matrix C is reshaped to a
3350two-dimensional matrix as ‘reshape (c, rows (c), prod (size
3351(c)(2:end)))’ and then the same behavior as a loop over a
3352two-dimensional matrix is produced.
3353
3354   Although it is possible to rewrite all ‘for’ loops as ‘while’ loops,
3355the Octave language has both statements because often a ‘for’ loop is
3356both less work to type and more natural to think of.  Counting the
3357number of iterations is very common in loops and it can be easier to
3358think of this counting as part of looping rather than as something to do
3359inside the loop.
3360
3361* Menu:
3362
3363* Looping Over Structure Elements::
3364
3365
3366File: octave.info,  Node: Looping Over Structure Elements,  Up: The for Statement
3367
336810.5.1 Looping Over Structure Elements
3369--------------------------------------
3370
3371A special form of the ‘for’ statement allows you to loop over all the
3372elements of a structure:
3373
3374     for [ VAL, KEY ] = EXPRESSION
3375       BODY
3376     endfor
3377
3378In this form of the ‘for’ statement, the value of EXPRESSION must be a
3379structure.  If it is, KEY and VAL are set to the name of the element and
3380the corresponding value in turn, until there are no more elements.  For
3381example:
3382
3383     x.a = 1
3384     x.b = [1, 2; 3, 4]
3385     x.c = "string"
3386     for [val, key] = x
3387       key
3388       val
3389     endfor
3390
3391          ⊣ key = a
3392          ⊣ val = 1
3393          ⊣ key = b
3394          ⊣ val =
33953396          ⊣   1  2
3397          ⊣   3  4
33983399          ⊣ key = c
3400          ⊣ val = string
3401
3402   The elements are not accessed in any particular order.  If you need
3403to cycle through the list in a particular way, you will have to use the
3404function ‘fieldnames’ and sort the list yourself.
3405
3406
3407File: octave.info,  Node: The break Statement,  Next: The continue Statement,  Prev: The for Statement,  Up: Statements
3408
340910.6 The break Statement
3410========================
3411
3412The ‘break’ statement jumps out of the innermost ‘while’, ‘do-until’, or
3413‘for’ loop that encloses it.  The ‘break’ statement may only be used
3414within the body of a loop.  The following example finds the smallest
3415divisor of a given integer, and also identifies prime numbers:
3416
3417     num = 103;
3418     div = 2;
3419     while (div*div <= num)
3420       if (rem (num, div) == 0)
3421         break;
3422       endif
3423       div++;
3424     endwhile
3425     if (rem (num, div) == 0)
3426       printf ("Smallest divisor of %d is %d\n", num, div)
3427     else
3428       printf ("%d is prime\n", num);
3429     endif
3430
3431   When the remainder is zero in the first ‘while’ statement, Octave
3432immediately “breaks out” of the loop.  This means that Octave proceeds
3433immediately to the statement following the loop and continues
3434processing.  (This is very different from the ‘exit’ statement which
3435stops the entire Octave program.)
3436
3437   Here is another program equivalent to the previous one.  It
3438illustrates how the CONDITION of a ‘while’ statement could just as well
3439be replaced with a ‘break’ inside an ‘if’:
3440
3441     num = 103;
3442     div = 2;
3443     while (1)
3444       if (rem (num, div) == 0)
3445         printf ("Smallest divisor of %d is %d\n", num, div);
3446         break;
3447       endif
3448       div++;
3449       if (div*div > num)
3450         printf ("%d is prime\n", num);
3451         break;
3452       endif
3453     endwhile
3454
3455
3456File: octave.info,  Node: The continue Statement,  Next: The unwind_protect Statement,  Prev: The break Statement,  Up: Statements
3457
345810.7 The continue Statement
3459===========================
3460
3461The ‘continue’ statement, like ‘break’, is used only inside ‘while’,
3462‘do-until’, or ‘for’ loops.  It skips over the rest of the loop body,
3463causing the next cycle around the loop to begin immediately.  Contrast
3464this with ‘break’, which jumps out of the loop altogether.  Here is an
3465example:
3466
3467     # print elements of a vector of random
3468     # integers that are even.
3469
3470     # first, create a row vector of 10 random
3471     # integers with values between 0 and 100:
3472
3473     vec = round (rand (1, 10) * 100);
3474
3475     # print what we're interested in:
3476
3477     for x = vec
3478       if (rem (x, 2) != 0)
3479         continue;
3480       endif
3481       printf ("%d\n", x);
3482     endfor
3483
3484   If one of the elements of VEC is an odd number, this example skips
3485the print statement for that element, and continues back to the first
3486statement in the loop.
3487
3488   This is not a practical example of the ‘continue’ statement, but it
3489should give you a clear understanding of how it works.  Normally, one
3490would probably write the loop like this:
3491
3492     for x = vec
3493       if (rem (x, 2) == 0)
3494         printf ("%d\n", x);
3495       endif
3496     endfor
3497
3498
3499File: octave.info,  Node: The unwind_protect Statement,  Next: The try Statement,  Prev: The continue Statement,  Up: Statements
3500
350110.8 The unwind_protect Statement
3502=================================
3503
3504Octave supports a limited form of exception handling modeled after the
3505unwind-protect form of Lisp.
3506
3507   The general form of an ‘unwind_protect’ block looks like this:
3508
3509     unwind_protect
3510       BODY
3511     unwind_protect_cleanup
3512       CLEANUP
3513     end_unwind_protect
3514
3515where BODY and CLEANUP are both optional and may contain any Octave
3516expressions or commands.  The statements in CLEANUP are guaranteed to be
3517executed regardless of how control exits BODY.
3518
3519   This is useful to protect temporary changes to global variables from
3520possible errors.  For example, the following code will always restore
3521the original value of the global variable ‘frobnosticate’ even if an
3522error occurs in the first part of the ‘unwind_protect’ block.
3523
3524     save_frobnosticate = frobnosticate;
3525     unwind_protect
3526       frobnosticate = true;
3527       ...
3528     unwind_protect_cleanup
3529       frobnosticate = save_frobnosticate;
3530     end_unwind_protect
3531
3532Without ‘unwind_protect’, the value of FROBNOSTICATE would not be
3533restored if an error occurs while evaluating the first part of the
3534‘unwind_protect’ block because evaluation would stop at the point of the
3535error and the statement to restore the value would not be executed.
3536
3537   In addition to unwind_protect, Octave supports another form of
3538exception handling, the ‘try’ block.
3539
3540
3541File: octave.info,  Node: The try Statement,  Next: Continuation Lines,  Prev: The unwind_protect Statement,  Up: Statements
3542
354310.9 The try Statement
3544======================
3545
3546The original form of a ‘try’ block looks like this:
3547
3548     try
3549       BODY
3550     catch
3551       CLEANUP
3552     end_try_catch
3553
3554where BODY and CLEANUP are both optional and may contain any Octave
3555expressions or commands.  The statements in CLEANUP are only executed if
3556an error occurs in BODY.
3557
3558   No warnings or error messages are printed while BODY is executing.
3559If an error does occur during the execution of BODY, CLEANUP can use the
3560functions ‘lasterr’ or ‘lasterror’ to access the text of the message
3561that would have been printed, as well as its identifier.  The
3562alternative form,
3563
3564     try
3565       BODY
3566     catch ERR
3567       CLEANUP
3568     end_try_catch
3569
3570will automatically store the output of ‘lasterror’ in the structure ERR.
3571*Note Errors and Warnings::, for more information about the ‘lasterr’
3572and ‘lasterror’ functions.
3573
3574
3575File: octave.info,  Node: Continuation Lines,  Prev: The try Statement,  Up: Statements
3576
357710.10 Continuation Lines
3578========================
3579
3580In the Octave language, most statements end with a newline character and
3581you must tell Octave to ignore the newline character in order to
3582continue a statement from one line to the next.  Lines that end with the
3583characters ‘...’ are joined with the following line before they are
3584divided into tokens by Octave’s parser.  For example, the lines
3585
3586     x = long_variable_name ...
3587         + longer_variable_name ...
3588         - 42
3589
3590form a single statement.
3591
3592   Any text between the continuation marker and the newline character is
3593ignored.  For example, the statement
3594
3595     x = long_variable_name ...    # comment one
3596         + longer_variable_name ...comment two
3597         - 42                      # last comment
3598
3599is equivalent to the one shown above.
3600
3601   Inside double-quoted string constants, the character ‘\’ has to be
3602used as continuation marker.  The ‘\’ must appear at the end of the line
3603just before the newline character:
3604
3605     s = "This text starts in the first line \
3606     and is continued in the second line."
3607
3608Input that occurs inside parentheses can be continued to the next line
3609without having to use a continuation marker.  For example, it is
3610possible to write statements like
3611
3612     if (fine_dining_destination == on_a_boat
3613         || fine_dining_destination == on_a_train)
3614       seuss (i, will, not, eat, them, sam, i, am, i,
3615              will, not, eat, green, eggs, and, ham);
3616     endif
3617
3618without having to add to the clutter with continuation markers.
3619
3620
3621File: octave.info,  Node: Functions and Scripts,  Next: Errors and Warnings,  Prev: Statements,  Up: Top
3622
362311 Functions and Scripts
3624************************
3625
3626Complicated Octave programs can often be simplified by defining
3627functions.  Functions can be defined directly on the command line during
3628interactive Octave sessions, or in external files, and can be called
3629just like built-in functions.
3630
3631* Menu:
3632
3633* Introduction to Function and Script Files::
3634* Defining Functions::
3635* Returning from a Function::
3636* Multiple Return Values::
3637* Variable-length Return Lists::
3638* Variable-length Argument Lists::
3639* Ignoring Arguments::
3640* Default Arguments::
3641* Validating Arguments::
3642* Function Files::
3643* Script Files::
3644* Function Handles and Anonymous Functions::
3645* Command Syntax and Function Syntax::
3646* Organization of Functions::
3647
3648
3649File: octave.info,  Node: Introduction to Function and Script Files,  Next: Defining Functions,  Up: Functions and Scripts
3650
365111.1 Introduction to Function and Script Files
3652==============================================
3653
3654There are seven different things covered in this section.
3655  1. Typing in a function at the command prompt.
3656
3657  2. Storing a group of commands in a file — called a script file.
3658
3659  3. Storing a function in a file—called a function file.
3660
3661  4. Subfunctions in function files.
3662
3663  5. Multiple functions in one script file.
3664
3665  6. Private functions.
3666
3667  7. Nested functions.
3668
3669   Both function files and script files end with an extension of .m, for
3670MATLAB compatibility.  If you want more than one independent functions
3671in a file, it must be a script file (*note Script Files::), and to use
3672these functions you must execute the script file before you can use the
3673functions that are in the script file.
3674
3675
3676File: octave.info,  Node: Defining Functions,  Next: Returning from a Function,  Prev: Introduction to Function and Script Files,  Up: Functions and Scripts
3677
367811.2 Defining Functions
3679=======================
3680
3681In its simplest form, the definition of a function named NAME looks like
3682this:
3683
3684     function NAME
3685       BODY
3686     endfunction
3687
3688A valid function name is like a valid variable name: a sequence of
3689letters, digits and underscores, not starting with a digit.  Functions
3690share the same pool of names as variables.
3691
3692   The function BODY consists of Octave statements.  It is the most
3693important part of the definition, because it says what the function
3694should actually _do_.
3695
3696   For example, here is a function that, when executed, will ring the
3697bell on your terminal (assuming that it is possible to do so):
3698
3699     function wakeup
3700       printf ("\a");
3701     endfunction
3702
3703   The ‘printf’ statement (*note Input and Output::) simply tells Octave
3704to print the string "\a".  The special character ‘\a’ stands for the
3705alert character (ASCII 7).  *Note Strings::.
3706
3707   Once this function is defined, you can ask Octave to evaluate it by
3708typing the name of the function.
3709
3710   Normally, you will want to pass some information to the functions you
3711define.  The syntax for passing parameters to a function in Octave is
3712
3713     function NAME (ARG-LIST)
3714       BODY
3715     endfunction
3716
3717where ARG-LIST is a comma-separated list of the function’s arguments.
3718When the function is called, the argument names are used to hold the
3719argument values given in the call.  The list of arguments may be empty,
3720in which case this form is equivalent to the one shown above.
3721
3722   To print a message along with ringing the bell, you might modify the
3723‘wakeup’ to look like this:
3724
3725     function wakeup (message)
3726       printf ("\a%s\n", message);
3727     endfunction
3728
3729   Calling this function using a statement like this
3730
3731     wakeup ("Rise and shine!");
3732
3733will cause Octave to ring your terminal’s bell and print the message
3734‘Rise and shine!’, followed by a newline character (the ‘\n’ in the
3735first argument to the ‘printf’ statement).
3736
3737   In most cases, you will also want to get some information back from
3738the functions you define.  Here is the syntax for writing a function
3739that returns a single value:
3740
3741     function RET-VAR = NAME (ARG-LIST)
3742       BODY
3743     endfunction
3744
3745The symbol RET-VAR is the name of the variable that will hold the value
3746to be returned by the function.  This variable must be defined before
3747the end of the function body in order for the function to return a
3748value.
3749
3750   Variables used in the body of a function are local to the function.
3751Variables named in ARG-LIST and RET-VAR are also local to the function.
3752*Note Global Variables::, for information about how to access global
3753variables inside a function.
3754
3755   For example, here is a function that computes the average of the
3756elements of a vector:
3757
3758     function retval = avg (v)
3759       retval = sum (v) / length (v);
3760     endfunction
3761
3762   If we had written ‘avg’ like this instead,
3763
3764     function retval = avg (v)
3765       if (isvector (v))
3766         retval = sum (v) / length (v);
3767       endif
3768     endfunction
3769
3770and then called the function with a matrix instead of a vector as the
3771argument, Octave would have printed an error message like this:
3772
3773     error: value on right hand side of assignment is undefined
3774
3775because the body of the ‘if’ statement was never executed, and ‘retval’
3776was never defined.  To prevent obscure errors like this, it is a good
3777idea to always make sure that the return variables will always have
3778values, and to produce meaningful error messages when problems are
3779encountered.  For example, ‘avg’ could have been written like this:
3780
3781     function retval = avg (v)
3782       retval = 0;
3783       if (isvector (v))
3784         retval = sum (v) / length (v);
3785       else
3786         error ("avg: expecting vector argument");
3787       endif
3788     endfunction
3789
3790   There is still one additional problem with this function.  What if it
3791is called without an argument?  Without additional error checking,
3792Octave will probably print an error message that won’t really help you
3793track down the source of the error.  To allow you to catch errors like
3794this, Octave provides each function with an automatic variable called
3795‘nargin’.  Each time a function is called, ‘nargin’ is automatically
3796initialized to the number of arguments that have actually been passed to
3797the function.  For example, we might rewrite the ‘avg’ function like
3798this:
3799
3800     function retval = avg (v)
3801       retval = 0;
3802       if (nargin != 1)
3803         usage ("avg (vector)");
3804       endif
3805       if (isvector (v))
3806         retval = sum (v) / length (v);
3807       else
3808         error ("avg: expecting vector argument");
3809       endif
3810     endfunction
3811
3812   Although Octave does not automatically report an error if you call a
3813function with more arguments than expected, doing so probably indicates
3814that something is wrong.  Octave also does not automatically report an
3815error if a function is called with too few arguments, but any attempt to
3816use a variable that has not been given a value will result in an error.
3817To avoid such problems and to provide useful messages, we check for both
3818possibilities and issue our own error message.
3819
3820 -- : nargin ()
3821 -- : nargin (FCN)
3822     Report the number of input arguments to a function.
3823
3824     Called from within a function, return the number of arguments
3825     passed to the function.  At the top level, return the number of
3826     command line arguments passed to Octave.
3827
3828     If called with the optional argument FCN—a function name or
3829     handle—return the declared number of arguments that the function
3830     can accept.
3831
3832     If the last argument to FCN is VARARGIN the returned value is
3833     negative.  For example, the function ‘union’ for sets is declared
3834     as
3835
3836          function [y, ia, ib] = union (a, b, varargin)
3837
3838          and
3839
3840          nargin ("union")
3841          ⇒ -3
3842
3843     Programming Note: ‘nargin’ does not work on compiled functions
3844     (‘.oct’ files) such as built-in or dynamically loaded functions.
3845
3846     See also: *note nargout: XREFnargout, *note narginchk:
3847     XREFnarginchk, *note varargin: XREFvarargin, *note inputname:
3848     XREFinputname.
3849
3850 -- : inputname (N)
3851 -- : inputname (N, IDS_ONLY)
3852     Return the name of the N-th argument to the calling function.
3853
3854     If the argument is not a simple variable name, return an empty
3855     string.  As an example, a reference to a field in a structure such
3856     as ‘s.field’ is not a simple name and will return "".
3857
3858     ‘inputname’ is only useful within a function.  When used at the
3859     command line it always returns an empty string.
3860
3861     By default, return an empty string if the N-th argument is not a
3862     valid variable name.  If the optional argument IDS_ONLY is false,
3863     return the text of the argument even if it is not a valid variable
3864     name.
3865
3866     See also: *note nargin: XREFnargin, *note nthargout: XREFnthargout.
3867
3868 -- : VAL = silent_functions ()
3869 -- : OLD_VAL = silent_functions (NEW_VAL)
3870 -- : silent_functions (NEW_VAL, "local")
3871     Query or set the internal variable that controls whether internal
3872     output from a function is suppressed.
3873
3874     If this option is disabled, Octave will display the results
3875     produced by evaluating expressions within a function body that are
3876     not terminated with a semicolon.
3877
3878     When called from inside a function with the "local" option, the
3879     variable is changed locally for the function and any subroutines it
3880     calls.  The original variable value is restored when exiting the
3881     function.
3882
3883
3884File: octave.info,  Node: Returning from a Function,  Next: Multiple Return Values,  Prev: Defining Functions,  Up: Functions and Scripts
3885
388611.3 Returning from a Function
3887==============================
3888
3889The body of a user-defined function can contain a ‘return’ statement.
3890This statement returns control to the rest of the Octave program.  It
3891looks like this:
3892
3893     return
3894
3895   Unlike the ‘return’ statement in C, Octave’s ‘return’ statement
3896cannot be used to return a value from a function.  Instead, you must
3897assign values to the list of return variables that are part of the
3898‘function’ statement.  The ‘return’ statement simply makes it easier to
3899exit a function from a deeply nested loop or conditional statement.
3900
3901   Here is an example of a function that checks to see if any elements
3902of a vector are nonzero.
3903
3904     function retval = any_nonzero (v)
3905       retval = 0;
3906       for i = 1:length (v)
3907         if (v (i) != 0)
3908           retval = 1;
3909           return;
3910         endif
3911       endfor
3912       printf ("no nonzero elements found\n");
3913     endfunction
3914
3915   Note that this function could not have been written using the ‘break’
3916statement to exit the loop once a nonzero value is found without adding
3917extra logic to avoid printing the message if the vector does contain a
3918nonzero element.
3919
3920 -- : return
3921     When Octave encounters the keyword ‘return’ inside a function or
3922     script, it returns control to the caller immediately.  At the top
3923     level, the return statement is ignored.  A ‘return’ statement is
3924     assumed at the end of every function definition.
3925
3926
3927File: octave.info,  Node: Multiple Return Values,  Next: Variable-length Return Lists,  Prev: Returning from a Function,  Up: Functions and Scripts
3928
392911.4 Multiple Return Values
3930===========================
3931
3932Unlike many other computer languages, Octave allows you to define
3933functions that return more than one value.  The syntax for defining
3934functions that return multiple values is
3935
3936     function [RET-LIST] = NAME (ARG-LIST)
3937       BODY
3938     endfunction
3939
3940where NAME, ARG-LIST, and BODY have the same meaning as before, and
3941RET-LIST is a comma-separated list of variable names that will hold the
3942values returned from the function.  The list of return values must have
3943at least one element.  If RET-LIST has only one element, this form of
3944the ‘function’ statement is equivalent to the form described in the
3945previous section.
3946
3947   Here is an example of a function that returns two values, the maximum
3948element of a vector and the index of its first occurrence in the vector.
3949
3950     function [max, idx] = vmax (v)
3951       idx = 1;
3952       max = v (idx);
3953       for i = 2:length (v)
3954         if (v (i) > max)
3955           max = v (i);
3956           idx = i;
3957         endif
3958       endfor
3959     endfunction
3960
3961   In this particular case, the two values could have been returned as
3962elements of a single array, but that is not always possible or
3963convenient.  The values to be returned may not have compatible
3964dimensions, and it is often desirable to give the individual return
3965values distinct names.
3966
3967   It is possible to use the ‘nthargout’ function to obtain only some of
3968the return values or several at once in a cell array.  *Note Cell Array
3969Objects::.
3970
3971 -- : nthargout (N, FUNC, ...)
3972 -- : nthargout (N, NTOT, FUNC, ...)
3973     Return the Nth output argument of the function specified by the
3974     function handle or string FUNC.
3975
3976     Any additional arguments are passed directly to FUNC.  The total
3977     number of arguments to call FUNC with can be passed in NTOT; by
3978     default NTOT is N.  The input N can also be a vector of indices of
3979     the output, in which case the output will be a cell array of the
3980     requested output arguments.
3981
3982     The intended use ‘nthargout’ is to avoid intermediate variables.
3983     For example, when finding the indices of the maximum entry of a
3984     matrix, the following two compositions of nthargout
3985
3986          M = magic (5);
3987          cell2mat (nthargout ([1, 2], @ind2sub, size (M),
3988                               nthargout (2, @max, M(:))))
3989          ⇒ 5   3
3990
3991     are completely equivalent to the following lines:
3992
3993          M = magic (5);
3994          [~, idx] = max (M(:));
3995          [i, j] = ind2sub (size (M), idx);
3996          [i, j]
3997          ⇒ 5   3
3998
3999     It can also be helpful to have all output arguments in a single
4000     cell in the following manner:
4001
4002          USV = nthargout ([1:3], @svd, hilb (5));
4003
4004     See also: *note nargin: XREFnargin, *note nargout: XREFnargout,
4005     *note varargin: XREFvarargin, *note varargout: XREFvarargout, *note
4006     isargout: XREFisargout.
4007
4008   In addition to setting ‘nargin’ each time a function is called,
4009Octave also automatically initializes ‘nargout’ to the number of values
4010that are expected to be returned.  This allows you to write functions
4011that behave differently depending on the number of values that the user
4012of the function has requested.  The implicit assignment to the built-in
4013variable ‘ans’ does not figure in the count of output arguments, so the
4014value of ‘nargout’ may be zero.
4015
4016   The ‘svd’ and ‘lu’ functions are examples of built-in functions that
4017behave differently depending on the value of ‘nargout’.
4018
4019   It is possible to write functions that only set some return values.
4020For example, calling the function
4021
4022     function [x, y, z] = f ()
4023       x = 1;
4024       z = 2;
4025     endfunction
4026
4027as
4028
4029     [a, b, c] = f ()
4030
4031produces:
4032
4033     a = 1
4034
4035     b = [](0x0)
4036
4037     c = 2
4038
4039along with a warning.
4040
4041 -- : nargout ()
4042 -- : nargout (FCN)
4043     Report the number of output arguments from a function.
4044
4045     Called from within a function, return the number of values the
4046     caller expects to receive.  At the top level, ‘nargout’ with no
4047     argument is undefined and will produce an error.
4048
4049     If called with the optional argument FCN—a function name or
4050     handle—return the number of declared output values that the
4051     function can produce.
4052
4053     If the final output argument is VARARGOUT the returned value is
4054     negative.
4055
4056     For example,
4057
4058          f ()
4059
4060     will cause ‘nargout’ to return 0 inside the function ‘f’ and
4061
4062          [s, t] = f ()
4063
4064     will cause ‘nargout’ to return 2 inside the function ‘f’.
4065
4066     In the second usage,
4067
4068          nargout (@histc)   # or nargout ("histc") using a string input
4069
4070     will return 2, because ‘histc’ has two outputs, whereas
4071
4072          nargout (@imread)
4073
4074     will return -2, because ‘imread’ has two outputs and the second is
4075     VARARGOUT.
4076
4077     Programming Note.  ‘nargout’ does not work for built-in functions
4078     and returns -1 for all anonymous functions.
4079
4080     See also: *note nargin: XREFnargin, *note varargout: XREFvarargout,
4081     *note isargout: XREFisargout, *note nthargout: XREFnthargout.
4082
4083
4084File: octave.info,  Node: Variable-length Return Lists,  Next: Variable-length Argument Lists,  Prev: Multiple Return Values,  Up: Functions and Scripts
4085
408611.5 Variable-length Return Lists
4087=================================
4088
4089It is possible to return a variable number of output arguments from a
4090function using a syntax that’s similar to the one used with the special
4091‘varargin’ parameter name.  To let a function return a variable number
4092of output arguments the special output parameter name ‘varargout’ is
4093used.  As with ‘varargin’, ‘varargout’ is a cell array that will contain
4094the requested output arguments.
4095
4096   As an example the following function sets the first output argument
4097to 1, the second to 2, and so on.
4098
4099     function varargout = one_to_n ()
4100       for i = 1:nargout
4101         varargout{i} = i;
4102       endfor
4103     endfunction
4104
4105When called this function returns values like this
4106
4107     [a, b, c] = one_to_n ()
4108          ⇒ a =  1
4109          ⇒ b =  2
4110          ⇒ c =  3
4111
4112   If ‘varargin’ (‘varargout’) does not appear as the last element of
4113the input (output) parameter list, then it is not special, and is
4114handled the same as any other parameter name.
4115
4116 -- : [R1, R2, ..., RN] = deal (A)
4117 -- : [R1, R2, ..., RN] = deal (A1, A2, ..., AN)
4118
4119     Copy the input parameters into the corresponding output parameters.
4120
4121     If only a single input parameter is supplied, its value is copied
4122     to each of the outputs.
4123
4124     For example,
4125
4126          [a, b, c] = deal (x, y, z);
4127
4128     is equivalent to
4129
4130          a = x;
4131          b = y;
4132          c = z;
4133
4134     and
4135
4136          [a, b, c] = deal (x);
4137
4138     is equivalent to
4139
4140          a = b = c = x;
4141
4142     Programming Note: ‘deal’ is often used with comma separated lists
4143     derived from cell arrays or structures.  This is unnecessary as the
4144     interpreter can perform the same action without the overhead of a
4145     function call.  For example:
4146
4147          c = {[1 2], "Three", 4};
4148          [x, y, z] = c{:}
41494150             x =
4151
4152                1   2
4153
4154             y = Three
4155             z =  4
4156
4157     See also: *note cell2struct: XREFcell2struct, *note struct2cell:
4158     XREFstruct2cell, *note repmat: XREFrepmat.
4159
4160
4161File: octave.info,  Node: Variable-length Argument Lists,  Next: Ignoring Arguments,  Prev: Variable-length Return Lists,  Up: Functions and Scripts
4162
416311.6 Variable-length Argument Lists
4164===================================
4165
4166Sometimes the number of input arguments is not known when the function
4167is defined.  As an example think of a function that returns the smallest
4168of all its input arguments.  For example:
4169
4170     a = smallest (1, 2, 3);
4171     b = smallest (1, 2, 3, 4);
4172
4173In this example both ‘a’ and ‘b’ would be 1.  One way to write the
4174‘smallest’ function is
4175
4176     function val = smallest (arg1, arg2, arg3, arg4, arg5)
4177       BODY
4178     endfunction
4179
4180and then use the value of ‘nargin’ to determine which of the input
4181arguments should be considered.  The problem with this approach is that
4182it can only handle a limited number of input arguments.
4183
4184   If the special parameter name ‘varargin’ appears at the end of a
4185function parameter list it indicates that the function takes a variable
4186number of input arguments.  Using ‘varargin’ the function looks like
4187this
4188
4189     function val = smallest (varargin)
4190       BODY
4191     endfunction
4192
4193In the function body the input arguments can be accessed through the
4194variable ‘varargin’.  This variable is a cell array containing all the
4195input arguments.  *Note Cell Arrays::, for details on working with cell
4196arrays.  The ‘smallest’ function can now be defined like this
4197
4198     function val = smallest (varargin)
4199       val = min ([varargin{:}]);
4200     endfunction
4201
4202This implementation handles any number of input arguments, but it’s also
4203a very simple solution to the problem.
4204
4205   A slightly more complex example of ‘varargin’ is a function
4206‘print_arguments’ that prints all input arguments.  Such a function can
4207be defined like this
4208
4209     function print_arguments (varargin)
4210       for i = 1:length (varargin)
4211         printf ("Input argument %d: ", i);
4212         disp (varargin{i});
4213       endfor
4214     endfunction
4215
4216This function produces output like this
4217
4218     print_arguments (1, "two", 3);
4219          ⊣ Input argument 1:  1
4220          ⊣ Input argument 2: two
4221          ⊣ Input argument 3:  3
4222
4223 -- : [REG, PROP] = parseparams (PARAMS)
4224 -- : [REG, VAR1, ...] = parseparams (PARAMS, NAME1, DEFAULT1, ...)
4225     Return in REG the cell elements of PARAM up to the first string
4226     element and in PROP all remaining elements beginning with the first
4227     string element.
4228
4229     For example:
4230
4231          [reg, prop] = parseparams ({1, 2, "linewidth", 10})
4232          reg =
4233          {
4234            [1,1] = 1
4235            [1,2] = 2
4236          }
4237          prop =
4238          {
4239            [1,1] = linewidth
4240            [1,2] = 10
4241          }
4242
4243     The parseparams function may be used to separate regular numeric
4244     arguments from additional arguments given as property/value pairs
4245     of the VARARGIN cell array.
4246
4247     In the second form of the call, available options are specified
4248     directly with their default values given as name-value pairs.  If
4249     PARAMS do not form name-value pairs, or if an option occurs that
4250     does not match any of the available options, an error occurs.
4251
4252     When called from an m-file function, the error is prefixed with the
4253     name of the caller function.
4254
4255     The matching of options is case-insensitive.
4256
4257     See also: *note varargin: XREFvarargin, *note inputParser:
4258     XREFinputParser.
4259
4260
4261File: octave.info,  Node: Ignoring Arguments,  Next: Default Arguments,  Prev: Variable-length Argument Lists,  Up: Functions and Scripts
4262
426311.7 Ignoring Arguments
4264=======================
4265
4266In the formal argument list, it is possible to use the dummy placeholder
4267‘~’ instead of a name.  This indicates that the corresponding argument
4268value should be ignored and not stored to any variable.
4269
4270     function val = pick2nd (~, arg2)
4271       val = arg2;
4272     endfunction
4273
4274   The value of ‘nargin’ is not affected by using this declaration.
4275
4276   Return arguments can also be ignored using the same syntax.  For
4277example, the sort function returns both the sorted values, and an index
4278vector for the original input which will result in a sorted output.
4279Ignoring the second output is simple—don’t request more than one output.
4280But ignoring the first, and calculating just the second output, requires
4281the use of the ‘~’ placeholder.
4282
4283     x = [2, 3, 1];
4284     [s, i] = sort (x)
42854286     s =
4287
4288        1   2   3
4289
4290     i =
4291
4292        3   1   2
4293
4294     [~, i] = sort (x)
42954296     i =
4297
4298        3   1   2
4299
4300   When using the ‘~’ placeholder, commas—not whitespace—must be used to
4301separate output arguments.  Otherwise, the interpreter will view ‘~’ as
4302the logical not operator.
4303
4304     [~ i] = sort (x)
4305     parse error:
4306
4307       invalid left hand side of assignment
4308
4309   Functions may take advantage of ignored outputs to reduce the number
4310of calculations performed.  To do so, use the ‘isargout’ function to
4311query whether the output argument is wanted.  For example:
4312
4313     function [out1, out2] = long_function (x, y, z)
4314       if (isargout (1))
4315         ## Long calculation
4316         ...
4317         out1 = result;
4318       endif
4319       ...
4320     endfunction
4321
4322 -- : isargout (K)
4323     Within a function, return a logical value indicating whether the
4324     argument K will be assigned to a variable on output.
4325
4326     If the result is false, the argument has been ignored during the
4327     function call through the use of the tilde (~) special output
4328     argument.  Functions can use ‘isargout’ to avoid performing
4329     unnecessary calculations for outputs which are unwanted.
4330
4331     If K is outside the range ‘1:max (nargout)’, the function returns
4332     false.  K can also be an array, in which case the function works
4333     element-by-element and a logical array is returned.  At the top
4334     level, ‘isargout’ returns an error.
4335
4336     See also: *note nargout: XREFnargout, *note varargout:
4337     XREFvarargout, *note nthargout: XREFnthargout.
4338
4339
4340File: octave.info,  Node: Default Arguments,  Next: Validating Arguments,  Prev: Ignoring Arguments,  Up: Functions and Scripts
4341
434211.8 Default Arguments
4343======================
4344
4345Since Octave supports variable number of input arguments, it is very
4346useful to assign default values to some input arguments.  When an input
4347argument is declared in the argument list it is possible to assign a
4348default value to the argument like this
4349
4350     function NAME (ARG1 = VAL1, ...)
4351       BODY
4352     endfunction
4353
4354If no value is assigned to ARG1 by the user, it will have the value
4355VAL1.
4356
4357   As an example, the following function implements a variant of the
4358classic “Hello, World” program.
4359
4360     function hello (who = "World")
4361       printf ("Hello, %s!\n", who);
4362     endfunction
4363
4364When called without an input argument the function prints the following
4365
4366     hello ();
4367          ⊣ Hello, World!
4368
4369and when it’s called with an input argument it prints the following
4370
4371     hello ("Beautiful World of Free Software");
4372          ⊣ Hello, Beautiful World of Free Software!
4373
4374   Sometimes it is useful to explicitly tell Octave to use the default
4375value of an input argument.  This can be done writing a ‘:’ as the value
4376of the input argument when calling the function.
4377
4378     hello (:);
4379          ⊣ Hello, World!
4380
4381
4382File: octave.info,  Node: Validating Arguments,  Next: Function Files,  Prev: Default Arguments,  Up: Functions and Scripts
4383
438411.9 Validating Arguments
4385=========================
4386
4387Octave is a weakly typed programming language.  Thus it is possible to
4388call a function with arguments, that probably cause errors or might have
4389undesirable side effects.  For example calling a string processing
4390function with a huge sparse matrix.
4391
4392   It is good practice at the head of a function to verify that it has
4393been called correctly.  Octave offers several functions for this
4394purpose.
4395
4396* Menu:
4397
4398* Validating the number of Arguments::
4399* Validating the type of Arguments::
4400* Parsing Arguments::
4401
4402
4403File: octave.info,  Node: Validating the number of Arguments,  Next: Validating the type of Arguments,  Up: Validating Arguments
4404
440511.9.1 Validating the number of Arguments
4406-----------------------------------------
4407
4408In Octave the following idiom is seen frequently at the beginning of a
4409function definition:
4410
4411     if (nargin < min_#_inputs || nargin > max_#_inputs)
4412       print_usage ();
4413     endif
4414
4415which stops the function execution and prints a message about the
4416correct way to call the function whenever the number of inputs is wrong.
4417
4418   Similar error checking is provided by ‘narginchk’ and ‘nargoutchk’.
4419
4420 -- : narginchk (MINARGS, MAXARGS)
4421     Check for correct number of input arguments.
4422
4423     Generate an error message if the number of arguments in the calling
4424     function is outside the range MINARGS and MAXARGS.  Otherwise, do
4425     nothing.
4426
4427     Both MINARGS and MAXARGS must be scalar numeric values.  Zero, Inf,
4428     and negative values are all allowed, and MINARGS and MAXARGS may be
4429     equal.
4430
4431     Note that this function evaluates ‘nargin’ on the caller.
4432
4433     See also: *note nargoutchk: XREFnargoutchk, *note error: XREFerror,
4434     *note nargout: XREFnargout, *note nargin: XREFnargin.
4435
4436 -- : nargoutchk (MINARGS, MAXARGS)
4437 -- : MSGSTR = nargoutchk (MINARGS, MAXARGS, NARGS)
4438 -- : MSGSTR = nargoutchk (MINARGS, MAXARGS, NARGS, "string")
4439 -- : MSGSTRUCT = nargoutchk (MINARGS, MAXARGS, NARGS, "struct")
4440     Check for correct number of output arguments.
4441
4442     In the first form, return an error if the number of arguments is
4443     not between MINARGS and MAXARGS.  Otherwise, do nothing.  Note that
4444     this function evaluates the value of ‘nargout’ on the caller so its
4445     value must have not been tampered with.
4446
4447     Both MINARGS and MAXARGS must be numeric scalars.  Zero, Inf, and
4448     negative are all valid, and they can have the same value.
4449
4450     For backwards compatibility, the other forms return an appropriate
4451     error message string (or structure) if the number of outputs
4452     requested is invalid.
4453
4454     This is useful for checking to that the number of output arguments
4455     supplied to a function is within an acceptable range.
4456
4457     See also: *note narginchk: XREFnarginchk, *note error: XREFerror,
4458     *note nargout: XREFnargout, *note nargin: XREFnargin.
4459
4460
4461File: octave.info,  Node: Validating the type of Arguments,  Next: Parsing Arguments,  Prev: Validating the number of Arguments,  Up: Validating Arguments
4462
446311.9.2 Validating the type of Arguments
4464---------------------------------------
4465
4466Besides the number of arguments, inputs can be checked for various
4467properties.  ‘validatestring’ is used for string arguments and
4468‘validateattributes’ for numeric arguments.
4469
4470 -- : VALIDSTR = validatestring (STR, STRARRAY)
4471 -- : VALIDSTR = validatestring (STR, STRARRAY, FUNCNAME)
4472 -- : VALIDSTR = validatestring (STR, STRARRAY, FUNCNAME, VARNAME)
4473 -- : VALIDSTR = validatestring (..., POSITION)
4474     Verify that STR is an element, or substring of an element, in
4475     STRARRAY.
4476
4477     When STR is a character string to be tested, and STRARRAY is a
4478     cellstr of valid values, then VALIDSTR will be the validated form
4479     of STR where validation is defined as STR being a member or
4480     substring of VALIDSTR.  This is useful for both verifying and
4481     expanding short options, such as "r", to their longer forms, such
4482     as "red".  If STR is a substring of VALIDSTR, and there are
4483     multiple matches, the shortest match will be returned if all
4484     matches are substrings of each other.  Otherwise, an error will be
4485     raised because the expansion of STR is ambiguous.  All comparisons
4486     are case insensitive.
4487
4488     The additional inputs FUNCNAME, VARNAME, and POSITION are optional
4489     and will make any generated validation error message more specific.
4490
4491     Examples:
4492
4493          validatestring ("r", {"red", "green", "blue"})
4494          ⇒ "red"
4495
4496          validatestring ("b", {"red", "green", "blue", "black"})
4497          ⇒ error: validatestring: multiple unique matches were found for 'b':
4498             blue, black
4499
4500     See also: *note strcmp: XREFstrcmp, *note strcmpi: XREFstrcmpi,
4501     *note validateattributes: XREFvalidateattributes, *note
4502     inputParser: XREFinputParser.
4503
4504 -- : validateattributes (A, CLASSES, ATTRIBUTES)
4505 -- : validateattributes (A, CLASSES, ATTRIBUTES, ARG_IDX)
4506 -- : validateattributes (A, CLASSES, ATTRIBUTES, FUNC_NAME)
4507 -- : validateattributes (A, CLASSES, ATTRIBUTES, FUNC_NAME, ARG_NAME)
4508 -- : validateattributes (A, CLASSES, ATTRIBUTES, FUNC_NAME, ARG_NAME,
4509          ARG_IDX)
4510     Check validity of input argument.
4511
4512     Confirms that the argument A is valid by belonging to one of
4513     CLASSES, and holding all of the ATTRIBUTES.  If it does not, an
4514     error is thrown, with a message formatted accordingly.  The error
4515     message can be made further complete by the function name FUN_NAME,
4516     the argument name ARG_NAME, and its position in the input ARG_IDX.
4517
4518     CLASSES must be a cell array of strings (an empty cell array is
4519     allowed) with the name of classes (remember that a class name is
4520     case sensitive).  In addition to the class name, the following
4521     categories names are also valid:
4522
4523     "float"
4524          Floating point value comprising classes "double" and "single".
4525
4526     "integer"
4527          Integer value comprising classes (u)int8, (u)int16, (u)int32,
4528          (u)int64.
4529
4530     "numeric"
4531          Numeric value comprising either a floating point or integer
4532          value.
4533
4534     ATTRIBUTES must be a cell array with names of checks for A.  Some
4535     of them require an additional value to be supplied right after the
4536     name (see details for each below).
4537
4538     "<="
4539          All values are less than or equal to the following value in
4540          ATTRIBUTES.
4541
4542     "<"
4543          All values are less than the following value in ATTRIBUTES.
4544
4545     ">="
4546          All values are greater than or equal to the following value in
4547          ATTRIBUTES.
4548
4549     ">"
4550          All values are greater than the following value in ATTRIBUTES.
4551
4552     "2d"
4553          A 2-dimensional matrix.  Note that vectors and empty matrices
4554          have 2 dimensions, one of them being of length 1, or both
4555          length 0.
4556
4557     "3d"
4558          Has no more than 3 dimensions.  A 2-dimensional matrix is a
4559          3-D matrix whose 3rd dimension is of length 1.
4560
4561     "binary"
4562          All values are either 1 or 0.
4563
4564     "column"
4565          Values are arranged in a single column.
4566
4567     "decreasing"
4568          No value is NAN, and each is less than the preceding one.
4569
4570     "diag"
4571          Value is a diagonal matrix.
4572
4573     "even"
4574          All values are even numbers.
4575
4576     "finite"
4577          All values are finite.
4578
4579     "increasing"
4580          No value is NAN, and each is greater than the preceding one.
4581
4582     "integer"
4583          All values are integer.  This is different than using
4584          ‘isinteger’ which only checks its an integer type.  This
4585          checks that each value in A is an integer value, i.e., it has
4586          no decimal part.
4587
4588     "ncols"
4589          Has exactly as many columns as the next value in ATTRIBUTES.
4590
4591     "ndims"
4592          Has exactly as many dimensions as the next value in
4593          ATTRIBUTES.
4594
4595     "nondecreasing"
4596          No value is NAN, and each is greater than or equal to the
4597          preceding one.
4598
4599     "nonempty"
4600          It is not empty.
4601
4602     "nonincreasing"
4603          No value is NAN, and each is less than or equal to the
4604          preceding one.
4605
4606     "nonnan"
4607          No value is a ‘NaN’.
4608
4609     "nonnegative"
4610          All values are non negative.
4611
4612     "nonsparse"
4613          It is not a sparse matrix.
4614
4615     "nonzero"
4616          No value is zero.
4617
4618     "nrows"
4619          Has exactly as many rows as the next value in ATTRIBUTES.
4620
4621     "numel"
4622          Has exactly as many elements as the next value in ATTRIBUTES.
4623
4624     "odd"
4625          All values are odd numbers.
4626
4627     "positive"
4628          All values are positive.
4629
4630     "real"
4631          It is a non-complex matrix.
4632
4633     "row"
4634          Values are arranged in a single row.
4635
4636     "scalar"
4637          It is a scalar.
4638
4639     "size"
4640          Its size has length equal to the values of the next in
4641          ATTRIBUTES.  The next value must is an array with the length
4642          for each dimension.  To ignore the check for a certain
4643          dimension, the value of ‘NaN’ can be used.
4644
4645     "square"
4646          Is a square matrix.
4647
4648     "vector"
4649          Values are arranged in a single vector (column or vector).
4650
4651     See also: *note isa: XREFisa, *note validatestring:
4652     XREFvalidatestring, *note inputParser: XREFinputParser.
4653
4654   As alternatives to ‘validateattributes’ there are several shorter
4655convenience functions to check for individual properties.
4656
4657 -- : mustBeFinite (X)
4658
4659     Require that input X is finite.
4660
4661     Raise an error if any element of the input X is not finite, as
4662     determined by ‘isfinite (x)’.
4663
4664     See also: *note mustBeNonNan: XREFmustBeNonNan, *note isfinite:
4665     XREFisfinite.
4666
4667 -- : mustBeGreaterThan (X, C)
4668
4669     Require that input X is greater than C.
4670
4671     Raise an error if any element of the input X is not greater than C,
4672     as determined by ‘X > C’.
4673
4674     See also: *note mustBeGreaterThanOrEqual:
4675     XREFmustBeGreaterThanOrEqual, *note mustBeLessThan:
4676     XREFmustBeLessThan, *note gt: XREFgt.
4677
4678 -- : mustBeGreaterThanOrEqual (X, C)
4679
4680     Require that input X is greater than or equal to C.
4681
4682     Raise an error if any element of the input X is not greater than or
4683     equal to C, as determined by ‘X >= C’.
4684
4685     See also: *note mustBeGreaterThan: XREFmustBeGreaterThan, *note
4686     mustBeLessThanOrEqual: XREFmustBeLessThanOrEqual, *note ge: XREFge.
4687
4688 -- : mustBeInteger (X)
4689
4690     Require that input X is integer-valued (but not necessarily
4691     integer-typed).
4692
4693     Raise an error if any element of the input X is not a finite, real,
4694     integer-valued numeric value, as determined by various checks.
4695
4696     See also: *note mustBeNumeric: XREFmustBeNumeric.
4697
4698 -- : mustBeLessThan (X, C)
4699
4700     Require that input X is less than C.
4701
4702     Raise an error if any element of the input X is not less than C, as
4703     determined by ‘X < C’.
4704
4705     See also: *note mustBeLessThanOrEqual: XREFmustBeLessThanOrEqual,
4706     *note mustBeGreaterThan: XREFmustBeGreaterThan, *note lt: XREFlt.
4707
4708 -- : mustBeLessThanOrEqual (X, C)
4709
4710     Require that input is less than or equal to a given value.
4711
4712     Raise an error if any element of the input X is not less than or
4713     equal to C, as determined by ‘X <= C’.
4714
4715     See also: *note mustBeLessThan: XREFmustBeLessThan, *note
4716     mustBeGreaterThanOrEqual: XREFmustBeGreaterThanOrEqual, *note le:
4717     XREFle.
4718
4719 -- : mustBeMember (X, VALID)
4720
4721     Require that input X is a member of a set of given valid values.
4722
4723     Raise an error if any element of the input X is not a member of the
4724     set VALID, as determined by ‘ismember (X)’.
4725
4726     Programming Note: char inputs may behave strangely because of the
4727     interaction between chars and cellstrings when calling ‘ismember’
4728     on them.  But it will probably "do what you mean" if you just use
4729     it naturally.  To guarantee operation, convert all char arrays to
4730     cellstrings with ‘cellstr’.
4731
4732     See also: *note mustBeNonempty: XREFmustBeNonempty, *note ismember:
4733     XREFismember.
4734
4735 -- : mustBeNegative (X)
4736
4737     Require that input X is negative.
4738
4739     Raise an error if any element of the input X is not negative, as
4740     determined by ‘X < 0’.
4741
4742     See also: *note mustBeNonnegative: XREFmustBeNonnegative.
4743
4744 -- : mustBeNonempty (X)
4745
4746     Require that input X is nonempty.
4747
4748     Raise an error if the input X is empty, as determined by ‘isempty
4749     (X)’.
4750
4751     See also: *note mustBeMember: XREFmustBeMember, *note
4752     mustBeNonzero: XREFmustBeNonzero, *note isempty: XREFisempty.
4753
4754 -- : mustBeNonNan (X)
4755
4756     Require that input X is non-‘NaN’.
4757
4758     Raise an error if any element of the input X is ‘NaN’, as
4759     determined by ‘isnan (X)’.
4760
4761     See also: *note mustBeFinite: XREFmustBeFinite, *note
4762     mustBeNonempty: XREFmustBeNonempty, *note isnan: XREFisnan.
4763
4764 -- : mustBeNonnegative (X)
4765
4766     Require that input X is not negative.
4767
4768     Raise an error if any element of the input X is negative, as
4769     determined by ‘X >= 0’.
4770
4771     See also: *note mustBeNonzero: XREFmustBeNonzero, *note
4772     mustBePositive: XREFmustBePositive.
4773
4774 -- : mustBeNonpositive (X)
4775
4776     Require that input X is not positive.
4777
4778     Raise an error if any element of the input X is positive, as
4779     determined by ‘X <= 0’.
4780
4781     See also: *note mustBeNegative: XREFmustBeNegative, *note
4782     mustBeNonzero: XREFmustBeNonzero.
4783
4784 -- : mustBeNonsparse (X)
4785
4786     Require that input X is not sparse.
4787
4788     Raise an error if the input X is sparse, as determined by ‘issparse
4789     (X)’.
4790
4791     See also: *note issparse: XREFissparse.
4792
4793 -- : mustBeNonzero (X)
4794
4795     Require that input X is not zero.
4796
4797     Raise an error if any element of the input X is zero, as determined
4798     by ‘X == 0’.
4799
4800     See also: *note mustBeNonnegative: XREFmustBeNonnegative, *note
4801     mustBePositive: XREFmustBePositive.
4802
4803 -- : mustBeNumeric (X)
4804
4805     Require that input X is numeric.
4806
4807     Raise an error if the input X is not numeric, as determined by
4808     ‘isnumeric (X)’.
4809
4810     See also: *note mustBeNumericOrLogical: XREFmustBeNumericOrLogical,
4811     *note isnumeric: XREFisnumeric.
4812
4813 -- : mustBeNumericOrLogical (X)
4814
4815     Require that input X is numeric or logical.
4816
4817     Raise an error if the input X is not numeric or logical, as
4818     determined by ‘isnumeric (X) || islogical (X)’.
4819
4820     See also: *note mustBeNumeric: XREFmustBeNumeric, *note isnumeric:
4821     XREFisnumeric, *note islogical: XREFislogical.
4822
4823 -- : mustBePositive (X)
4824
4825     Require that input X is positive.
4826
4827     Raise an error if any element of the input X is not positive, as
4828     determined by ‘X > 0’.
4829
4830     See also: *note mustBeNonnegative: XREFmustBeNonnegative, *note
4831     mustBeNonzero: XREFmustBeNonzero.
4832
4833 -- : mustBeReal (X)
4834
4835     Require that input X is real.
4836
4837     Raise an error if the input X is not real, as determined by ‘isreal
4838     (X)’.
4839
4840     See also: *note mustBeFinite: XREFmustBeFinite, *note mustBeNonNan:
4841     XREFmustBeNonNan, *note isreal: XREFisreal.
4842
4843
4844File: octave.info,  Node: Parsing Arguments,  Prev: Validating the type of Arguments,  Up: Validating Arguments
4845
484611.9.3 Parsing Arguments
4847------------------------
4848
4849If none of the preceding validation functions is sufficient there is
4850also the class ‘inputParser’ which can perform extremely complex input
4851checking for functions.
4852
4853 -- : P = inputParser ()
4854     Create object P of the inputParser class.
4855
4856     This class is designed to allow easy parsing of function arguments.
4857     The class supports four types of arguments:
4858
4859       1. mandatory (see ‘addRequired’);
4860
4861       2. optional (see ‘addOptional’);
4862
4863       3. named (see ‘addParameter’);
4864
4865       4. switch (see ‘addSwitch’).
4866
4867     After defining the function API with these methods, the supplied
4868     arguments can be parsed with the ‘parse’ method and the parsing
4869     results accessed with the ‘Results’ accessor.
4870
4871 -- : inputParser.Parameters
4872     Return list of parameter names already defined.
4873
4874 -- : inputParser.Results
4875     Return structure with argument names as fieldnames and
4876     corresponding values.
4877
4878 -- : inputParser.Unmatched
4879     Return structure similar to ‘Results’, but for unmatched
4880     parameters.  See the ‘KeepUnmatched’ property.
4881
4882 -- : inputParser.UsingDefaults
4883     Return cell array with the names of arguments that are using
4884     default values.
4885
4886 -- : inputParser.CaseSensitive = BOOLEAN
4887     Set whether matching of argument names should be case sensitive.
4888     Defaults to false.
4889
4890 -- : inputParser.FunctionName = NAME
4891     Set function name to be used in error messages; Defaults to empty
4892     string.
4893
4894 -- : inputParser.KeepUnmatched = BOOLEAN
4895     Set whether an error should be given for non-defined arguments.
4896     Defaults to false.  If set to true, the extra arguments can be
4897     accessed through ‘Unmatched’ after the ‘parse’ method.  Note that
4898     since ‘Switch’ and ‘Parameter’ arguments can be mixed, it is not
4899     possible to know the unmatched type.  If argument is found
4900     unmatched it is assumed to be of the ‘Parameter’ type and it is
4901     expected to be followed by a value.
4902
4903 -- : inputParser.StructExpand = BOOLEAN
4904     Set whether a structure can be passed to the function instead of
4905     parameter/value pairs.  Defaults to true.
4906
4907     The following example shows how to use this class:
4908
4909          function check (varargin)
4910            p = inputParser ();                      # create object
4911            p.FunctionName = "check";                # set function name
4912            p.addRequired ("pack", @ischar);         # mandatory argument
4913            p.addOptional ("path", pwd(), @ischar);  # optional argument
4914
4915            ## create a function handle to anonymous functions for validators
4916            val_mat = @(x) isvector (x) && all (x <= 1) && all (x >= 0);
4917            p.addOptional ("mat", [0 0], val_mat);
4918
4919            ## create two arguments of type "Parameter"
4920            val_type = @(x) any (strcmp (x, {"linear", "quadratic"}));
4921            p.addParameter ("type", "linear", val_type);
4922            val_verb = @(x) any (strcmp (x, {"low", "medium", "high"}));
4923            p.addParameter ("tolerance", "low", val_verb);
4924
4925            ## create a switch type of argument
4926            p.addSwitch ("verbose");
4927
4928            p.parse (varargin{:});  # Run created parser on inputs
4929
4930            ## the rest of the function can access inputs by using p.Results.
4931            ## for example, get the tolerance input with p.Results.tolerance
4932          endfunction
4933
4934          check ("mech");           # valid, use defaults for other arguments
4935          check ();                 # error, one argument is mandatory
4936          check (1);                # error, since ! ischar
4937          check ("mech", "~/dev");  # valid, use defaults for other arguments
4938
4939          check ("mech", "~/dev", [0 1 0 0], "type", "linear");  # valid
4940
4941          ## following is also valid.  Note how the Switch argument type can
4942          ## be mixed into or before the Parameter argument type (but it
4943          ## must still appear after any Optional argument).
4944          check ("mech", "~/dev", [0 1 0 0], "verbose", "tolerance", "high");
4945
4946          ## following returns an error since not all optional arguments,
4947          ## 'path' and 'mat', were given before the named argument 'type'.
4948          check ("mech", "~/dev", "type", "linear");
4949
4950     _Note 1_: A function can have any mixture of the four API types but
4951     they must appear in a specific order.  ‘Required’ arguments must be
4952     first and can be followed by any ‘Optional’ arguments.  Only the
4953     ‘Parameter’ and ‘Switch’ arguments may be mixed together and they
4954     must appear at the end.
4955
4956     _Note 2_: If both ‘Optional’ and ‘Parameter’ arguments are mixed in
4957     a function API then once a string Optional argument fails to
4958     validate it will be considered the end of the ‘Optional’ arguments.
4959     The remaining arguments will be compared against any ‘Parameter’ or
4960     ‘Switch’ arguments.
4961
4962     See also: *note nargin: XREFnargin, *note validateattributes:
4963     XREFvalidateattributes, *note validatestring: XREFvalidatestring,
4964     *note varargin: XREFvarargin.
4965
4966
4967File: octave.info,  Node: Function Files,  Next: Script Files,  Prev: Validating Arguments,  Up: Functions and Scripts
4968
496911.10 Function Files
4970====================
4971
4972Except for simple one-shot programs, it is not practical to have to
4973define all the functions you need each time you need them.  Instead, you
4974will normally want to save them in a file so that you can easily edit
4975them, and save them for use at a later time.
4976
4977   Octave does not require you to load function definitions from files
4978before using them.  You simply need to put the function definitions in a
4979place where Octave can find them.
4980
4981   When Octave encounters an identifier that is undefined, it first
4982looks for variables or functions that are already compiled and currently
4983listed in its symbol table.  If it fails to find a definition there, it
4984searches a list of directories (the “path”) for files ending in ‘.m’
4985that have the same base name as the undefined identifier.(1)  Once
4986Octave finds a file with a name that matches, the contents of the file
4987are read.  If it defines a _single_ function, it is compiled and
4988executed.  *Note Script Files::, for more information about how you can
4989define more than one function in a single file.
4990
4991   When Octave defines a function from a function file, it saves the
4992full name of the file it read and the time stamp on the file.  If the
4993time stamp on the file changes, Octave may reload the file.  When Octave
4994is running interactively, time stamp checking normally happens at most
4995once each time Octave prints the prompt.  Searching for new function
4996definitions also occurs if the current working directory changes.
4997
4998   Checking the time stamp allows you to edit the definition of a
4999function while Octave is running, and automatically use the new function
5000definition without having to restart your Octave session.
5001
5002   To avoid degrading performance unnecessarily by checking the time
5003stamps on functions that are not likely to change, Octave assumes that
5004function files in the directory tree
5005OCTAVE-HOME/share/octave/VERSION/m’ will not change, so it doesn’t have
5006to check their time stamps every time the functions defined in those
5007files are used.  This is normally a very good assumption and provides a
5008significant improvement in performance for the function files that are
5009distributed with Octave.
5010
5011   If you know that your own function files will not change while you
5012are running Octave, you can improve performance by calling
5013‘ignore_function_time_stamp ("all")’, so that Octave will ignore the
5014time stamps for all function files.  Passing "system" to this function
5015resets the default behavior.
5016
5017 -- : edit NAME
5018 -- : edit FIELD VALUE
5019 -- : VALUE = edit ("get", FIELD)
5020 -- : VALUE = edit ("get", "all")
5021     Edit the named function, or change editor settings.
5022
5023     If ‘edit’ is called with the name of a file or function as its
5024     argument it will be opened in the text editor defined by ‘EDITOR’.
5025
5026        • If the function NAME is available in a file on your path, then
5027          it will be opened in the editor.  If no file is found, then
5028          the m-file variant, ending with ".m", will be considered.  If
5029          still no file is found, then variants with a leading "@" and
5030          then with both a leading "@" and trailing ".m" will be
5031          considered.
5032
5033        • If NAME is the name of a command-line function, then an m-file
5034          will be created to contain that function along with its
5035          current definition.
5036
5037        • If ‘NAME.cc’ is specified, then it will search for ‘NAME.cc5038          in the path and open it in the editor.  If the file is not
5039          found, then a new ‘.cc’ file will be created.  If NAME happens
5040          to be an m-file or command-line function, then the text of
5041          that function will be inserted into the .cc file as a comment.
5042
5043        • If ‘NAME.ext’ is on your path then it will be edited,
5044          otherwise the editor will be started with ‘NAME.ext’ in the
5045          current directory as the filename.
5046
5047          *Warning:* You may need to clear NAME before the new
5048          definition is available.  If you are editing a .cc file, you
5049          will need to execute ‘mkoctfile NAME.cc’ before the definition
5050          will be available.
5051
5052     If ‘edit’ is called with FIELD and VALUE variables, the value of
5053     the control field FIELD will be set to VALUE.
5054
5055     If an output argument is requested and the first input argument is
5056     ‘get’ then ‘edit’ will return the value of the control field FIELD.
5057     If the control field does not exist, edit will return a structure
5058     containing all fields and values.  Thus, ‘edit ("get", "all")’
5059     returns a complete control structure.
5060
5061     The following control fields are used:
5062
5063     ‘author’
5064          This is the name to put after the "## Author:" field of new
5065          functions.  By default it guesses from the ‘gecos’ field of
5066          the password database.
5067
5068     ‘email’
5069          This is the e-mail address to list after the name in the
5070          author field.  By default it guesses ‘<$LOGNAME@$HOSTNAME>’,
5071          and if ‘$HOSTNAME’ is not defined it uses ‘uname -n’.  You
5072          probably want to override this.  Be sure to use the format
5073          ‘<user@host>’.
5074
5075     ‘license’
5076
5077          ‘gpl’
5078               GNU General Public License (default).
5079
5080          ‘bsd’
5081               BSD-style license without advertising clause.
5082
5083          ‘pd’
5084               Public domain.
5085
5086          ‘"text"’
5087               Your own default copyright and license.
5088
5089          Unless you specify ‘pd’, edit will prepend the copyright
5090          statement with "Copyright (C) YYYY Author".
5091
5092     ‘mode’
5093          This value determines whether the editor should be started in
5094          async mode (editor is started in the background and Octave
5095          continues) or sync mode (Octave waits until the editor exits).
5096          Set it to "sync" to start the editor in sync mode.  The
5097          default is "async" (*note system: XREFsystem.).
5098
5099     ‘editinplace’
5100          Determines whether files should be edited in place, without
5101          regard to whether they are modifiable or not.  The default is
5102          ‘true’.  Set it to ‘false’ to have read-only function files
5103          automatically copied to ‘home’, if it exists, when editing
5104          them.
5105
5106     ‘home’
5107          This value indicates a directory that system m-files should be
5108          copied into before opening them in the editor.  The intent is
5109          that this directory is also in the path, so that the edited
5110          copy of a system function file shadows the original.  This
5111          setting only has an effect when ‘editinplace’ is set to
5112          ‘false’.  The default is the empty matrix (‘[]’), which means
5113          it is not used.  The default in previous versions of Octave
5114          was ‘~/octave’.
5115
5116     See also: *note EDITOR: XREFEDITOR, *note path: XREFpath.
5117
5118 -- : mfilename ()
5119 -- : mfilename ("fullpath")
5120 -- : mfilename ("fullpathext")
5121     Return the name of the currently executing file.
5122
5123     The base name of the currently executing script or function is
5124     returned without any extension.  If called from outside an m-file,
5125     such as the command line, return the empty string.
5126
5127     Given the argument "fullpath", include the directory part of the
5128     filename, but not the extension.
5129
5130     Given the argument "fullpathext", include the directory part of the
5131     filename and the extension.
5132
5133     See also: *note inputname: XREFinputname, *note dbstack:
5134     XREFdbstack.
5135
5136 -- : VAL = ignore_function_time_stamp ()
5137 -- : OLD_VAL = ignore_function_time_stamp (NEW_VAL)
5138     Query or set the internal variable that controls whether Octave
5139     checks the time stamp on files each time it looks up functions
5140     defined in function files.
5141
5142     If the internal variable is set to "system", Octave will not
5143     automatically recompile function files in subdirectories of
5144OCTAVE-HOME/share/VERSION/m’ if they have changed since they were
5145     last compiled, but will recompile other function files in the
5146     search path if they change.
5147
5148     If set to "all", Octave will not recompile any function files
5149     unless their definitions are removed with ‘clear’.
5150
5151     If set to "none", Octave will always check time stamps on files to
5152     determine whether functions defined in function files need to
5153     recompiled.
5154
5155* Menu:
5156
5157* Manipulating the Load Path::
5158* Subfunctions::
5159* Private Functions::
5160* Nested Functions::
5161* Overloading and Autoloading::
5162* Function Locking::
5163* Function Precedence::
5164
5165   ---------- Footnotes ----------
5166
5167   (1) The ‘.m’ suffix was chosen for compatibility with MATLAB.
5168
5169
5170File: octave.info,  Node: Manipulating the Load Path,  Next: Subfunctions,  Up: Function Files
5171
517211.10.1 Manipulating the Load Path
5173----------------------------------
5174
5175When a function is called, Octave searches a list of directories for a
5176file that contains the function declaration.  This list of directories
5177is known as the load path.  By default the load path contains a list of
5178directories distributed with Octave plus the current working directory.
5179To see your current load path call the ‘path’ function without any input
5180or output arguments.
5181
5182   It is possible to add or remove directories to or from the load path
5183using ‘addpath’ and ‘rmpath’.  As an example, the following code adds
5184‘~/Octave’ to the load path.
5185
5186     addpath ("~/Octave")
5187
5188After this the directory ‘~/Octave’ will be searched for functions.
5189
5190 -- : addpath (DIR1, ...)
5191 -- : addpath (DIR1, ..., OPTION)
5192     Add named directories to the function search path.
5193
5194     If OPTION is "-begin" or 0 (the default), prepend the directory
5195     name(s) to the current path.  If OPTION is "-end" or 1, append the
5196     directory name(s) to the current path.  Directories added to the
5197     path must exist.
5198
5199     In addition to accepting individual directory arguments, lists of
5200     directory names separated by ‘pathsep’ are also accepted.  For
5201     example:
5202
5203          addpath ("dir1:/dir2:~/dir3")
5204
5205     The newly added paths appear in the load path in the same order
5206     that they appear in the arguments of ‘addpath’.  When extending the
5207     load path to the front, the last path in the list of arguments is
5208     added first.  When extending the load path to the end, the first
5209     path in the list of arguments is added first.
5210
5211     For each directory that is added, and that was not already in the
5212     path, ‘addpath’ checks for the existence of a file named ‘PKG_ADD’
5213     (note lack of .m extension) and runs it if it exists.
5214
5215     See also: *note path: XREFpath, *note rmpath: XREFrmpath, *note
5216     genpath: XREFgenpath, *note pathdef: XREFpathdef, *note savepath:
5217     XREFsavepath, *note pathsep: XREFpathsep.
5218
5219 -- : genpath (DIR)
5220 -- : genpath (DIR, SKIP, ...)
5221     Return a path constructed from DIR and all its subdirectories.
5222
5223     The path does not include package directories (beginning with ‘+’),
5224     old-style class directories (beginning with ‘@’), ‘private’
5225     directories, or any subdirectories of these types.
5226
5227     If additional string parameters are given, the resulting path will
5228     exclude directories with those names.
5229
5230     See also: *note path: XREFpath, *note addpath: XREFaddpath.
5231
5232 -- : rmpath (DIR1, ...)
5233     Remove DIR1, ... from the current function search path.
5234
5235     In addition to accepting individual directory arguments, lists of
5236     directory names separated by ‘pathsep’ are also accepted.  For
5237     example:
5238
5239          rmpath ("dir1:/dir2:~/dir3")
5240
5241     For each directory that is removed, ‘rmpath’ checks for the
5242     existence of a file named ‘PKG_DEL’ (note lack of .m extension) and
5243     runs it if it exists.
5244
5245     See also: *note path: XREFpath, *note addpath: XREFaddpath, *note
5246     genpath: XREFgenpath, *note pathdef: XREFpathdef, *note savepath:
5247     XREFsavepath, *note pathsep: XREFpathsep.
5248
5249 -- : savepath ()
5250 -- : savepath (FILE)
5251 -- : STATUS = savepath (...)
5252     Save the unique portion of the current function search path that is
5253     not set during Octave’s initialization process to FILE.
5254
5255     If FILE is omitted, Octave looks in the current directory for a
5256     project-specific ‘.octaverc’ file in which to save the path
5257     information.  If no such file is present then the user’s
5258     configuration file ‘~/.octaverc’ is used.
5259
5260     If successful, ‘savepath’ returns 0.
5261
5262     The ‘savepath’ function makes it simple to customize a user’s
5263     configuration file to restore the working paths necessary for a
5264     particular instance of Octave.  Assuming no filename is specified,
5265     Octave will automatically restore the saved directory paths from
5266     the appropriate ‘.octaverc’ file when starting up.  If a filename
5267     has been specified then the paths may be restored manually by
5268     calling ‘source FILE’.
5269
5270     See also: *note path: XREFpath, *note addpath: XREFaddpath, *note
5271     rmpath: XREFrmpath, *note genpath: XREFgenpath, *note pathdef:
5272     XREFpathdef.
5273
5274 -- : path ()
5275 -- : STR = path ()
5276 -- : STR = path (PATH1, ...)
5277     Modify or display Octave’s load path.
5278
5279     If NARGIN and NARGOUT are zero, display the elements of Octave’s
5280     load path in an easy to read format.
5281
5282     If NARGIN is zero and nargout is greater than zero, return the
5283     current load path.
5284
5285     If NARGIN is greater than zero, concatenate the arguments,
5286     separating them with ‘pathsep’.  Set the internal search path to
5287     the result and return it.
5288
5289     No checks are made for duplicate elements.
5290
5291     See also: *note addpath: XREFaddpath, *note rmpath: XREFrmpath,
5292     *note genpath: XREFgenpath, *note pathdef: XREFpathdef, *note
5293     savepath: XREFsavepath, *note pathsep: XREFpathsep.
5294
5295 -- : VAL = pathdef ()
5296     Return the default path for Octave.
5297
5298     The path information is extracted from one of four sources.  The
5299     possible sources, in order of preference, are:
5300
5301       1. ‘.octaverc’
5302
5303       2. ‘~/.octaverc’
5304
5305       3. ‘<OCTAVE_HOME>/.../<version>/m/startup/octaverc5306
5307       4. Octave’s path prior to changes by any octaverc file.
5308
5309     See also: *note path: XREFpath, *note addpath: XREFaddpath, *note
5310     rmpath: XREFrmpath, *note genpath: XREFgenpath, *note savepath:
5311     XREFsavepath.
5312
5313 -- : VAL = pathsep ()
5314     Query the character used to separate directories in a path.
5315
5316     See also: *note filesep: XREFfilesep.
5317
5318 -- : rehash ()
5319     Reinitialize Octave’s load path directory cache.
5320
5321 -- : FNAME = file_in_loadpath (FILE)
5322 -- : FNAME = file_in_loadpath (FILE, "all")
5323     Return the absolute name of FILE if it can be found in the list of
5324     directories specified by ‘path’.
5325
5326     If no file is found, return an empty character string.
5327
5328     When FILE is already an absolute name, the name is checked against
5329     the file system instead of Octave’s loadpath.  In this case, if
5330     FILE exists it will be returned in FNAME, otherwise an empty string
5331     is returned.
5332
5333     If the first argument is a cell array of strings, search each
5334     directory of the loadpath for element of the cell array and return
5335     the first that matches.
5336
5337     If the second optional argument "all" is supplied, return a cell
5338     array containing the list of all files that have the same name in
5339     the path.  If no files are found, return an empty cell array.
5340
5341     See also: *note file_in_path: XREFfile_in_path, *note
5342     dir_in_loadpath: XREFdir_in_loadpath, *note path: XREFpath.
5343
5344 -- : restoredefaultpath ()
5345     Restore Octave’s path to its initial state at startup.
5346
5347     See also: *note path: XREFpath, *note addpath: XREFaddpath, *note
5348     rmpath: XREFrmpath, *note genpath: XREFgenpath, *note pathdef:
5349     XREFpathdef, *note savepath: XREFsavepath, *note pathsep:
5350     XREFpathsep.
5351
5352 -- : command_line_path ()
5353     Return the command line path variable.
5354
5355     See also: *note path: XREFpath, *note addpath: XREFaddpath, *note
5356     rmpath: XREFrmpath, *note genpath: XREFgenpath, *note pathdef:
5357     XREFpathdef, *note savepath: XREFsavepath, *note pathsep:
5358     XREFpathsep.
5359
5360 -- : DIRNAME = dir_in_loadpath (DIR)
5361 -- : DIRNAME = dir_in_loadpath (DIR, "all")
5362     Return the absolute name of the loadpath element matching DIR if it
5363     can be found in the list of directories specified by ‘path’.
5364
5365     If no match is found, return an empty character string.
5366
5367     The match is performed at the end of each path element.  For
5368     example, if DIR is "foo/bar", it matches the path element
5369     "/some/dir/foo/bar", but not "/some/dir/foo/bar/baz"
5370     "/some/dir/allfoo/bar".  When DIR is an absolute name, rather than
5371     just a path fragment, it is matched against the file system instead
5372     of Octave’s loadpath.  In this case, if DIR exists it will be
5373     returned in DIRNAME, otherwise an empty string is returned.
5374
5375     If the optional second argument is supplied, return a cell array
5376     containing all name matches rather than just the first.
5377
5378     See also: *note file_in_path: XREFfile_in_path, *note
5379     file_in_loadpath: XREFfile_in_loadpath, *note path: XREFpath.
5380
5381
5382File: octave.info,  Node: Subfunctions,  Next: Private Functions,  Prev: Manipulating the Load Path,  Up: Function Files
5383
538411.10.2 Subfunctions
5385--------------------
5386
5387A function file may contain secondary functions called “subfunctions”.
5388These secondary functions are only visible to the other functions in the
5389same function file.  For example, a file ‘f.m’ containing
5390
5391     function f ()
5392       printf ("in f, calling g\n");
5393       g ()
5394     endfunction
5395     function g ()
5396       printf ("in g, calling h\n");
5397       h ()
5398     endfunction
5399     function h ()
5400       printf ("in h\n")
5401     endfunction
5402
5403defines a main function ‘f’ and two subfunctions.  The subfunctions ‘g’
5404and ‘h’ may only be called from the main function ‘f’ or from the other
5405subfunctions, but not from outside the file ‘f.m’.
5406
5407 -- : localfunctions ()
5408     Return a list of all local functions, i.e., subfunctions, within
5409     the current file.
5410
5411     The return value is a column cell array of function handles to all
5412     local functions accessible from the function from which
5413     ‘localfunctions’ is called.  Nested functions are _not_ included in
5414     the list.
5415
5416     If the call is from the command line, an anonymous function, or a
5417     script, the return value is an empty cell array.
5418
5419     See also: *note functions: XREFfunctions.
5420
5421
5422File: octave.info,  Node: Private Functions,  Next: Nested Functions,  Prev: Subfunctions,  Up: Function Files
5423
542411.10.3 Private Functions
5425-------------------------
5426
5427In many cases one function needs to access one or more helper functions.
5428If the helper function is limited to the scope of a single function,
5429then subfunctions as discussed above might be used.  However, if a
5430single helper function is used by more than one function, then this is
5431no longer possible.  In this case the helper functions might be placed
5432in a subdirectory, called "private", of the directory in which the
5433functions needing access to this helper function are found.
5434
5435   As a simple example, consider a function ‘func1’, that calls a helper
5436function ‘func2’ to do much of the work.  For example:
5437
5438     function y = func1 (x)
5439       y = func2 (x);
5440     endfunction
5441
5442Then if the path to ‘func1’ is ‘<directory>/func1.m’, and if ‘func2’ is
5443found in the directory ‘<directory>/private/func2.m’, then ‘func2’ is
5444only available for use of the functions, like ‘func1’, that are found in
5445‘<directory>’.
5446
5447
5448File: octave.info,  Node: Nested Functions,  Next: Overloading and Autoloading,  Prev: Private Functions,  Up: Function Files
5449
545011.10.4 Nested Functions
5451------------------------
5452
5453Nested functions are similar to subfunctions in that only the main
5454function is visible outside the file.  However, they also allow for
5455child functions to access the local variables in their parent function.
5456This shared access mimics using a global variable to share information —
5457but a global variable which is not visible to the rest of Octave.  As a
5458programming strategy, sharing data this way can create code which is
5459difficult to maintain.  It is recommended to use subfunctions in place
5460of nested functions when possible.
5461
5462   As a simple example, consider a parent function ‘foo’, that calls a
5463nested child function ‘bar’, with a shared variable X.
5464
5465     function y = foo ()
5466       x = 10;
5467       bar ();
5468       y = x;
5469
5470       function bar ()
5471         x = 20;
5472       endfunction
5473     endfunction
5474
5475     foo ()
5476      ⇒ 20
5477
5478Notice that there is no special syntax for sharing X.  This can lead to
5479problems with accidental variable sharing between a parent function and
5480its child.  While normally variables are inherited, child function
5481parameters and return values are local to the child function.
5482
5483   Now consider the function ‘foobar’ that uses variables X and Y.
5484‘foobar’ calls a nested function ‘foo’ which takes X as a parameter and
5485returns Y.  ‘foo’ then calls ‘bat’ which does some computation.
5486
5487     function z = foobar ()
5488       x = 0;
5489       y = 0;
5490       z = foo (5);
5491       z += x + y;
5492
5493       function y = foo (x)
5494         y = x + bat ();
5495
5496         function z = bat ()
5497           z = x;
5498         endfunction
5499       endfunction
5500     endfunction
5501
5502     foobar ()
5503         ⇒ 10
5504
5505It is important to note that the X and Y in ‘foobar’ remain zero, as in
5506‘foo’ they are a return value and parameter respectively.  The X in
5507‘bat’ refers to the X in ‘foo’.
5508
5509   Variable inheritance leads to a problem for ‘eval’ and scripts.  If a
5510new variable is created in a parent function, it is not clear what
5511should happen in nested child functions.  For example, consider a parent
5512function ‘foo’ with a nested child function ‘bar’:
5513
5514     function y = foo (to_eval)
5515       bar ();
5516       eval (to_eval);
5517
5518       function bar ()
5519         eval ("x = 100;");
5520         eval ("y = x;");
5521       endfunction
5522     endfunction
5523
5524     foo ("x = 5;")
5525         ⇒ error: can not add variable "x" to a static workspace
5526
5527     foo ("y = 10;")
5528         ⇒ 10
5529
5530     foo ("")
5531         ⇒ 100
5532
5533The parent function ‘foo’ is unable to create a new variable X, but the
5534child function ‘bar’ was successful.  Furthermore, even in an ‘eval’
5535statement Y in ‘bar’ is the same Y as in its parent function ‘foo’.  The
5536use of ‘eval’ in conjunction with nested functions is best avoided.
5537
5538   As with subfunctions, only the first nested function in a file may be
5539called from the outside.  Inside a function the rules are more
5540complicated.  In general a nested function may call:
5541
5542  0. Globally visible functions
5543
5544  1. Any function that the nested function’s parent can call
5545
5546  2. Sibling functions (functions that have the same parents)
5547
5548  3. Direct children
5549
5550   As a complex example consider a parent function ‘ex_top’ with two
5551child functions, ‘ex_a’ and ‘ex_b’.  In addition, ‘ex_a’ has two more
5552child functions, ‘ex_aa’ and ‘ex_ab’.  For example:
5553
5554     function ex_top ()
5555       ## Can call: ex_top, ex_a, and ex_b
5556       ## Can NOT call: ex_aa and ex_ab
5557
5558       function ex_a ()
5559         ## Can call everything
5560
5561         function ex_aa ()
5562           ## Can call everything
5563         endfunction
5564
5565         function ex_ab ()
5566           ## Can call everything
5567         endfunction
5568       endfunction
5569
5570       function ex_b ()
5571         ## Can call: ex_top, ex_a, and ex_b
5572         ## Can NOT call: ex_aa and ex_ab
5573       endfunction
5574     endfunction
5575
5576
5577File: octave.info,  Node: Overloading and Autoloading,  Next: Function Locking,  Prev: Nested Functions,  Up: Function Files
5578
557911.10.5 Overloading and Autoloading
5580-----------------------------------
5581
5582Functions can be overloaded to work with different input arguments.  For
5583example, the operator ’+’ has been overloaded in Octave to work with
5584single, double, uint8, int32, and many other arguments.  The preferred
5585way to overload functions is through classes and object oriented
5586programming (*note Function Overloading::).  Occasionally, however, one
5587needs to undo user overloading and call the default function associated
5588with a specific type.  The ‘builtin’ function exists for this purpose.
5589
5590 -- : [...] = builtin (F, ...)
5591     Call the base function F even if F is overloaded to another
5592     function for the given type signature.
5593
5594     This is normally useful when doing object-oriented programming and
5595     there is a requirement to call one of Octave’s base functions
5596     rather than the overloaded one of a new class.
5597
5598     A trivial example which redefines the ‘sin’ function to be the
5599     ‘cos’ function shows how ‘builtin’ works.
5600
5601          sin (0)
5602            ⇒ 0
5603          function y = sin (x), y = cos (x); endfunction
5604          sin (0)
5605            ⇒ 1
5606          builtin ("sin", 0)
5607            ⇒ 0
5608
5609   A single dynamically linked file might define several functions.
5610However, as Octave searches for functions based on the functions
5611filename, Octave needs a manner in which to find each of the functions
5612in the dynamically linked file.  On operating systems that support
5613symbolic links, it is possible to create a symbolic link to the original
5614file for each of the functions which it contains.
5615
5616   However, there is at least one well known operating system that
5617doesn’t support symbolic links.  Making copies of the original file for
5618each of the functions is undesirable as it increases the amount of disk
5619space used by Octave.  Instead Octave supplies the ‘autoload’ function,
5620that permits the user to define in which file a certain function will be
5621found.
5622
5623 -- : AUTOLOAD_MAP = autoload ()
5624 -- : autoload (FUNCTION, FILE)
5625 -- : autoload (..., "remove")
5626     Define FUNCTION to autoload from FILE.
5627
5628     The second argument, FILE, should be an absolute filename or a file
5629     name in the same directory as the function or script from which the
5630     autoload command was run.  FILE _should not_ depend on the Octave
5631     load path.
5632
5633     Normally, calls to ‘autoload’ appear in PKG_ADD script files that
5634     are evaluated when a directory is added to Octave’s load path.  To
5635     avoid having to hardcode directory names in FILE, if FILE is in the
5636     same directory as the PKG_ADD script then
5637
5638          autoload ("foo", "bar.oct");
5639
5640     will load the function ‘foo’ from the file ‘bar.oct’.  The above
5641     usage when ‘bar.oct’ is not in the same directory, or usages such
5642     as
5643
5644          autoload ("foo", file_in_loadpath ("bar.oct"))
5645
5646     are strongly discouraged, as their behavior may be unpredictable.
5647
5648     With no arguments, return a structure containing the current
5649     autoload map.
5650
5651     If a third argument "remove" is given, the function is cleared and
5652     not loaded anymore during the current Octave session.
5653
5654     See also: *note PKG_ADD: XREFPKG_ADD.
5655
5656
5657File: octave.info,  Node: Function Locking,  Next: Function Precedence,  Prev: Overloading and Autoloading,  Up: Function Files
5658
565911.10.6 Function Locking
5660------------------------
5661
5662It is sometime desirable to lock a function into memory with the ‘mlock’
5663function.  This is typically used for dynamically linked functions in
5664oct-files or mex-files that contain some initialization, and it is
5665desirable that calling ‘clear’ does not remove this initialization.
5666
5667   As an example,
5668
5669     function my_function ()
5670       mlock ();
5671       ...
5672     endfunction
5673
5674prevents ‘my_function’ from being removed from memory after it is
5675called, even if ‘clear’ is called.  It is possible to determine if a
5676function is locked into memory with the ‘mislocked’, and to unlock a
5677function with ‘munlock’, which the following code illustrates.
5678
5679     my_function ();
5680     mislocked ("my_function")
5681     ⇒ ans = 1
5682     munlock ("my_function");
5683     mislocked ("my_function")
5684     ⇒ ans = 0
5685
5686   A common use of ‘mlock’ is to prevent persistent variables from being
5687removed from memory, as the following example shows:
5688
5689     function count_calls ()
5690       mlock ();
5691       persistent calls = 0;
5692       printf ("count_calls() has been called %d times\n", ++calls);
5693     endfunction
5694
5695     count_calls ();
5696     ⊣ count_calls() has been called 1 times
5697
5698     clear count_calls
5699     count_calls ();
5700     ⊣ count_calls() has been called 2 times
5701
5702   ‘mlock’ might also be used to prevent changes to an m-file, such as
5703in an external editor, from having any effect in the current Octave
5704session; A similar effect can be had with the
5705‘ignore_function_time_stamp’ function.
5706
5707 -- : mlock ()
5708     Lock the current function into memory so that it can’t be removed
5709     with ‘clear’.
5710
5711     See also: *note munlock: XREFmunlock, *note mislocked:
5712     XREFmislocked, *note persistent: XREFpersistent, *note clear:
5713     XREFclear.
5714
5715 -- : munlock ()
5716 -- : munlock (FCN)
5717     Unlock the named function FCN so that it may be removed from memory
5718     with ‘clear’.
5719
5720     If no function is named then unlock the current function.
5721
5722     See also: *note mlock: XREFmlock, *note mislocked: XREFmislocked,
5723     *note persistent: XREFpersistent, *note clear: XREFclear.
5724
5725 -- : mislocked ()
5726 -- : mislocked (FCN)
5727     Return true if the named function FCN is locked in memory.
5728
5729     If no function is named then return true if the current function is
5730     locked.
5731
5732     See also: *note mlock: XREFmlock, *note munlock: XREFmunlock, *note
5733     persistent: XREFpersistent, *note clear: XREFclear.
5734
5735
5736File: octave.info,  Node: Function Precedence,  Prev: Function Locking,  Up: Function Files
5737
573811.10.7 Function Precedence
5739---------------------------
5740
5741Given the numerous different ways that Octave can define a function, it
5742is possible and even likely that multiple versions of a function, might
5743be defined within a particular scope.  The precedence of which function
5744will be used within a particular scope is given by
5745
5746  1. Subfunction A subfunction with the required function name in the
5747     given scope.
5748
5749  2. Private function A function defined within a private directory of
5750     the directory which contains the current function.
5751
5752  3. Class constructor A function that constructs a user class as
5753     defined in chapter *note Object Oriented Programming::.
5754
5755  4. Class method An overloaded function of a class as in chapter *note
5756     Object Oriented Programming::.
5757
5758  5. Command-line Function A function that has been defined on the
5759     command-line.
5760
5761  6. Autoload function A function that is marked as autoloaded with
5762     *Note autoload: XREFautoload.
5763
5764  7. A Function on the Path A function that can be found on the users
5765     load-path.  There can also be Oct-file, mex-file or m-file versions
5766     of this function and the precedence between these versions are in
5767     that order.
5768
5769  8. Built-in function A function that is a part of core Octave such as
5770     ‘numel’, ‘size’, etc.
5771
5772
5773File: octave.info,  Node: Script Files,  Next: Function Handles and Anonymous Functions,  Prev: Function Files,  Up: Functions and Scripts
5774
577511.11 Script Files
5776==================
5777
5778A script file is a file containing (almost) any sequence of Octave
5779commands.  It is read and evaluated just as if you had typed each
5780command at the Octave prompt, and provides a convenient way to perform a
5781sequence of commands that do not logically belong inside a function.
5782
5783   Unlike a function file, a script file must _not_ begin with the
5784keyword ‘function’.  If it does, Octave will assume that it is a
5785function file, and that it defines a single function that should be
5786evaluated as soon as it is defined.
5787
5788   A script file also differs from a function file in that the variables
5789named in a script file are not local variables, but are in the same
5790scope as the other variables that are visible on the command line.
5791
5792   Even though a script file may not begin with the ‘function’ keyword,
5793it is possible to define more than one function in a single script file
5794and load (but not execute) all of them at once.  To do this, the first
5795token in the file (ignoring comments and other white space) must be
5796something other than ‘function’.  If you have no other statements to
5797evaluate, you can use a statement that has no effect, like this:
5798
5799     # Prevent Octave from thinking that this
5800     # is a function file:
5801
5802     1;
5803
5804     # Define function one:
5805
5806     function one ()
5807       ...
5808
5809   To have Octave read and compile these functions into an internal
5810form, you need to make sure that the file is in Octave’s load path
5811(accessible through the ‘path’ function), then simply type the base name
5812of the file that contains the commands.  (Octave uses the same rules to
5813search for script files as it does to search for function files.)
5814
5815   If the first token in a file (ignoring comments) is ‘function’,
5816Octave will compile the function and try to execute it, printing a
5817message warning about any non-whitespace characters that appear after
5818the function definition.
5819
5820   Note that Octave does not try to look up the definition of any
5821identifier until it needs to evaluate it.  This means that Octave will
5822compile the following statements if they appear in a script file, or are
5823typed at the command line,
5824
5825     # not a function file:
5826     1;
5827     function foo ()
5828       do_something ();
5829     endfunction
5830     function do_something ()
5831       do_something_else ();
5832     endfunction
5833
5834even though the function ‘do_something’ is not defined before it is
5835referenced in the function ‘foo’.  This is not an error because Octave
5836does not need to resolve all symbols that are referenced by a function
5837until the function is actually evaluated.
5838
5839   Since Octave doesn’t look for definitions until they are needed, the
5840following code will always print ‘bar = 3’ whether it is typed directly
5841on the command line, read from a script file, or is part of a function
5842body, even if there is a function or script file called ‘bar.m’ in
5843Octave’s path.
5844
5845     eval ("bar = 3");
5846     bar
5847
5848   Code like this appearing within a function body could fool Octave if
5849definitions were resolved as the function was being compiled.  It would
5850be virtually impossible to make Octave clever enough to evaluate this
5851code in a consistent fashion.  The parser would have to be able to
5852perform the call to ‘eval’ at compile time, and that would be impossible
5853unless all the references in the string to be evaluated could also be
5854resolved, and requiring that would be too restrictive (the string might
5855come from user input, or depend on things that are not known until the
5856function is evaluated).
5857
5858   Although Octave normally executes commands from script files that
5859have the name ‘FILE.m’, you can use the function ‘source’ to execute
5860commands from any file.
5861
5862 -- : source (FILE)
5863 -- : source (FILE, CONTEXT)
5864     Parse and execute the contents of FILE.
5865
5866     Without specifying CONTEXT, this is equivalent to executing
5867     commands from a script file, but without requiring the file to be
5868     named ‘FILE.m’ or to be on the execution path.
5869
5870     Instead of the current context, the script may be executed in
5871     either the context of the function that called the present function
5872     ("caller"), or the top-level context ("base").
5873
5874     See also: *note run: XREFrun.
5875
5876* Menu:
5877
5878* Publish Octave Script Files::
5879* Publishing Markup::
5880
5881
5882File: octave.info,  Node: Publish Octave Script Files,  Next: Publishing Markup,  Up: Script Files
5883
588411.11.1 Publish Octave Script Files
5885-----------------------------------
5886
5887The function ‘publish’ provides a dynamic possibility to document your
5888script file.  Unlike static documentation, ‘publish’ runs the script
5889file, saves any figures and output while running the script, and
5890presents them alongside static documentation in a desired output format.
5891The static documentation can make use of *note Publishing Markup:: to
5892enhance and customize the output.
5893
5894 -- : publish (FILE)
5895 -- : publish (FILE, OUTPUT_FORMAT)
5896 -- : publish (FILE, OPTION1, VALUE1, ...)
5897 -- : publish (FILE, OPTIONS)
5898 -- : OUTPUT_FILE = publish (FILE, ...)
5899
5900     Generate a report from the Octave script file FILE in one of
5901     several output formats.
5902
5903     The generated reports interpret any Publishing Markup in comments,
5904     which is explained in detail in the GNU Octave manual.  Assume the
5905     following example, using some Publishing Markup, to be the contents
5906     of the script file ‘pub_example.m’:
5907
5908          ## Headline title
5909          #
5910          # Some *bold*, _italic_, or |monospaced| Text with
5911          # a <https://www.octave.org link to *GNU Octave*>.
5912          ##
5913
5914          # "Real" Octave commands to be evaluated
5915          sombrero ()
5916
5917          %% MATLAB comment style ('%') is supported as well
5918          %
5919          % * Bulleted list item 1
5920          % * Bulleted list item 2
5921          %
5922          % # Numbered list item 1
5923          % # Numbered list item 2
5924
5925     To publish this script file, type ‘publish ("pub_example.m")’.
5926
5927     With only FILE given, a HTML report is generated in a subdirectory
5928     ‘html’ relative to the current working directory.  The Octave
5929     commands are evaluated in a separate context and any figures
5930     created while executing the script file are included in the report.
5931     All formatting syntax of FILE is treated according to the specified
5932     output format and included in the report.
5933
5934     Using ‘publish (FILE, OUTPUT_FORMAT)’ is equivalent to the function
5935     call using a structure
5936
5937          OPTIONS.format = OUTPUT_FORMAT;
5938          publish (FILE, OPTIONS)
5939
5940     which is described below.  The same holds for using option/value
5941     pairs
5942
5943          OPTIONS.OPTION1 = VALUE1;
5944          publish (FILE, OPTIONS)
5945
5946     The structure OPTIONS can have the following field names.  If a
5947     field name is not specified, the default value is used:
5948
5949        • ‘format’ — Output format of the published script file, one of
5950
5951          ‘html’ (default), ‘doc’, ‘latex’, ‘ppt’, ‘pdf’, or ‘xml’.
5952
5953          The output formats ‘doc’, ‘ppt’, and ‘xml’ are not currently
5954          supported.  To generate a ‘doc’ report, open a generated
5955          ‘html’ report with your office suite.
5956
5957          In Octave custom formats are supported by implementing all
5958          callback subfunctions in a function file named
5959          ‘__publish_<custom format>_output__.m’.  To obtain a template
5960          for the HTML format type:
5961
5962               edit (fullfile (fileparts (which ("publish")), ...
5963                     "private", "__publish_html_output__.m"))
5964
5965        • ‘outputDir’ — Full path of the directory where the generated
5966          report will be located.  If no directory is given, the report
5967          is generated in a subdirectory ‘html’ relative to the current
5968          working directory.
5969
5970        • ‘stylesheet’ — Not supported, only for MATLAB compatibility.
5971
5972        • ‘createThumbnail’ — Not supported, only for MATLAB
5973          compatibility.
5974
5975        • ‘figureSnapMethod’ — Not supported, only for MATLAB
5976          compatibility.
5977
5978        • ‘imageFormat’ — Desired format for any images produced while
5979          evaluating the code.  The allowed image formats depend on the
5980          output format:
5981
5982             • ‘html’, ‘xml’ — ‘png’ (default), any image format
5983               supported by Octave
5984
5985             • ‘latex’ — ‘epsc2’ (default), any image format supported
5986               by Octave
5987
5988             • ‘pdf’ — ‘jpg’ (default) or ‘bmp’, note MATLAB uses ‘bmp’
5989               as default
5990
5991             • ‘doc’ or ‘ppt’ — ‘png’ (default), ‘jpg’, ‘bmp’, or ‘tiff’
5992
5993        • ‘maxWidth’ and ‘maxHeight’ — Maximum width (height) of the
5994          produced images in pixels.  An empty value means no
5995          restriction.  Both values must be set in order for the option
5996          to work properly.
5997
5998          ‘[]’ (default), integer value ≥ 0
5999
6000        • ‘useNewFigure’ — Use a new figure window for figures created
6001          by the evaluated code.  This avoids side effects with already
6002          opened figure windows.
6003
6004          ‘true’ (default) or ‘false’
6005
6006        • ‘evalCode’ — Evaluate code of the Octave source file
6007
6008          ‘true’ (default) or ‘false’
6009
6010        • ‘catchError’ — Catch errors while evaluating code and continue
6011
6012          ‘true’ (default) or ‘false’
6013
6014        • ‘codeToEvaluate’ — Octave commands that should be evaluated
6015          prior to publishing the script file.  These Octave commands do
6016          not appear in the generated report.
6017
6018        • ‘maxOutputLines’ — Maximum number of output lines from code
6019          evaluation which are included in output.
6020
6021          ‘Inf’ (default) or integer value > 0
6022
6023        • ‘showCode’ — Show the evaluated Octave commands in the
6024          generated report
6025
6026          ‘true’ (default) or ‘false’
6027
6028     The option output OUTPUT_FILE is a string with path and file name
6029     of the generated report.
6030
6031     See also: *note grabcode: XREFgrabcode.
6032
6033   The counterpart to ‘publish’ is ‘grabcode’:
6034
6035 -- : grabcode (URL)
6036 -- : grabcode (FILENAME)
6037 -- : CODE_STR = grabcode (...)
6038
6039     Grab the code from a report created by the ‘publish’ function.
6040
6041     The grabbed code inside the published report must be enclosed by
6042     the strings ‘##### SOURCE BEGIN #####’ and ‘##### SOURCE END
6043     #####’.  The ‘publish’ function creates this format automatically.
6044
6045     If no return value is requested the code is saved to a temporary
6046     file and opened in the default editor.  NOTE: The temporary file
6047     must be saved under a new or the code will be lost.
6048
6049     If an output is requested the grabbed code will be returned as
6050     string CODE_STR.
6051
6052     Example:
6053
6054          publish ("my_script.m");
6055          grabcode ("html/my_script.html");
6056
6057     The example above publishes ‘my_script.m’ to the default location
6058html/my_script.html’.  Next, the published Octave script is
6059     grabbed to edit its content in a new temporary file.
6060
6061     See also: *note publish: XREFpublish.
6062
6063
6064File: octave.info,  Node: Publishing Markup,  Prev: Publish Octave Script Files,  Up: Script Files
6065
606611.11.2 Publishing Markup
6067-------------------------
6068
6069* Menu:
6070
6071* Using Publishing Markup in Script Files::
6072* Text Formatting::
6073* Sections::
6074* Preformatted Code::
6075* Preformatted Text::
6076* Bulleted Lists::
6077* Numbered Lists::
6078* Including File Content::
6079* Including Graphics::
6080* Including URLs::
6081* Mathematical Equations::
6082* HTML Markup::
6083* LaTeX Markup::
6084
6085
6086File: octave.info,  Node: Using Publishing Markup in Script Files,  Next: Text Formatting,  Up: Publishing Markup
6087
608811.11.2.1 Using Publishing Markup in Script Files
6089.................................................
6090
6091To use Publishing Markup, start by typing ‘##’ or ‘%%’ at the beginning
6092of a new line.  For MATLAB compatibility ‘%%%’ is treated the same way
6093as ‘%%’.
6094
6095   The lines following ‘##’ or ‘%%’ start with one of either ‘#’ or ‘%’
6096followed by at least one space.  These lines are interpreted as section.
6097A section ends at the first line not starting with ‘#’ or ‘%’, or when
6098the end of the document is reached.
6099
6100   A section starting in the first line of the document, followed by
6101another start of a section that might be empty, is interpreted as a
6102document title and introduction text.
6103
6104   See the example below for clarity:
6105
6106     %% Headline title
6107     %
6108     % Some *bold*, _italic_, or |monospaced| Text with
6109     % a <https://www.octave.org link to GNU Octave>.
6110     %%
6111
6112     # "Real" Octave commands to be evaluated
6113     sombrero ()
6114
6115     ## Octave comment style supported as well
6116     #
6117     # * Bulleted list item 1
6118     # * Bulleted list item 2
6119     #
6120     # # Numbered list item 1
6121     # # Numbered list item 2
6122
6123
6124File: octave.info,  Node: Text Formatting,  Next: Sections,  Prev: Using Publishing Markup in Script Files,  Up: Publishing Markup
6125
612611.11.2.2 Text Formatting
6127.........................
6128
6129Basic text formatting is supported inside sections, see the example
6130given below:
6131
6132     ##
6133     # *bold*, _italic_, or |monospaced| Text
6134
6135   Additionally two trademark symbols are supported, just embrace the
6136letters ‘TM’ or ‘R’.
6137
6138     ##
6139     # (TM) or (R)
6140
6141
6142File: octave.info,  Node: Sections,  Next: Preformatted Code,  Prev: Text Formatting,  Up: Publishing Markup
6143
614411.11.2.3 Sections
6145..................
6146
6147A section is started by typing ‘##’ or ‘%%’ at the beginning of a new
6148line.  A section title can be provided by writing it, separated by a
6149space, in the first line after ‘##’ or ‘%%’.  Without a section title,
6150the section is interpreted as a continuation of the previous section.
6151For MATLAB compatibility ‘%%%’ is treated the same way as ‘%%’.
6152
6153     some_code ();
6154
6155     ## Section 1
6156     #
6157     ## Section 2
6158
6159     some_code ();
6160
6161     ##
6162     # Still in section 2
6163
6164     some_code ();
6165
6166     %%% Section 3
6167     %
6168     %
6169
6170
6171File: octave.info,  Node: Preformatted Code,  Next: Preformatted Text,  Prev: Sections,  Up: Publishing Markup
6172
617311.11.2.4 Preformatted Code
6174...........................
6175
6176To write preformatted code inside a section, indent the code by three
6177spaces after ‘#’ at the beginning of each line and leave the lines above
6178and below the code blank, except for ‘#’ at the beginning of those
6179lines.
6180
6181     ##
6182     # This is a syntax highlighted for-loop:
6183     #
6184     #   for i = 1:5
6185     #     disp (i);
6186     #   endfor
6187     #
6188     # And more usual text.
6189
6190
6191File: octave.info,  Node: Preformatted Text,  Next: Bulleted Lists,  Prev: Preformatted Code,  Up: Publishing Markup
6192
619311.11.2.5 Preformatted Text
6194...........................
6195
6196To write preformatted text inside a section, indent the code by two
6197spaces after ‘#’ at the beginning of each line and leave the lines above
6198and below the preformatted text blank, except for ‘#’ at the beginning
6199of those lines.
6200
6201     ##
6202     # This following text is preformatted:
6203     #
6204     #  "To be, or not to be: that is the question:
6205     #  Whether 'tis nobler in the mind to suffer
6206     #  The slings and arrows of outrageous fortune,
6207     #  Or to take arms against a sea of troubles,
6208     #  And by opposing end them?  To die: to sleep;"
6209     #
6210     #  --"Hamlet" by W. Shakespeare
6211
6212
6213File: octave.info,  Node: Bulleted Lists,  Next: Numbered Lists,  Prev: Preformatted Text,  Up: Publishing Markup
6214
621511.11.2.6 Bulleted Lists
6216........................
6217
6218To create a bulleted list, type
6219
6220     ##
6221     #
6222     # * Bulleted list item 1
6223     # * Bulleted list item 2
6224     #
6225
6226to get output like
6227
6228   • Bulleted list item 1
6229
6230   • Bulleted list item 2
6231
6232   Notice the blank lines, except for the ‘#’ or ‘%’ before and after
6233the bulleted list!
6234
6235
6236File: octave.info,  Node: Numbered Lists,  Next: Including File Content,  Prev: Bulleted Lists,  Up: Publishing Markup
6237
623811.11.2.7 Numbered Lists
6239........................
6240
6241To create a numbered list, type
6242
6243     ##
6244     #
6245     # # Numbered list item 1
6246     # # Numbered list item 2
6247     #
6248
6249to get output like
6250
6251  1. Numbered list item 1
6252
6253  2. Numbered list item 2
6254
6255   Notice the blank lines, except for the ‘#’ or ‘%’ before and after
6256the numbered list!
6257
6258
6259File: octave.info,  Node: Including File Content,  Next: Including Graphics,  Prev: Numbered Lists,  Up: Publishing Markup
6260
626111.11.2.8 Including File Content
6262................................
6263
6264To include the content of an external file, e.g., a file called
6265my_function.m’ at the same location as the published Octave script, use
6266the following syntax to include it with Octave syntax highlighting.
6267
6268   Alternatively, you can write the full or relative path to the file.
6269
6270     ##
6271     #
6272     # <include>my_function.m</include>
6273     #
6274     # <include>/full/path/to/my_function.m</include>
6275     #
6276     # <include>../relative/path/to/my_function.m</include>
6277     #
6278
6279
6280File: octave.info,  Node: Including Graphics,  Next: Including URLs,  Prev: Including File Content,  Up: Publishing Markup
6281
628211.11.2.9 Including Graphics
6283............................
6284
6285To include external graphics, e.g., a graphic called ‘my_graphic.png’ at
6286the same location as the published Octave script, use the following
6287syntax.
6288
6289   Alternatively, you can write the full path to the graphic.
6290
6291     ##
6292     #
6293     # <<my_graphic.png>>
6294     #
6295     # <</full/path/to/my_graphic.png>>
6296     #
6297     # <<../relative/path/to/my_graphic.png>>
6298     #
6299
6300
6301File: octave.info,  Node: Including URLs,  Next: Mathematical Equations,  Prev: Including Graphics,  Up: Publishing Markup
6302
630311.11.2.10 Including URLs
6304.........................
6305
6306Basically, a URL is written between an opening ‘<’ and a closing ‘>’
6307angle.
6308
6309     ##
6310     # <https://www.octave.org>
6311
6312   Text that is within these angles and separated by at least one space
6313from the URL is a displayed text for the link.
6314
6315     ##
6316     # <https://www.octave.org GNU Octave>
6317
6318   A link starting with ‘<octave:’ followed by the name of a GNU Octave
6319function, optionally with a displayed text, results in a link to the
6320online GNU Octave documentations function index.
6321
6322     ##
6323     # <octave:DISP The display function>
6324
6325
6326File: octave.info,  Node: Mathematical Equations,  Next: HTML Markup,  Prev: Including URLs,  Up: Publishing Markup
6327
632811.11.2.11 Mathematical Equations
6329.................................
6330
6331One can insert LaTeX inline math, surrounded by single ‘$’ signs, or
6332displayed math, surrounded by double ‘$$’ signs, directly inside
6333sections.
6334
6335     ##
6336     # Some shorter inline equation $e^{ix} = \cos x + i\sin x$.
6337     #
6338     # Or more complicated formulas as displayed math:
6339     # $$e^x = \lim_{n\rightarrow\infty}\left(1+\dfrac{x}{n}\right)^{n}.$$
6340
6341
6342File: octave.info,  Node: HTML Markup,  Next: LaTeX Markup,  Prev: Mathematical Equations,  Up: Publishing Markup
6343
634411.11.2.12 HTML Markup
6345......................
6346
6347If the published output is a HTML report, you can insert HTML markup,
6348that is only visible in this kind of output.
6349
6350     ##
6351     # <html>
6352     # <table style="border:1px solid black;">
6353     # <tr><td>1</td><td>2</td></tr>
6354     # <tr><td>3</td><td>3</td></tr>
6355     # </html>
6356
6357
6358File: octave.info,  Node: LaTeX Markup,  Prev: HTML Markup,  Up: Publishing Markup
6359
636011.11.2.13 LaTeX Markup
6361.......................
6362
6363If the published output is a LaTeX or PDF report, you can insert LaTeX
6364markup, that is only visible in this kind of output.
6365
6366     ##
6367     # <latex>
6368     # Some output only visible in LaTeX or PDF reports.
6369     # \begin{equation}
6370     # e^x = \lim\limits_{n\rightarrow\infty}\left(1+\dfrac{x}{n}\right)^{n}
6371     # \end{equation}
6372     # </latex>
6373
6374
6375File: octave.info,  Node: Function Handles and Anonymous Functions,  Next: Command Syntax and Function Syntax,  Prev: Script Files,  Up: Functions and Scripts
6376
637711.12 Function Handles and Anonymous Functions
6378==============================================
6379
6380It can be very convenient store a function in a variable so that it can
6381be passed to a different function.  For example, a function that
6382performs numerical minimization needs access to the function that should
6383be minimized.
6384
6385* Menu:
6386
6387* Function Handles::
6388* Anonymous Functions::
6389
6390
6391File: octave.info,  Node: Function Handles,  Next: Anonymous Functions,  Up: Function Handles and Anonymous Functions
6392
639311.12.1 Function Handles
6394------------------------
6395
6396A function handle is a pointer to another function and is defined with
6397the syntax
6398
6399     @FUNCTION-NAME
6400
6401For example,
6402
6403     f = @sin;
6404
6405creates a function handle called ‘f’ that refers to the function ‘sin’.
6406
6407   Function handles are used to call other functions indirectly, or to
6408pass a function as an argument to another function like ‘quad’ or
6409‘fsolve’.  For example:
6410
6411     f = @sin;
6412     quad (f, 0, pi)
6413         ⇒ 2
6414
6415   You may use ‘feval’ to call a function using function handle, or
6416simply write the name of the function handle followed by an argument
6417list.  If there are no arguments, you must use an empty argument list
6418‘()’.  For example:
6419
6420     f = @sin;
6421     feval (f, pi/4)
6422         ⇒ 0.70711
6423     f (pi/4)
6424         ⇒ 0.70711
6425
6426 -- : is_function_handle (X)
6427     Return true if X is a function handle.
6428
6429     See also: *note isa: XREFisa, *note typeinfo: XREFtypeinfo, *note
6430     class: XREFclass, *note functions: XREFfunctions.
6431
6432 -- : S = functions (FCN_HANDLE)
6433     Return a structure containing information about the function handle
6434     FCN_HANDLE.
6435
6436     The structure S always contains these three fields:
6437
6438     function
6439          The function name.  For an anonymous function (no name) this
6440          will be the actual function definition.
6441
6442     type
6443          Type of the function.
6444
6445          anonymous
6446               The function is anonymous.
6447
6448          private
6449               The function is private.
6450
6451          overloaded
6452               The function overloads an existing function.
6453
6454          simple
6455               The function is a built-in or m-file function.
6456
6457          subfunction
6458               The function is a subfunction within an m-file.
6459
6460     nested
6461          The function is nested.
6462
6463     file
6464          The m-file that will be called to perform the function.  This
6465          field is empty for anonymous and built-in functions.
6466
6467     In addition, some function types may return more information in
6468     additional fields.
6469
6470     *Warning:* ‘functions’ is provided for debugging purposes only.
6471     Its behavior may change in the future and programs should not
6472     depend on any particular output format.
6473
6474     See also: *note func2str: XREFfunc2str, *note str2func:
6475     XREFstr2func.
6476
6477 -- : func2str (FCN_HANDLE)
6478     Return a string containing the name of the function referenced by
6479     the function handle FCN_HANDLE.
6480
6481     See also: *note str2func: XREFstr2func, *note functions:
6482     XREFfunctions.
6483
6484 -- : str2func (FCN_NAME)
6485     Return a function handle constructed from the string FCN_NAME.
6486
6487     Previous versions of Octave accepted an optional second argument,
6488     "global", that caused str2func to ignore locally visible functions.
6489     This option is no longer supported.
6490
6491     See also: *note func2str: XREFfunc2str, *note functions:
6492     XREFfunctions.
6493
6494
6495File: octave.info,  Node: Anonymous Functions,  Prev: Function Handles,  Up: Function Handles and Anonymous Functions
6496
649711.12.2 Anonymous Functions
6498---------------------------
6499
6500Anonymous functions are defined using the syntax
6501
6502     @(ARGUMENT-LIST) EXPRESSION
6503
6504Any variables that are not found in the argument list are inherited from
6505the enclosing scope.  Anonymous functions are useful for creating simple
6506unnamed functions from expressions or for wrapping calls to other
6507functions to adapt them for use by functions like ‘quad’.  For example,
6508
6509     f = @(x) x.^2;
6510     quad (f, 0, 10)
6511         ⇒ 333.33
6512
6513creates a simple unnamed function from the expression ‘x.^2’ and passes
6514it to ‘quad’,
6515
6516     quad (@(x) sin (x), 0, pi)
6517         ⇒ 2
6518
6519wraps another function, and
6520
6521     a = 1;
6522     b = 2;
6523     quad (@(x) betainc (x, a, b), 0, 0.4)
6524         ⇒ 0.13867
6525
6526adapts a function with several parameters to the form required by
6527‘quad’.  In this example, the values of A and B that are passed to
6528‘betainc’ are inherited from the current environment.
6529
6530   Note that for performance reasons it is better to use handles to
6531existing Octave functions, rather than to define anonymous functions
6532which wrap an existing function.  The integration of ‘sin (x)’ is 5X
6533faster if the code is written as
6534
6535     quad (@sin, 0, pi)
6536
6537rather than using the anonymous function ‘@(x) sin (x)’.  There are many
6538operators which have functional equivalents that may be better choices
6539than an anonymous function.  Instead of writing
6540
6541     f = @(x, y) x + y
6542
6543this should be coded as
6544
6545     f = @plus
6546
6547   *Note Operator Overloading::, for a list of operators which also have
6548a functional form.
6549
6550
6551File: octave.info,  Node: Command Syntax and Function Syntax,  Next: Organization of Functions,  Prev: Function Handles and Anonymous Functions,  Up: Functions and Scripts
6552
655311.13 Command Syntax and Function Syntax
6554========================================
6555
6556Additionally to the function syntax described above (i.e., calling a
6557function like ‘fun (arg1, arg2, ...)’), a function can be called using
6558command syntax (for example, calling a function like ‘fun arg1 arg2
6559...’).  In that case, all arguments are passed to the function as
6560strings.  For example,
6561
6562     my_command hello world
6563
6564is equivalent to
6565
6566     my_command ("hello", "world")
6567
6568The general form of a command call is
6569
6570     cmdname arg1 arg2 ...
6571
6572which translates directly to
6573
6574     cmdname ("arg1", "arg2", ...)
6575
6576   If an argument including spaces should be passed to a function in
6577command syntax, (double-)quotes can be used.  For example,
6578
6579     my_command "first argument" "second argument"
6580
6581is equivalent to
6582
6583     my_command ("first argument", "second argument")
6584
6585   Any function can be used as a command if it accepts string input
6586arguments.  For example:
6587
6588     toupper lower_case_arg
6589        ⇒ ans = LOWER_CASE_ARG
6590
6591   Since the arguments are passed as strings to the corresponding
6592function, it is not possible to pass input arguments that are stored in
6593variables.  In that case, a command must be called using the function
6594syntax.  For example:
6595
6596     strvar = "hello world";
6597     toupper strvar
6598        ⇒ ans = STRVAR
6599     toupper (strvar)
6600        ⇒ ans = HELLO WORLD
6601
6602   Additionally, the return values of functions cannot be assigned to
6603variables using the command syntax.  Only the first return argument is
6604assigned to the built-in variable ‘ans’.  If the output argument of a
6605command should be assigned to a variable, or multiple output arguments
6606of a function should be returned, the function syntax must be used.
6607
6608
6609File: octave.info,  Node: Organization of Functions,  Prev: Command Syntax and Function Syntax,  Up: Functions and Scripts
6610
661111.14 Organization of Functions Distributed with Octave
6612=======================================================
6613
6614Many of Octave’s standard functions are distributed as function files.
6615They are loosely organized by topic, in subdirectories of
6616OCTAVE-HOME/share/octave/VERSION/m’, to make it easier to find them.
6617
6618   The following is a list of all the function file subdirectories, and
6619the types of functions you will find there.
6620
6621‘@ftp’
6622     Class functions for the FTP object.
6623
6624‘+containers’
6625     Package for the containers classes.
6626
6627‘audio’
6628     Functions for playing and recording sounds.
6629
6630‘deprecated’
6631     Out-of-date functions which will eventually be removed from Octave.
6632
6633‘elfun’
6634     Elementary functions, principally trigonometric.
6635
6636‘general’
6637     Miscellaneous matrix manipulations, like ‘flipud’, ‘rot90’, and
6638     ‘triu’, as well as other basic functions, like ‘ismatrix’,
6639     ‘narginchk’, etc.
6640
6641‘geometry’
6642     Functions related to Delaunay triangulation.
6643
6644‘gui’
6645     Functions for GUI elements like dialog, message box, etc.
6646
6647‘help’
6648     Functions for Octave’s built-in help system.
6649
6650‘image’
6651     Image processing tools.  These functions require the X Window
6652     System.
6653
6654‘io’
6655     Input-output functions.
6656
6657‘java’
6658     Functions related to the Java integration.
6659
6660‘linear-algebra’
6661     Functions for linear algebra.
6662
6663‘miscellaneous’
6664     Functions that don’t really belong anywhere else.
6665
6666‘ode’
6667     Functions to solve ordinary differential equations (ODEs).
6668
6669‘optimization’
6670     Functions related to minimization, optimization, and root finding.
6671
6672‘path’
6673     Functions to manage the directory path Octave uses to find
6674     functions.
6675
6676‘pkg’
6677     Package manager for installing external packages of functions in
6678     Octave.
6679
6680‘plot’
6681     Functions for displaying and printing two- and three-dimensional
6682     graphs.
6683
6684‘polynomial’
6685     Functions for manipulating polynomials.
6686
6687‘prefs’
6688     Functions implementing user-defined preferences.
6689
6690‘set’
6691     Functions for creating and manipulating sets of unique values.
6692
6693‘signal’
6694     Functions for signal processing applications.
6695
6696‘sparse’
6697     Functions for handling sparse matrices.
6698
6699‘specfun’
6700     Special functions such as ‘bessel’ or ‘factor’.
6701
6702‘special-matrix’
6703     Functions that create special matrix forms such as Hilbert or
6704     Vandermonde matrices.
6705
6706‘startup’
6707     Octave’s system-wide startup file.
6708
6709‘statistics’
6710     Statistical functions.
6711
6712‘strings’
6713     Miscellaneous string-handling functions.
6714
6715‘testfun’
6716     Functions for performing unit tests on other functions.
6717
6718‘time’
6719     Functions related to time and date processing.
6720
6721
6722File: octave.info,  Node: Errors and Warnings,  Next: Debugging,  Prev: Functions and Scripts,  Up: Top
6723
672412 Errors and Warnings
6725**********************
6726
6727Octave includes several functions for printing error and warning
6728messages.  When you write functions that need to take special action
6729when they encounter abnormal conditions, you should print the error
6730messages using the functions described in this chapter.
6731
6732   Since many of Octave’s functions use these functions, it is also
6733useful to understand them, so that errors and warnings can be handled.
6734
6735* Menu:
6736
6737* Handling Errors::
6738* Handling Warnings::
6739
6740
6741File: octave.info,  Node: Handling Errors,  Next: Handling Warnings,  Up: Errors and Warnings
6742
674312.1 Handling Errors
6744====================
6745
6746An error is something that occurs when a program is in a state where it
6747doesn’t make sense to continue.  An example is when a function is called
6748with too few input arguments.  In this situation the function should
6749abort with an error message informing the user of the lacking input
6750arguments.
6751
6752   Since an error can occur during the evaluation of a program, it is
6753very convenient to be able to detect that an error occurred, so that the
6754error can be fixed.  This is possible with the ‘try’ statement described
6755in *note The try Statement::.
6756
6757* Menu:
6758
6759* Raising Errors::
6760* Catching Errors::
6761* Recovering From Errors::
6762
6763
6764File: octave.info,  Node: Raising Errors,  Next: Catching Errors,  Up: Handling Errors
6765
676612.1.1 Raising Errors
6767---------------------
6768
6769The most common use of errors is for checking input arguments to
6770functions.  The following example calls the ‘error’ function if the
6771function ‘f’ is called without any input arguments.
6772
6773     function f (arg1)
6774       if (nargin == 0)
6775         error ("not enough input arguments");
6776       endif
6777     endfunction
6778
6779   When the ‘error’ function is called, it prints the given message and
6780returns to the Octave prompt.  This means that no code following a call
6781to ‘error’ will be executed.
6782
6783   It is also possible to assign an identification string to an error.
6784If an error has such an ID the user can catch this error as will be
6785described in the next section.  To assign an ID to an error, simply call
6786‘error’ with two string arguments, where the first is the identification
6787string, and the second is the actual error.  Note that error IDs are in
6788the format "NAMESPACE:ERROR-NAME". The namespace "Octave" is used for
6789Octave’s own errors.  Any other string is available as a namespace for
6790user’s own errors.
6791
6792 -- : error (TEMPLATE, ...)
6793 -- : error (ID, TEMPLATE, ...)
6794     Display an error message and stop m-file execution.
6795
6796     Format the optional arguments under the control of the template
6797     string TEMPLATE using the same rules as the ‘printf’ family of
6798     functions (*note Formatted Output::) and print the resulting
6799     message on the ‘stderr’ stream.  The message is prefixed by the
6800     character string ‘error: ’.
6801
6802     Calling ‘error’ also sets Octave’s internal error state such that
6803     control will return to the top level without evaluating any further
6804     commands.  This is useful for aborting from functions or scripts.
6805
6806     If the error message does not end with a newline character, Octave
6807     will print a traceback of all the function calls leading to the
6808     error.  For example, given the following function definitions:
6809
6810          function f () g (); end
6811          function g () h (); end
6812          function h () nargin == 1 || error ("nargin != 1"); end
6813
6814     calling the function ‘f’ will result in a list of messages that can
6815     help you to quickly find the exact location of the error:
6816
6817          f ()
6818          error: nargin != 1
6819          error: called from:
6820          error:   h at line 1, column 27
6821          error:   g at line 1, column 15
6822          error:   f at line 1, column 15
6823
6824     If the error message ends in a newline character, Octave will print
6825     the message but will not display any traceback messages as it
6826     returns control to the top level.  For example, modifying the error
6827     message in the previous example to end in a newline causes Octave
6828     to only print a single message:
6829
6830          function h () nargin == 1 || error ("nargin != 1\n"); end
6831          f ()
6832          error: nargin != 1
6833
6834     A null string ("") input to ‘error’ will be ignored and the code
6835     will continue running as if the statement were a NOP.  This is for
6836     compatibility with MATLAB.  It also makes it possible to write code
6837     such as
6838
6839          err_msg = "";
6840          if (CONDITION 1)
6841            err_msg = "CONDITION 1 found";
6842          elseif (CONDITION2)
6843            err_msg = "CONDITION 2 found";
6844          ...
6845          endif
6846          error (err_msg);
6847
6848     which will only stop execution if an error has been found.
6849
6850     Implementation Note: For compatibility with MATLAB, escape
6851     sequences in TEMPLATE (e.g., "\n" => newline) are processed
6852     regardless of whether TEMPLATE has been defined with single quotes,
6853     as long as there are two or more input arguments.  To disable
6854     escape sequence expansion use a second backslash before the
6855     sequence (e.g., "\\n") or use the ‘regexptranslate’ function.
6856
6857     See also: *note warning: XREFwarning, *note lasterror:
6858     XREFlasterror.
6859
6860   Since it is common to use errors when there is something wrong with
6861the input to a function, Octave supports functions to simplify such
6862code.  When the ‘print_usage’ function is called, it reads the help text
6863of the function calling ‘print_usage’, and presents a useful error.  If
6864the help text is written in Texinfo it is possible to present an error
6865message that only contains the function prototypes as described by the
6866‘@deftypefn’ parts of the help text.  When the help text isn’t written
6867in Texinfo, the error message contains the entire help message.
6868
6869   Consider the following function.
6870
6871     ## -*- texinfo -*-
6872     ## @deftypefn {} f (@var{arg1})
6873     ## Function help text goes here...
6874     ## @end deftypefn
6875     function f (arg1)
6876       if (nargin == 0)
6877         print_usage ();
6878       endif
6879     endfunction
6880
6881When it is called with no input arguments it produces the following
6882error.
6883
6884     f ()
6885
6886     ⊣  error: Invalid call to f.  Correct usage is:
68876888     ⊣   -- f (ARG1)
688968906891     ⊣  Additional help for built-in functions and operators is
6892     ⊣  available in the online version of the manual.  Use the command
6893     ⊣  'doc <topic>' to search the manual index.
68946895     ⊣  Help and information about Octave is also available on the WWW
6896     ⊣  at https://www.octave.org and via the help@octave.org
6897     ⊣  mailing list.
6898
6899 -- : print_usage ()
6900 -- : print_usage (NAME)
6901     Print the usage message for the function NAME.
6902
6903     When called with no input arguments the ‘print_usage’ function
6904     displays the usage message of the currently executing function.
6905
6906     See also: *note help: XREFhelp.
6907
6908 -- : beep ()
6909     Produce a beep from the speaker (or visual bell).
6910
6911     This function sends the alarm character "\a" to the terminal.
6912     Depending on the user’s configuration this may produce an audible
6913     beep, a visual bell, or nothing at all.
6914
6915     See also: *note puts: XREFputs, *note fputs: XREFfputs, *note
6916     printf: XREFprintf, *note fprintf: XREFfprintf.
6917
6918 -- : VAL = beep_on_error ()
6919 -- : OLD_VAL = beep_on_error (NEW_VAL)
6920 -- : beep_on_error (NEW_VAL, "local")
6921     Query or set the internal variable that controls whether Octave
6922     will try to ring the terminal bell before printing an error
6923     message.
6924
6925     When called from inside a function with the "local" option, the
6926     variable is changed locally for the function and any subroutines it
6927     calls.  The original variable value is restored when exiting the
6928     function.
6929
6930
6931File: octave.info,  Node: Catching Errors,  Next: Recovering From Errors,  Prev: Raising Errors,  Up: Handling Errors
6932
693312.1.2 Catching Errors
6934----------------------
6935
6936When an error occurs, it can be detected and handled using the ‘try’
6937statement as described in *note The try Statement::.  As an example, the
6938following piece of code counts the number of errors that occurs during a
6939‘for’ loop.
6940
6941     number_of_errors = 0;
6942     for n = 1:100
6943       try
6944         ...
6945       catch
6946         number_of_errors++;
6947       end_try_catch
6948     endfor
6949
6950   The above example treats all errors the same.  In many situations it
6951can however be necessary to discriminate between errors, and take
6952different actions depending on the error.  The ‘lasterror’ function
6953returns a structure containing information about the last error that
6954occurred.  As an example, the code above could be changed to count the
6955number of errors related to the ‘*’ operator.
6956
6957     number_of_errors = 0;
6958     for n = 1:100
6959       try
6960         ...
6961       catch
6962         msg = lasterror.message;
6963         if (strfind (msg, "operator *"))
6964           number_of_errors++;
6965         endif
6966       end_try_catch
6967     endfor
6968
6969Alternatively, the output of the ‘lasterror’ function can be found in a
6970variable indicated immediately after the ‘catch’ keyword, as in the
6971example below showing how to redirect an error as a warning:
6972
6973     try
6974       ...
6975     catch err
6976       warning(err.identifier, err.message);
6977       ...
6978     end_try_catch
6979
6980 -- : LASTERR = lasterror ()
6981 -- : lasterror (ERR)
6982 -- : lasterror ("reset")
6983     Query or set the last error message structure.
6984
6985     When called without arguments, return a structure containing the
6986     last error message and other information related to this error.
6987     The elements of the structure are:
6988
6989     ‘message’
6990          The text of the last error message
6991
6992     ‘identifier’
6993          The message identifier of this error message
6994
6995     ‘stack’
6996          A structure containing information on where the message
6997          occurred.  This may be an empty structure if the information
6998          cannot be obtained.  The fields of the structure are:
6999
7000          ‘file’
7001               The name of the file where the error occurred
7002
7003          ‘name’
7004               The name of function in which the error occurred
7005
7006          ‘line’
7007               The line number at which the error occurred
7008
7009          ‘column’
7010               An optional field with the column number at which the
7011               error occurred
7012
7013     The last error structure may be set by passing a scalar structure,
7014     ERR, as input.  Any fields of ERR that match those above are set
7015     while any unspecified fields are initialized with default values.
7016
7017     If ‘lasterror’ is called with the argument "reset", all fields are
7018     set to their default values.
7019
7020     See also: *note lasterr: XREFlasterr, *note error: XREFerror, *note
7021     lastwarn: XREFlastwarn.
7022
7023 -- : [MSG, MSGID] = lasterr ()
7024 -- : lasterr (MSG)
7025 -- : lasterr (MSG, MSGID)
7026     Query or set the last error message.
7027
7028     When called without input arguments, return the last error message
7029     and message identifier.
7030
7031     With one argument, set the last error message to MSG.
7032
7033     With two arguments, also set the last message identifier.
7034
7035     See also: *note lasterror: XREFlasterror, *note error: XREFerror,
7036     *note lastwarn: XREFlastwarn.
7037
7038   The next example counts indexing errors.  The errors are caught using
7039the field identifier of the structure returned by the function
7040‘lasterror’.
7041
7042     number_of_errors = 0;
7043     for n = 1:100
7044       try
7045         ...
7046       catch
7047         id = lasterror.identifier;
7048         if (strcmp (id, "Octave:invalid-indexing"))
7049           number_of_errors++;
7050         endif
7051       end_try_catch
7052     endfor
7053
7054   The functions distributed with Octave can issue one of the following
7055errors.
7056
7057‘Octave:bad-alloc’
7058     Indicates that memory couldn’t be allocated.
7059
7060‘Octave:invalid-context’
7061     Indicates the error was generated by an operation that cannot be
7062     executed in the scope from which it was called.  For example, the
7063     function ‘print_usage ()’ when called from the Octave prompt raises
7064     this error.
7065
7066‘Octave:invalid-fun-call’
7067     Indicates that a function was called in an incorrect way, e.g.,
7068     wrong number of input arguments.
7069
7070‘Octave:invalid-indexing’
7071     Indicates that a data-type was indexed incorrectly, e.g.,
7072     real-value index for arrays, nonexistent field of a structure.
7073
7074‘Octave:invalid-input-arg’
7075     Indicates that a function was called with invalid input arguments.
7076
7077‘Octave:undefined-function’
7078     Indicates a call to a function that is not defined.  The function
7079     may exist but Octave is unable to find it in the search path.
7080
7081   When an error has been handled it is possible to raise it again.
7082This can be useful when an error needs to be detected, but the program
7083should still abort.  This is possible using the ‘rethrow’ function.  The
7084previous example can now be changed to count the number of errors
7085related to the ‘*’ operator, but still abort if another kind of error
7086occurs.
7087
7088     number_of_errors = 0;
7089     for n = 1:100
7090       try
7091         ...
7092       catch
7093         msg = lasterror.message;
7094         if (strfind (msg, "operator *"))
7095           number_of_errors++;
7096         else
7097           rethrow (lasterror);
7098         endif
7099       end_try_catch
7100     endfor
7101
7102 -- : rethrow (ERR)
7103     Reissue a previous error as defined by ERR.
7104
7105     ERR is a structure that must contain at least the "message" and
7106     "identifier" fields.  ERR can also contain a field "stack" that
7107     gives information on the assumed location of the error.  Typically
7108     ERR is returned from ‘lasterror’.
7109
7110     See also: *note lasterror: XREFlasterror, *note lasterr:
7111     XREFlasterr, *note error: XREFerror.
7112
7113 -- : ERR = errno ()
7114 -- : ERR = errno (VAL)
7115 -- : ERR = errno (NAME)
7116     Query or set the system-dependent variable errno.
7117
7118     When called with no inputs, return the current value of errno.
7119
7120     When called with a numeric input VAL, set the current value of
7121     errno to the specified value.  The previous value of errno is
7122     returned as ERR.
7123
7124     When called with a character string NAME, return the numeric value
7125     of errno which corresponds to the specified error code.  If NAME is
7126     not a recognized error code then -1 is returned.
7127
7128     See also: *note errno_list: XREFerrno_list.
7129
7130 -- : errno_list ()
7131     Return a structure containing the system-dependent errno values.
7132
7133     See also: *note errno: XREFerrno.
7134
7135
7136File: octave.info,  Node: Recovering From Errors,  Prev: Catching Errors,  Up: Handling Errors
7137
713812.1.3 Recovering From Errors
7139-----------------------------
7140
7141Octave provides several ways of recovering from errors.  There are
7142‘try’/‘catch’ blocks, ‘unwind_protect’/‘unwind_protect_cleanup’ blocks,
7143and finally the ‘onCleanup’ command.
7144
7145   The ‘onCleanup’ command associates an ordinary Octave variable (the
7146trigger) with an arbitrary function (the action).  Whenever the Octave
7147variable ceases to exist—whether due to a function return, an error, or
7148simply because the variable has been removed with ‘clear’—then the
7149assigned function is executed.
7150
7151   The function can do anything necessary for cleanup such as closing
7152open file handles, printing an error message, or restoring global
7153variables to their initial values.  The last example is a very
7154convenient idiom for Octave code.  For example:
7155
7156     function rand42
7157       old_state = rand ("state");
7158       restore_state = onCleanup (@() rand ("state", old_state));
7159       rand ("state", 42);
7160       ...
7161     endfunction  # rand generator state restored by onCleanup
7162
7163 -- : OBJ = onCleanup (FUNCTION)
7164     Create a special object that executes a given function upon
7165     destruction.
7166
7167     If the object is copied to multiple variables (or cell or struct
7168     array elements) or returned from a function, FUNCTION will be
7169     executed after clearing the last copy of the object.  Note that if
7170     multiple local onCleanup variables are created, the order in which
7171     they are called is unspecified.  For similar functionality *Note
7172     The unwind_protect Statement::.
7173
7174
7175File: octave.info,  Node: Handling Warnings,  Prev: Handling Errors,  Up: Errors and Warnings
7176
717712.2 Handling Warnings
7178======================
7179
7180Like an error, a warning is issued when something unexpected happens.
7181Unlike an error, a warning doesn’t abort the currently running program.
7182A simple example of a warning is when a number is divided by zero.  In
7183this case Octave will issue a warning and assign the value ‘Inf’ to the
7184result.
7185
7186     a = 1/0
7187          ⊣ warning: division by zero
7188          ⇒ a = Inf
7189
7190* Menu:
7191
7192* Issuing Warnings::
7193* Enabling and Disabling Warnings::
7194
7195
7196File: octave.info,  Node: Issuing Warnings,  Next: Enabling and Disabling Warnings,  Up: Handling Warnings
7197
719812.2.1 Issuing Warnings
7199-----------------------
7200
7201It is possible to issue warnings from any code using the ‘warning’
7202function.  In its most simple form, the ‘warning’ function takes a
7203string describing the warning as its input argument.  As an example, the
7204following code controls if the variable ‘a’ is non-negative, and if not
7205issues a warning and sets ‘a’ to zero.
7206
7207     a = -1;
7208     if (a < 0)
7209       warning ("'a' must be non-negative.  Setting 'a' to zero.");
7210       a = 0;
7211     endif
7212          ⊣ 'a' must be non-negative.  Setting 'a' to zero.
7213
7214   Since warnings aren’t fatal to a running program, it is not possible
7215to catch a warning using the ‘try’ statement or something similar.  It
7216is however possible to access the last warning as a string using the
7217‘lastwarn’ function.
7218
7219   It is also possible to assign an identification string to a warning.
7220If a warning has such an ID the user can enable and disable this warning
7221as will be described in the next section.  To assign an ID to a warning,
7222simply call ‘warning’ with two string arguments, where the first is the
7223identification string, and the second is the actual warning.  Note that
7224warning IDs are in the format "NAMESPACE:WARNING-NAME". The namespace
7225"Octave" is used for Octave’s own warnings.  Any other string is
7226available as a namespace for user’s own warnings.
7227
7228 -- : warning (TEMPLATE, ...)
7229 -- : warning (ID, TEMPLATE, ...)
7230 -- : warning ("on", ID)
7231 -- : warning ("off", ID)
7232 -- : warning ("error", ID)
7233 -- : warning ("query", ID)
7234 -- : warning (STATE, ID, "local")
7235 -- : warning (WARNING_STRUCT)
7236 -- : WARNING_STRUCT = warning (...)
7237 -- : warning (STATE, MODE)
7238
7239     Display a warning message or control the behavior of Octave’s
7240     warning system.
7241
7242     The first call form uses a template TEMPLATE and optional
7243     additional arguments to display a message on the ‘stderr’ stream.
7244     The message is formatted using the same rules as the ‘printf’
7245     family of functions (*note Formatted Output::) and prefixed by the
7246     character string ‘warning: ’.  You should use this function when
7247     you want to notify the user of an unusual condition, but only when
7248     it makes sense for your program to go on.  For example:
7249
7250          warning ("foo: maybe something wrong here");
7251
7252     If the warning message does not end with a newline character,
7253     Octave will print a traceback of all the function calls leading to
7254     the warning.  If the warning message does end in a newline
7255     character, Octave will suppress the traceback messages as it
7256     returns control to the top level.  For more details and examples,
7257     see *note error: XREFerror.
7258
7259     The optional warning identifier ID allows users to enable or
7260     disable warnings tagged by this identifier.  A message identifier
7261     is a string of the form "NAMESPACE:WARNING-NAME". Octave’s own
7262     warnings use the "Octave" namespace (*note warning_ids:
7263     XREFwarning_ids.).  For example:
7264
7265          warning ("MyNameSpace:check-something",
7266                   "foo: maybe something wrong here");
7267
7268     The second call form is meant to change and/or query the state of
7269     warnings.  The first input argument must be a string STATE ("on",
7270     "off", "error", or "query") followed by an optional warning
7271     identifier ID or "all" (default).
7272
7273     The optional output argument WARNING_STRUCT is a structure or
7274     structure array with fields "state" and "identifier".  The STATE
7275     argument may have the following values:
7276
7277     "on"|"off":
7278          Enable or disable the display of warnings identified by ID and
7279          optionally return their previous state STOUT.
7280
7281     "error":
7282          Turn warnings identified by ID into errors and optionally
7283          return their previous state STOUT.
7284
7285     "query":
7286          Return the current state of warnings identified by ID.
7287
7288     A structure or structure array WARNING_STRUCT, with fields "state"
7289     and "identifier", may be given as an input to achieve equivalent
7290     results.  The following example shows how to temporarily disable a
7291     warning and then restore its original state:
7292
7293          loglog (-1:10);
7294          ## Disable the previous warning and save its original state
7295          [~, id] = lastwarn ();
7296          warnstate = warning ("off", id);
7297          loglog (-1:10);
7298          ## Restore its original state
7299          warning (warnstate);
7300
7301     If a final argument "local" is provided then the warning state will
7302     be set temporarily until the end of the current function.  Changes
7303     to warning states that are set locally affect the current function
7304     and all functions called from the current scope.  The previous
7305     warning state is restored on return from the current function.  The
7306     "local" option is ignored if used in the top-level workspace.
7307
7308     With no input argument ‘warning ()’ is equivalent to ‘warning
7309     ("query", "all")’ except that in the absence of an output argument,
7310     the state of warnings is displayed on ‘stderr’.
7311
7312     The level of verbosity of the warning system may also be controlled
7313     by two modes MODE:
7314
7315     "backtrace":
7316          enable/disable the display of the stack trace after the
7317          warning message
7318
7319     "verbose":
7320          enable/disable the display of additional information after the
7321          warning message
7322
7323     In this case the STATE argument may only be "on" or "off".
7324
7325     Implementation Note: For compatibility with MATLAB, escape
7326     sequences in TEMPLATE (e.g., "\n" => newline) are processed
7327     regardless of whether TEMPLATE has been defined with single quotes,
7328     as long as there are two or more input arguments.  To disable
7329     escape sequence expansion use a second backslash before the
7330     sequence (e.g., "\\n") or use the ‘regexptranslate’ function.
7331
7332     See also: *note warning_ids: XREFwarning_ids, *note lastwarn:
7333     XREFlastwarn, *note error: XREFerror.
7334
7335 -- : [MSG, MSGID] = lastwarn ()
7336 -- : lastwarn (MSG)
7337 -- : lastwarn (MSG, MSGID)
7338     Query or set the last warning message.
7339
7340     When called without input arguments, return the last warning
7341     message and message identifier.
7342
7343     With one argument, set the last warning message to MSG.
7344
7345     With two arguments, also set the last message identifier.
7346
7347     See also: *note warning: XREFwarning, *note lasterror:
7348     XREFlasterror, *note lasterr: XREFlasterr.
7349
7350   The functions distributed with Octave can issue one of the following
7351warnings.
7352
7353‘Octave:abbreviated-property-match’
7354     By default, the ‘Octave:abbreviated-property-match’ warning is
7355     enabled.
7356
7357‘Octave:addpath-pkg’
7358     If the ‘Octave:addpath-pkg’ warning is enabled, Octave will warn
7359     when a package directory (i.e., +package_name) is added to the
7360     ‘path’.  Typically, only the parent directory which contains the
7361     package directory should be added to the load path.  By default,
7362     the ‘Octave:addpath-pkg’ warning is enabled.
7363
7364‘Octave:array-as-logical’
7365     If the ‘Octave:array-as-logical’ warning is enabled, Octave will
7366     warn when an array of size greater than 1x1 is used as a truth
7367     value in an if, while, or until statement.  By default, the
7368     ‘Octave:array-as-logical’ warning is disabled.
7369
7370‘Octave:array-to-scalar’
7371     If the ‘Octave:array-to-scalar’ warning is enabled, Octave will
7372     warn when an implicit conversion from an array to a scalar value is
7373     attempted.  By default, the ‘Octave:array-to-scalar’ warning is
7374     disabled.
7375
7376‘Octave:array-to-vector’
7377     If the ‘Octave:array-to-vector’ warning is enabled, Octave will
7378     warn when an implicit conversion from an array to a vector value is
7379     attempted.  By default, the ‘Octave:array-to-vector’ warning is
7380     disabled.
7381
7382‘Octave:assign-as-truth-value’
7383     If the ‘Octave:assign-as-truth-value’ warning is enabled, a warning
7384     is issued for statements like
7385
7386          if (s = t)
7387            ...
7388
7389     since such statements are not common, and it is likely that the
7390     intent was to write
7391
7392          if (s == t)
7393            ...
7394
7395     instead.
7396
7397     There are times when it is useful to write code that contains
7398     assignments within the condition of a ‘while’ or ‘if’ statement.
7399     For example, statements like
7400
7401          while (c = getc ())
7402            ...
7403
7404     are common in C programming.
7405
7406     It is possible to avoid all warnings about such statements by
7407     disabling the ‘Octave:assign-as-truth-value’ warning, but that may
7408     also let real errors like
7409
7410          if (x = 1)  # intended to test (x == 1)!
7411            ...
7412
7413     slip by.
7414
7415     In such cases, it is possible suppress errors for specific
7416     statements by writing them with an extra set of parentheses.  For
7417     example, writing the previous example as
7418
7419          while ((c = getc ()))
7420            ...
7421
7422     will prevent the warning from being printed for this statement,
7423     while allowing Octave to warn about other assignments used in
7424     conditional contexts.
7425
7426     By default, the ‘Octave:assign-as-truth-value’ warning is enabled.
7427
7428‘Octave:autoload-relative-file-name’
7429     If the ‘Octave:autoload-relative-file-name’ is enabled, Octave will
7430     warn when parsing autoload() function calls with relative paths to
7431     function files.  This usually happens when using autoload() calls
7432     in PKG_ADD files, when the PKG_ADD file is not in the same
7433     directory as the .oct file referred to by the autoload() command.
7434     By default, the ‘Octave:autoload-relative-file-name’ warning is
7435     enabled.
7436
7437‘Octave:built-in-variable-assignment’
7438     By default, the ‘Octave:built-in-variable-assignment’ warning is
7439     enabled.
7440
7441‘Octave:classdef-to-struct’
7442     If the ‘Octave:classdef-to-struct’ warning is enabled, a warning is
7443     issued when a classdef object is forcibly converted into a struct
7444     with ‘struct (CLASSDEF_OBJ)’.  Conversion removes the access
7445     restrictions from the object and makes private and protected
7446     properties visible.  By default, the ‘Octave:classdef-to-struct’
7447     warning is enabled.
7448
7449‘Octave:colon-complex-argument’
7450     If the ‘Octave:colon-complex-argument’ warning is enabled, a
7451     warning is issued when one of the three arguments to the colon
7452     operator (base, increment, limit) is a complex value.  For example,
7453     ‘1:3*i’ will cause a warning to be emitted.  By default, the
7454     ‘Octave:colon-complex-argument’ warning is enabled.
7455
7456‘Octave:colon-nonscalar-argument’
7457     If the ‘Octave:colon-nonscalar-argument’ warning is enabled, a
7458     warning is issued when one of the three arguments to the colon
7459     operator (base, increment, limit) is not a scalar.  For example,
7460     ‘1:[3, 5]’ will cause a warning to be emitted.  By default, the
7461     ‘Octave:colon-nonscalar-argument’ warning is enabled.
7462
7463‘Octave:data-file-in-path’
7464     If the ‘Octave:data-file-in-path’ warning is enabled, a warning is
7465     issued when Octave does not find the target of a file operation
7466     such as ‘load’ or ‘fopen’ directly, but is able to locate the file
7467     in Octave’s search ‘path’ for files.  The warning could indicate
7468     that a different file target than the programmer intended is being
7469     used.  By default, the ‘Octave:data-file-in-path’ warning is
7470     enabled.
7471
7472‘Octave:deprecated-function’
7473     If the ‘Octave:deprecated-function’ warning is enabled, a warning
7474     is issued when Octave encounters a function that is obsolete and
7475     scheduled for removal from Octave.  By default, the
7476     ‘Octave:deprecated-function’ warning is enabled.
7477
7478‘Octave:deprecated-keyword’
7479     If the ‘Octave:deprecated-keyword’ warning is enabled, a warning is
7480     issued when Octave encounters a keyword that is obsolete and
7481     scheduled for removal from Octave.  By default, the
7482     ‘Octave:deprecated-keyword’ warning is enabled.
7483
7484‘Octave:deprecated-property’
7485     If the ‘Octave:deprecated-property’ warning is enabled, a warning
7486     is issued when Octave encounters a graphics property that is
7487     obsolete and scheduled for removal from Octave.  By default, the
7488     ‘Octave:deprecated-property’ warning is enabled.
7489
7490‘Octave:eigs:UnconvergedEigenvalues’
7491     If the ‘Octave:eigs:UnconvergedEigenvalues’ warning is enabled then
7492     the eigs function will issue a warning if the number of calculated
7493     eigenvalues is less than the number of requested eigenvalues.  By
7494     default, the ‘Octave:eigs:UnconvergedEigenvalues’ warning is
7495     enabled.
7496
7497‘Octave:empty-index’
7498     If the ‘Octave:empty-index’ warning is enabled then Octave will
7499     emit a warning whenever indexing operators are used without an
7500     index, for example ‘X()’.  By default, the ‘Octave:empty-index’
7501     warning is enabled.
7502
7503‘Octave:erase:chararray’
7504     If the ‘Octave:erase:chararray’ warning is enabled then the erase
7505     function will issue a warning if the input pattern is a character
7506     array rather than a string or cell array of strings.  By default,
7507     the ‘Octave:erase:chararray’ warning is enabled.
7508
7509‘Octave:function-name-clash’
7510     If the ‘Octave:function-name-clash’ warning is enabled, a warning
7511     is issued when Octave finds that the name of a function defined in
7512     a function file differs from the name of the file.  (If the names
7513     disagree, the name declared inside the file is ignored.)  By
7514     default, the ‘Octave:function-name-clash’ warning is enabled.
7515
7516‘Octave:future-time-stamp’
7517     If the ‘Octave:future-time-stamp’ warning is enabled, Octave will
7518     print a warning if it finds a function file with a time stamp that
7519     is in the future.  By default, the ‘Octave:future-time-stamp’
7520     warning is enabled.
7521
7522‘Octave:glyph-render’
7523     If the ‘Octave:glyph-render’ warning is enabled, Octave will print
7524     a warning if the glyph for a character couldn’t be rendered with
7525     the current font.  By default, the ‘Octave:glyph-render’ warning is
7526     enabled.
7527
7528‘Octave:imag-to-real’
7529     If the ‘Octave:imag-to-real’ warning is enabled, a warning is
7530     printed for implicit conversions of complex numbers to real
7531     numbers.  By default, the ‘Octave:imag-to-real’ warning is
7532     disabled.
7533
7534‘Octave:language-extension’
7535     Print warnings when using features that are unique to the Octave
7536     language and that may still be missing in MATLAB.  By default, the
7537     ‘Octave:language-extension’ warning is disabled.  The
7538     ‘--traditional’ or ‘--braindead’ startup options for Octave may
7539     also be of use, *note Command Line Options::.
7540
7541‘Octave:legacy-function’
7542     If the ‘Octave:legacy-function’ warning is enabled, a warning is
7543     issued when Octave encounters a function that MATLAB has suggested
7544     should be avoided.  The function may become obsolete at some point
7545     in the future and removed, in which case the warning will change to
7546     ‘Octave:deprecated-function’, and the function will continue to
7547     exist for two further versions of Octave before being removed.  By
7548     default, the ‘Octave:legacy-function’ warning is enabled.
7549
7550‘Octave:logical-conversion’
7551     By default, the ‘Octave:logical-conversion’ warning is enabled.
7552
7553‘Octave:lu:sparse_input’
7554     If the ‘Octave:lu:sparse_input’ warning is enabled, Octave will
7555     warn when the lu function is called with a sparse input and less
7556     than four output arguments.  In this case, sparsity-preserving
7557     column permutations are not performed and the result may be
7558     inaccurate.  By default, the ‘Octave:lu:sparse_input’ warning is
7559     enabled.
7560
7561‘Octave:missing-glyph’
7562     If the ‘Octave:glyph-render’ warning is enabled, Octave will print
7563     a warning if the current font doesn’t provide a glyph for a used
7564     character.  By default, the ‘Octave:missing-glyph’ warning is
7565     enabled.
7566
7567‘Octave:missing-semicolon’
7568     If the ‘Octave:missing-semicolon’ warning is enabled, Octave will
7569     warn when statements in function definitions don’t end in
7570     semicolons.  By default the ‘Octave:missing-semicolon’ warning is
7571     disabled.
7572
7573‘Octave:mixed-string-concat’
7574     If the ‘Octave:mixed-string-concat’ warning is enabled, print a
7575     warning when concatenating a mixture of double and single quoted
7576     strings.  By default, the ‘Octave:mixed-string-concat’ warning is
7577     disabled.
7578
7579‘Octave:nearly-singular-matrix’
7580‘Octave:singular-matrix’
7581     These warnings are emitted if a (nearly) singular matrix is
7582     inverted.  By default, the ‘Octave:nearly-singular-matrix’ and
7583     ‘Octave:singular-matrix’ warnings are enabled.
7584
7585‘Octave:neg-dim-as-zero’
7586     If the ‘Octave:neg-dim-as-zero’ warning is enabled, print a warning
7587     for expressions like
7588
7589          eye (-1)
7590
7591     By default, the ‘Octave:neg-dim-as-zero’ warning is disabled.
7592
7593‘Octave:noninteger-range-as-index’
7594     By default, the ‘Octave:noninteger-range-as-index’ warning is
7595     enabled.
7596
7597‘Octave:num-to-str’
7598     If the ‘Octave:num-to-str’ warning is enable, a warning is printed
7599     for implicit conversions of numbers to their UTF-8 encoded
7600     character equivalents when strings are constructed using a mixture
7601     of strings and numbers in matrix notation.  For example,
7602
7603          [ "f", 111, 111 ]
7604          ⇒ "foo"
7605
7606     elicits a warning if the ‘Octave:num-to-str’ warning is enabled.
7607     By default, the ‘Octave:num-to-str’ warning is enabled.
7608
7609‘Octave:possible-matlab-short-circuit-operator’
7610     If the ‘Octave:possible-matlab-short-circuit-operator’ warning is
7611     enabled, Octave will warn about using the not short circuiting
7612     operators ‘&’ and ‘|’ inside ‘if’ or ‘while’ conditions.  They
7613     normally never short circuit, but they do short circuit when used
7614     in a condition.  By default, the
7615     ‘Octave:possible-matlab-short-circuit-operator’ warning is enabled.
7616
7617‘Octave:recursive-path-search’
7618     If the ‘Octave:recursive-path-search’ warning is enabled, Octave
7619     will issue a warning if ‘addpath’ is used with double trailing
7620     slashes.  By default, the ‘Octave:recursive-path-search’ warning is
7621     enabled.
7622
7623‘Octave:remove-init-dir’
7624     The ‘path’ function changes the search path that Octave uses to
7625     find functions.  It is possible to set the path to a value which
7626     excludes Octave’s own built-in functions.  If the
7627     ‘Octave:remove-init-dir’ warning is enabled then Octave will warn
7628     when the ‘path’ function has been used in a way that may render
7629     Octave unworkable.  By default, the ‘Octave:remove-init-dir’
7630     warning is enabled.
7631
7632‘Octave:reload-forces-clear’
7633     If several functions have been loaded from the same file, Octave
7634     must clear all the functions before any one of them can be
7635     reloaded.  If the ‘Octave:reload-forces-clear’ warning is enabled,
7636     Octave will warn you when this happens, and print a list of the
7637     additional functions that it is forced to clear.  By default, the
7638     ‘Octave:reload-forces-clear’ warning is enabled.
7639
7640‘Octave:separator-insert’
7641     Print warning if commas or semicolons might be inserted
7642     automatically in literal matrices.  By default, the
7643     ‘Octave:separator-insert’ warning is disabled.
7644
7645‘Octave:shadowed-function’
7646     If the ‘Octave:shadowed-function’ warning is enabled, Octave will
7647     warn if a path is added to the search path that contains functions
7648     that shadow core functions.  By default, the
7649     ‘Octave:shadowed-function’ warning is enabled.
7650
7651‘Octave:single-quote-string’
7652     Print warning if a single quote character is used to introduce a
7653     string constant.  By default, the ‘Octave:single-quote-string’
7654     warning is disabled.
7655
7656‘Octave:sqrtm:SingularMatrix’
7657     By default, the ‘Octave:sqrtm:SingularMatrix’ warning is enabled.
7658
7659‘Octave:str-to-num’
7660     If the ‘Octave:str-to-num’ warning is enabled, a warning is printed
7661     for implicit conversions of strings to their numeric UTF-8 encoded
7662     byte sequences.  For example,
7663
7664          "abc" + 0
7665          ⇒ 97 98 99
7666
7667     elicits a warning if the ‘Octave:str-to-num’ warning is enabled.
7668     By default, the ‘Octave:str-to-num’ warning is disabled.
7669
7670‘Octave:text_interpreter’
7671     If the ‘Octave:text_interpreter’ warning is enabled, a warning is
7672     printed when the "interpreter" property of a text graphics object
7673     is set to the unsupported value of "latex".  Even when enabled, the
7674     warning message is printed just once per Octave session.  By
7675     default, the ‘Octave:glyph-render’ warning is enabled.
7676
7677‘Octave:variable-switch-label’
7678     If the ‘Octave:variable-switch-label’ warning is enabled, Octave
7679     will print a warning if a switch label is not a constant or
7680     constant expression.  By default, the
7681     ‘Octave:variable-switch-label’ warning is disabled.
7682
7683
7684File: octave.info,  Node: Enabling and Disabling Warnings,  Prev: Issuing Warnings,  Up: Handling Warnings
7685
768612.2.2 Enabling and Disabling Warnings
7687--------------------------------------
7688
7689The ‘warning’ function also allows you to control which warnings are
7690actually printed to the screen.  If the ‘warning’ function is called
7691with a string argument that is either "on" or "off" all warnings will be
7692enabled or disabled.
7693
7694   It is also possible to enable and disable individual warnings through
7695their string identifications.  The following code will issue a warning
7696
7697     warning ("example:non-negative-variable",
7698              "'a' must be non-negative.  Setting 'a' to zero.");
7699
7700while the following won’t issue a warning
7701
7702     warning ("off", "example:non-negative-variable");
7703     warning ("example:non-negative-variable",
7704              "'a' must be non-negative.  Setting 'a' to zero.");
7705
7706
7707File: octave.info,  Node: Debugging,  Next: Input and Output,  Prev: Errors and Warnings,  Up: Top
7708
770913 Debugging
7710************
7711
7712Octave includes a built-in debugger to aid in the development of
7713scripts.  This can be used to interrupt the execution of an Octave
7714script at a certain point, or when certain conditions are met.  Once
7715execution has stopped, and debug mode is entered, the symbol table at
7716the point where execution has stopped can be examined and modified to
7717check for errors.
7718
7719   The normal command-line editing and history functions are available
7720in debug mode.
7721
7722* Menu:
7723
7724* Entering Debug Mode::
7725* Leaving Debug Mode::
7726* Breakpoints::
7727* Debug Mode::
7728* Call Stack::
7729* Profiling::
7730* Profiler Example::
7731
7732
7733File: octave.info,  Node: Entering Debug Mode,  Next: Leaving Debug Mode,  Up: Debugging
7734
773513.1 Entering Debug Mode
7736========================
7737
7738There are two basic means of interrupting the execution of an Octave
7739script.  These are breakpoints (*note Breakpoints::), discussed in the
7740next section, and interruption based on some condition.
7741
7742   Octave supports three means to stop execution based on the values set
7743in the functions ‘debug_on_interrupt’, ‘debug_on_warning’, and
7744‘debug_on_error’.
7745
7746 -- : VAL = debug_on_interrupt ()
7747 -- : OLD_VAL = debug_on_interrupt (NEW_VAL)
7748 -- : debug_on_interrupt (NEW_VAL, "local")
7749     Query or set the internal variable that controls whether Octave
7750     will try to enter debugging mode when it receives an interrupt
7751     signal (typically generated with ‘C-c’).
7752
7753     If a second interrupt signal is received before reaching the
7754     debugging mode, a normal interrupt will occur.
7755
7756     When called from inside a function with the "local" option, the
7757     variable is changed locally for the function and any subroutines it
7758     calls.  The original variable value is restored when exiting the
7759     function.
7760
7761     See also: *note debug_on_error: XREFdebug_on_error, *note
7762     debug_on_warning: XREFdebug_on_warning.
7763
7764 -- : VAL = debug_on_warning ()
7765 -- : OLD_VAL = debug_on_warning (NEW_VAL)
7766 -- : debug_on_warning (NEW_VAL, "local")
7767     Query or set the internal variable that controls whether Octave
7768     will try to enter the debugger when a warning is encountered.
7769
7770     When called from inside a function with the "local" option, the
7771     variable is changed locally for the function and any subroutines it
7772     calls.  The original variable value is restored when exiting the
7773     function.
7774
7775     See also: *note debug_on_error: XREFdebug_on_error, *note
7776     debug_on_interrupt: XREFdebug_on_interrupt.
7777
7778 -- : VAL = debug_on_error ()
7779 -- : OLD_VAL = debug_on_error (NEW_VAL)
7780 -- : debug_on_error (NEW_VAL, "local")
7781     Query or set the internal variable that controls whether Octave
7782     will try to enter the debugger when an error is encountered.
7783
7784     This will also inhibit printing of the normal traceback message
7785     (you will only see the top-level error message).
7786
7787     When called from inside a function with the "local" option, the
7788     variable is changed locally for the function and any subroutines it
7789     calls.  The original variable value is restored when exiting the
7790     function.
7791
7792     See also: *note debug_on_warning: XREFdebug_on_warning, *note
7793     debug_on_interrupt: XREFdebug_on_interrupt.
7794
7795
7796File: octave.info,  Node: Leaving Debug Mode,  Next: Breakpoints,  Prev: Entering Debug Mode,  Up: Debugging
7797
779813.2 Leaving Debug Mode
7799=======================
7800
7801Use either ‘dbcont’ or ‘return’ to leave the debug mode and continue the
7802normal execution of the script.
7803
7804 -- : dbcont
7805     Leave command-line debugging mode and continue code execution
7806     normally.
7807
7808     See also: *note dbstep: XREFdbstep, *note dbquit: XREFdbquit.
7809
7810   To quit debug mode and return directly to the prompt without
7811executing any additional code use ‘dbquit’.
7812
7813 -- : dbquit
7814 -- : dbquit all
7815     Quit debugging mode immediately without further code execution.
7816     With no arguments, exit the current debugging level.  With argument
7817     ‘all’, exit all debugging levels and return to the Octave prompt.
7818
7819     See also: *note dbcont: XREFdbcont, *note dbstep: XREFdbstep.
7820
7821   Finally, typing ‘exit’ or ‘quit’ at the debug prompt will result in
7822Octave terminating normally.
7823
7824
7825File: octave.info,  Node: Breakpoints,  Next: Debug Mode,  Prev: Leaving Debug Mode,  Up: Debugging
7826
782713.3 Breakpoints
7828================
7829
7830Breakpoints can be set in any m-file function by using the ‘dbstop’
7831function.
7832
7833 -- : dbstop FUNC
7834 -- : dbstop FUNC LINE
7835 -- : dbstop FUNC LINE1 LINE2 ...
7836 -- : dbstop LINE1 ...
7837 -- : dbstop in FUNC
7838 -- : dbstop in FUNC at LINE
7839 -- : dbstop in FUNC at LINE if "CONDITION"
7840 -- : dbstop in CLASS at METHOD
7841 -- : dbstop if EVENT
7842 -- : dbstop if EVENT ID
7843 -- : dbstop (BP_STRUCT)
7844 -- : RLINE = dbstop ...
7845
7846     Set breakpoints for the built-in debugger.
7847
7848     FUNC is the name of a function on the current ‘path’.  When already
7849     in debug mode the FUNC argument can be omitted and the current
7850     function will be used.  Breakpoints at subfunctions are set with
7851     the scope operator ‘>’.  For example, If ‘file.m’ has a subfunction
7852     ‘func2’, then a breakpoint in ‘func2’ can be specified by
7853     ‘file>func2’.
7854
7855     LINE is the line number at which to break.  If LINE is not
7856     specified, it defaults to the first executable line in the file
7857func.m’.  Multiple lines can be specified in a single command;
7858     when function syntax is used, the lines may also be passed as a
7859     single vector argument (‘[LINE1, LINE2, ...]’).
7860
7861     CONDITION is any Octave expression that can be evaluated in the
7862     code context that exists at the breakpoint.  When the breakpoint is
7863     encountered, CONDITION will be evaluated, and execution will stop
7864     if CONDITION is true.  If CONDITION cannot be evaluated, for
7865     example because it refers to an undefined variable, an error will
7866     be thrown.  Expressions with side effects (such as ‘y++ > 1’) will
7867     alter variables, and should generally be avoided.  Conditions
7868     containing quotes (‘"’, ‘'’) or comment characters (‘#’, ‘%’) must
7869     be enclosed in quotes.  (This does not apply to conditions entered
7870     from the editor’s context menu.)  For example:
7871
7872          dbstop in axis at 246 if 'any (opt == "x")'
7873
7874     The form specifying EVENT does not cause a specific breakpoint at a
7875     given function and line number.  Instead it causes debug mode to be
7876     entered when certain unexpected events are encountered.  Possible
7877     values are
7878
7879     ‘error’
7880          Stop when an error is reported.  This is equivalent to
7881          specifying both ‘debug_on_error (true)’ and
7882          ‘debug_on_interrupt (true)’.
7883
7884     ‘caught error’
7885          Stop when an error is caught by a try-catch block (not yet
7886          implemented).
7887
7888     ‘interrupt’
7889          Stop when an interrupt (‘Ctrl-C’) occurs.
7890
7891     ‘naninf’
7892          Stop when code returns a non-finite value (not yet
7893          implemented).
7894
7895     ‘warning’
7896          Stop when a warning is reported.  This is equivalent to
7897          specifying ‘debug_on_warning (true)’.
7898
7899     The events ‘error’, ‘caught error’, and ‘warning’ can all be
7900     followed by a string specifying an error ID or warning ID.  If that
7901     is done, only errors with the specified ID will cause execution to
7902     stop.  To stop on one of a set of IDs, multiple ‘dbstop’ commands
7903     must be issued.
7904
7905     Breakpoints and events can be removed using the ‘dbclear’ command
7906     with the same syntax.
7907
7908     It is possible to save all breakpoints and restore them at once by
7909     issuing the commands ‘bp_state = dbstatus; ...; dbstop (bp_state)’.
7910
7911     The optional output RLINE is the real line number where the
7912     breakpoint was set.  This can differ from the specified line if the
7913     line is not executable.  For example, if a breakpoint attempted on
7914     a blank line then Octave will set the real breakpoint at the next
7915     executable line.
7916
7917     When a file is re-parsed, such as when it is modified outside the
7918     GUI, all breakpoints within the file are cleared.
7919
7920     See also: *note dbclear: XREFdbclear, *note dbstatus: XREFdbstatus,
7921     *note dbstep: XREFdbstep, *note debug_on_error: XREFdebug_on_error,
7922     *note debug_on_warning: XREFdebug_on_warning, *note
7923     debug_on_interrupt: XREFdebug_on_interrupt.
7924
7925Breakpoints in class methods are also supported (e.g., ‘dbstop
7926("@class/method")’).  However, breakpoints cannot be set in built-in
7927functions (e.g., ‘sin’, etc.) or dynamically loaded functions (i.e.,
7928oct-files).
7929
7930   To set a breakpoint immediately upon entering a function use line
7931number 1, or omit the line number entirely and just give the function
7932name.  When setting the breakpoint Octave will ignore the leading
7933comment block, and the breakpoint will be set on the first executable
7934statement in the function.  For example:
7935
7936     dbstop ("asind", 1)
7937     ⇒ 29
7938
7939Note that the return value of ‘29’ means that the breakpoint was
7940effectively set to line 29.  The status of breakpoints in a function can
7941be queried with ‘dbstatus’.
7942
7943 -- : dbstatus
7944 -- : dbstatus FUNC
7945 -- : BP_LIST = dbstatus ...
7946     Report the location of active breakpoints.
7947
7948     When called with no input or output arguments, print the list of
7949     all functions with breakpoints and the line numbers where those
7950     breakpoints are set.
7951
7952     If a function name FUNC is specified then only report breakpoints
7953     for the named function and its subfunctions.
7954
7955     The optional return argument BP_LIST is a struct array with the
7956     following fields.
7957
7958     name
7959          The name of the function with a breakpoint.  A subfunction,
7960          say ‘func2’ within an m-file, say ‘file.m’, is specified as
7961          ‘file>func2’.
7962
7963     file
7964          The name of the m-file where the function code is located.
7965
7966     line
7967          The line number with the breakpoint.
7968
7969     cond
7970          The condition that must be satisfied for the breakpoint to be
7971          active, or the empty string for unconditional breakpoints.
7972
7973     If ‘dbstop if error’ is true but no explicit IDs are specified, the
7974     return value will have an empty field called "errs".  If IDs are
7975     specified, the ‘errs’ field will have one row per ID.  If ‘dbstop
7976     if error’ is false, there is no "errs" field.  The "warn" field is
7977     set similarly by ‘dbstop if warning’.
7978
7979     See also: *note dbstop: XREFdbstop, *note dbclear: XREFdbclear,
7980     *note dbwhere: XREFdbwhere, *note dblist: XREFdblist, *note
7981     dbstack: XREFdbstack.
7982
7983Reusing the previous example, ‘dbstatus ("asind")’ will return 29.  The
7984breakpoints listed can then be cleared with the ‘dbclear’ function.
7985
7986 -- : dbclear FUNC
7987 -- : dbclear FUNC LINE
7988 -- : dbclear FUNC LINE1 LINE2 ...
7989 -- : dbclear LINE ...
7990 -- : dbclear all
7991 -- : dbclear in FUNC
7992 -- : dbclear in FUNC at LINE
7993 -- : dbclear if EVENT
7994 -- : dbclear ("FUNC")
7995 -- : dbclear ("FUNC", LINE)
7996 -- : dbclear ("FUNC", LINE1, LINE2, ...)
7997 -- : dbclear ("FUNC", LINE1, ...)
7998 -- : dbclear (LINE, ...)
7999 -- : dbclear ("all")
8000     Delete a breakpoint at line number LINE in the function FUNC.
8001
8002     Arguments are
8003
8004     FUNC
8005          Function name as a string variable.  When already in debug
8006          mode this argument can be omitted and the current function
8007          will be used.
8008
8009     LINE
8010          Line number from which to remove a breakpoint.  Multiple lines
8011          may be given as separate arguments or as a vector.
8012
8013     EVENT
8014          An event such as ‘error’, ‘interrupt’, or ‘warning’ (*note
8015          dbstop: XREFdbstop. for details).
8016
8017     When called without a line number specification all breakpoints in
8018     the named function are cleared.
8019
8020     If the requested line is not a breakpoint no action is performed.
8021
8022     The special keyword "all" will clear all breakpoints from all
8023     files.
8024
8025     See also: *note dbstop: XREFdbstop, *note dbstatus: XREFdbstatus,
8026     *note dbwhere: XREFdbwhere.
8027
8028
8029   A breakpoint may also be set in a subfunction.  For example, if a
8030file contains the functions
8031
8032     function y = func1 (x)
8033       y = func2 (x);
8034     endfunction
8035     function y = func2 (x)
8036       y = x + 1;
8037     endfunction
8038
8039then a breakpoint can be set at the start of the subfunction directly
8040with
8041
8042     dbstop func1>func2
8043     ⇒ 5
8044
8045   Note that ‘>’ is the character that distinguishes subfunctions from
8046the m-file containing them.
8047
8048   Another simple way of setting a breakpoint in an Octave script is the
8049use of the ‘keyboard’ function.
8050
8051 -- : keyboard ()
8052 -- : keyboard ("PROMPT")
8053     Stop m-file execution and enter debug mode.
8054
8055     When the ‘keyboard’ function is executed, Octave prints a prompt
8056     and waits for user input.  The input strings are then evaluated and
8057     the results are printed.  This makes it possible to examine the
8058     values of variables within a function, and to assign new values if
8059     necessary.  To leave the prompt and return to normal execution type
8060     ‘return’ or ‘dbcont’.  The ‘keyboard’ function does not return an
8061     exit status.
8062
8063     If ‘keyboard’ is invoked without arguments, a default prompt of
8064     ‘debug> ’ is used.
8065
8066     See also: *note dbstop: XREFdbstop, *note dbcont: XREFdbcont, *note
8067     dbquit: XREFdbquit.
8068
8069The ‘keyboard’ function is placed in a script at the point where the
8070user desires that the execution be stopped.  It automatically sets the
8071running script into the debug mode.
8072
8073
8074File: octave.info,  Node: Debug Mode,  Next: Call Stack,  Prev: Breakpoints,  Up: Debugging
8075
807613.4 Debug Mode
8077===============
8078
8079There are three additional support functions that allow the user to find
8080out where in the execution of a script Octave entered the debug mode,
8081and to print the code in the script surrounding the point where Octave
8082entered debug mode.
8083
8084 -- : dbwhere
8085     In debugging mode, report the current file and line number where
8086     execution is stopped.
8087
8088     See also: *note dbstack: XREFdbstack, *note dblist: XREFdblist,
8089     *note dbstatus: XREFdbstatus, *note dbcont: XREFdbcont, *note
8090     dbstep: XREFdbstep, *note dbup: XREFdbup, *note dbdown: XREFdbdown.
8091
8092 -- : dbtype
8093 -- : dbtype LINENO
8094 -- : dbtype STARTL:ENDL
8095 -- : dbtype STARTL:END
8096 -- : dbtype FUNC
8097 -- : dbtype FUNC LINENO
8098 -- : dbtype FUNC STARTL:ENDL
8099 -- : dbtype FUNC STARTL:END
8100     Display a script file with line numbers.
8101
8102     When called with no arguments in debugging mode, display the script
8103     file currently being debugged.
8104
8105     An optional range specification can be used to list only a portion
8106     of the file.  The special keyword "end" is a valid line number
8107     specification for the last line of the file.
8108
8109     When called with the name of a function, list that script file with
8110     line numbers.
8111
8112     See also: *note dblist: XREFdblist, *note dbwhere: XREFdbwhere,
8113     *note dbstatus: XREFdbstatus, *note dbstop: XREFdbstop.
8114
8115 -- : dblist
8116 -- : dblist N
8117     In debugging mode, list N lines of the function being debugged
8118     centered around the current line to be executed.
8119
8120     If unspecified N defaults to 10 (+/- 5 lines)
8121
8122     See also: *note dbwhere: XREFdbwhere, *note dbtype: XREFdbtype,
8123     *note dbstack: XREFdbstack.
8124
8125   You may also use ‘isdebugmode’ to determine whether the debugger is
8126currently active.
8127
8128 -- : isdebugmode ()
8129     Return true if in debugging mode, otherwise false.
8130
8131     See also: *note dbwhere: XREFdbwhere, *note dbstack: XREFdbstack,
8132     *note dbstatus: XREFdbstatus.
8133
8134   Debug mode also allows single line stepping through a function using
8135the command ‘dbstep’.
8136
8137 -- : dbstep
8138 -- : dbstep N
8139 -- : dbstep in
8140 -- : dbstep out
8141 -- : dbnext ...
8142     In debugging mode, execute the next N lines of code.
8143
8144     If N is omitted, execute the next single line of code.  If the next
8145     line of code is itself defined in terms of an m-file remain in the
8146     existing function.
8147
8148     Using ‘dbstep in’ will cause execution of the next line to step
8149     into any m-files defined on the next line.
8150
8151     Using ‘dbstep out’ will cause execution to continue until the
8152     current function returns.
8153
8154     ‘dbnext’ is an alias for ‘dbstep’.
8155
8156     See also: *note dbcont: XREFdbcont, *note dbquit: XREFdbquit.
8157
8158   When in debug mode the <RETURN> key will execute the last entered
8159command.  This is useful, for example, after hitting a breakpoint and
8160entering ‘dbstep’ once.  After that, one can advance line by line
8161through the code with only a single key stroke.  This feature may be
8162disabled using the ‘auto_repeat_debug_command’ function.
8163
8164 -- : VAL = auto_repeat_debug_command ()
8165 -- : OLD_VAL = auto_repeat_debug_command (NEW_VAL)
8166 -- : auto_repeat_debug_command (NEW_VAL, "local")
8167     Query or set the internal variable that controls whether debugging
8168     commands are automatically repeated when the input line is empty
8169     (typing just <RET>).
8170
8171     When called from inside a function with the "local" option, the
8172     variable is changed locally for the function and any subroutines it
8173     calls.  The original variable value is restored when exiting the
8174     function.
8175
8176
8177File: octave.info,  Node: Call Stack,  Next: Profiling,  Prev: Debug Mode,  Up: Debugging
8178
817913.5 Call Stack
8180===============
8181
8182The function being debugged may be the leaf node of a series of function
8183calls.  After examining values in the current subroutine it may turn out
8184that the problem occurred in earlier pieces of code.  Use ‘dbup’ and
8185‘dbdown’ to move up and down through the series of function calls to
8186locate where variables first took on the wrong values.  ‘dbstack’ shows
8187the entire series of function calls and at what level debugging is
8188currently taking place.
8189
8190 -- : dbstack
8191 -- : dbstack N
8192 -- : dbstack -COMPLETENAMES
8193 -- : [STACK, IDX] = dbstack (...)
8194     Display or return current debugging function stack information.
8195
8196     With optional argument N, omit the N innermost stack frames.
8197
8198     Although accepted, the argument -COMPLETENAMES is silently ignored.
8199     Octave always returns absolute filenames.
8200
8201     The arguments N and -COMPLETENAMES can be both specified in any
8202     order.
8203
8204     The optional return argument STACK is a struct array with the
8205     following fields:
8206
8207     file
8208          The name of the m-file where the function code is located.
8209
8210     name
8211          The name of the function with a breakpoint.
8212
8213     line
8214          The line number of an active breakpoint.
8215
8216     column
8217          The column number of the line where the breakpoint begins.
8218
8219     scope
8220          Undocumented.
8221
8222     context
8223          Undocumented.
8224
8225     The return argument IDX specifies which element of the STACK struct
8226     array is currently active.
8227
8228     See also: *note dbup: XREFdbup, *note dbdown: XREFdbdown, *note
8229     dbwhere: XREFdbwhere, *note dblist: XREFdblist, *note dbstatus:
8230     XREFdbstatus.
8231
8232 -- : dbup
8233 -- : dbup N
8234     In debugging mode, move up the execution stack N frames.
8235
8236     If N is omitted, move up one frame.
8237
8238     See also: *note dbstack: XREFdbstack, *note dbdown: XREFdbdown.
8239
8240 -- : dbdown
8241 -- : dbdown N
8242     In debugging mode, move down the execution stack N frames.
8243
8244     If N is omitted, move down one frame.
8245
8246     See also: *note dbstack: XREFdbstack, *note dbup: XREFdbup.
8247
8248
8249File: octave.info,  Node: Profiling,  Next: Profiler Example,  Prev: Call Stack,  Up: Debugging
8250
825113.6 Profiling
8252==============
8253
8254Octave supports profiling of code execution on a per-function level.  If
8255profiling is enabled, each call to a function (supporting built-ins,
8256operators, functions in oct- and mex-files, user-defined functions in
8257Octave code and anonymous functions) is recorded while running Octave
8258code.  After that, this data can aid in analyzing the code behavior, and
8259is in particular helpful for finding “hot spots” in the code which use
8260up a lot of computation time and are the best targets to spend
8261optimization efforts on.
8262
8263   The main command for profiling is ‘profile’, which can be used to
8264start or stop the profiler and also to query collected data afterwards.
8265The data is returned in an Octave data structure which can then be
8266examined or further processed by other routines or tools.
8267
8268 -- : profile on
8269 -- : profile off
8270 -- : profile resume
8271 -- : profile clear
8272 -- : S = profile ("status")
8273 -- : T = profile ("info")
8274     Control the built-in profiler.
8275
8276     ‘profile on’
8277          Start the profiler, clearing all previously collected data if
8278          there is any.
8279
8280     ‘profile off’
8281          Stop profiling.  The collected data can later be retrieved and
8282          examined with ‘T = profile ("info")’.
8283
8284     ‘profile clear’
8285          Clear all collected profiler data.
8286
8287     ‘profile resume’
8288          Restart profiling without clearing the old data.  All newly
8289          collected statistics are added to the existing ones.
8290
8291     ‘S = profile ("status")’
8292          Return a structure with information about the current status
8293          of the profiler.  At the moment, the only field is
8294          ‘ProfilerStatus’ which is either "on" or "off".
8295
8296     ‘T = profile ("info")’
8297          Return the collected profiling statistics in the structure T.
8298          The flat profile is returned in the field ‘FunctionTable’
8299          which is an array of structures, each entry corresponding to a
8300          function which was called and for which profiling statistics
8301          are present.  In addition, the field ‘Hierarchical’ contains
8302          the hierarchical call tree.  Each node has an index into the
8303          ‘FunctionTable’ identifying the function it corresponds to as
8304          well as data fields for number of calls and time spent at this
8305          level in the call tree.
8306
8307          See also: *note profshow: XREFprofshow, *note profexplore:
8308          XREFprofexplore.
8309
8310   An easy way to get an overview over the collected data is ‘profshow’.
8311This function takes the profiler data returned by ‘profile’ as input and
8312prints a flat profile, for instance:
8313
8314      Function Attr     Time (s)        Calls
8315     ----------------------------------------
8316        >myfib    R        2.195        13529
8317     binary <=             0.061        13529
8318      binary -             0.050        13528
8319      binary +             0.026         6764
8320
8321   This shows that most of the run time was spent executing the function
8322‘myfib’, and some minor proportion evaluating the listed binary
8323operators.  Furthermore, it is shown how often the function was called
8324and the profiler also records that it is recursive.
8325
8326 -- : profshow (DATA)
8327 -- : profshow (DATA, N)
8328 -- : profshow ()
8329 -- : profshow (N)
8330     Display flat per-function profiler results.
8331
8332     Print out profiler data (execution time, number of calls) for the
8333     most critical N functions.  The results are sorted in descending
8334     order by the total time spent in each function.  If N is
8335     unspecified it defaults to 20.
8336
8337     The input DATA is the structure returned by ‘profile ("info")’.  If
8338     unspecified, ‘profshow’ will use the current profile dataset.
8339
8340     The attribute column displays ‘R’ for recursive functions, and is
8341     blank for all other function types.
8342
8343     See also: *note profexplore: XREFprofexplore, *note profile:
8344     XREFprofile.
8345
8346 -- : profexport (DIR)
8347 -- : profexport (DIR, DATA)
8348 -- : profexport (DIR, NAME)
8349 -- : profexport (DIR, NAME, DATA)
8350
8351     Export profiler data as HTML.
8352
8353     Export the profiling data in DATA into a series of HTML files in
8354     the folder DIR.  The initial file will be ‘DATA/index.html’.
8355
8356     If NAME is specified, it must be a string that contains a “name”
8357     for the profile being exported.  This name is included in the HTML.
8358
8359     The input DATA is the structure returned by ‘profile ("info")’.  If
8360     unspecified, ‘profexport’ will use the current profile dataset.
8361
8362     See also: *note profshow: XREFprofshow, *note profexplore:
8363     XREFprofexplore, *note profile: XREFprofile.
8364
8365 -- : profexplore ()
8366 -- : profexplore (DATA)
8367     Interactively explore hierarchical profiler output.
8368
8369     Assuming DATA is the structure with profile data returned by
8370     ‘profile ("info")’, this command opens an interactive prompt that
8371     can be used to explore the call-tree.  Type ‘help’ to get a list of
8372     possible commands.  If DATA is omitted, ‘profile ("info")’ is
8373     called and used in its place.
8374
8375     See also: *note profile: XREFprofile, *note profshow: XREFprofshow.
8376
8377
8378File: octave.info,  Node: Profiler Example,  Prev: Profiling,  Up: Debugging
8379
838013.7 Profiler Example
8381=====================
8382
8383Below, we will give a short example of a profiler session.  *Note
8384Profiling::, for the documentation of the profiler functions in detail.
8385Consider the code:
8386
8387     global N A;
8388
8389     N = 300;
8390     A = rand (N, N);
8391
8392     function xt = timesteps (steps, x0, expM)
8393       global N;
8394
8395       if (steps == 0)
8396         xt = NA (N, 0);
8397       else
8398         xt = NA (N, steps);
8399         x1 = expM * x0;
8400         xt(:, 1) = x1;
8401         xt(:, 2 : end) = timesteps (steps - 1, x1, expM);
8402       endif
8403     endfunction
8404
8405     function foo ()
8406       global N A;
8407
8408       initial = @(x) sin (x);
8409       x0 = (initial (linspace (0, 2 * pi, N)))';
8410
8411       expA = expm (A);
8412       xt = timesteps (100, x0, expA);
8413     endfunction
8414
8415     function fib = bar (N)
8416       if (N <= 2)
8417         fib = 1;
8418       else
8419         fib = bar (N - 1) + bar (N - 2);
8420       endif
8421     endfunction
8422
8423   If we execute the two main functions, we get:
8424
8425     tic; foo; toc;
8426     ⇒ Elapsed time is 2.37338 seconds.
8427
8428     tic; bar (20); toc;
8429     ⇒ Elapsed time is 2.04952 seconds.
8430
8431   But this does not give much information about where this time is
8432spent; for instance, whether the single call to ‘expm’ is more expensive
8433or the recursive time-stepping itself.  To get a more detailed picture,
8434we can use the profiler.
8435
8436     profile on;
8437     foo;
8438     profile off;
8439
8440     data = profile ("info");
8441     profshow (data, 10);
8442
8443   This prints a table like:
8444
8445        #  Function Attr     Time (s)        Calls
8446     ---------------------------------------------
8447        7      expm             1.034            1
8448        3  binary *             0.823          117
8449       41  binary \             0.188            1
8450       38  binary ^             0.126            2
8451       43 timesteps    R        0.111          101
8452       44        NA             0.029          101
8453       39  binary +             0.024            8
8454       34      norm             0.011            1
8455       40  binary -             0.004          101
8456       33   balance             0.003            1
8457
8458   The entries are the individual functions which have been executed
8459(only the 10 most important ones), together with some information for
8460each of them.  The entries like ‘binary *’ denote operators, while other
8461entries are ordinary functions.  They include both built-ins like ‘expm’
8462and our own routines (for instance ‘timesteps’).  From this profile, we
8463can immediately deduce that ‘expm’ uses up the largest proportion of the
8464processing time, even though it is only called once.  The second
8465expensive operation is the matrix-vector product in the routine
8466‘timesteps’.  (1)
8467
8468   Timing, however, is not the only information available from the
8469profile.  The attribute column shows us that ‘timesteps’ calls itself
8470recursively.  This may not be that remarkable in this example (since
8471it’s clear anyway), but could be helpful in a more complex setting.  As
8472to the question of why is there a ‘binary \’ in the output, we can
8473easily shed some light on that too.  Note that ‘data’ is a structure
8474array (*note Structure Arrays::) which contains the field
8475‘FunctionTable’.  This stores the raw data for the profile shown.  The
8476number in the first column of the table gives the index under which the
8477shown function can be found there.  Looking up ‘data.FunctionTable(41)’
8478gives:
8479
8480       scalar structure containing the fields:
8481
8482         FunctionName = binary \
8483         TotalTime =  0.18765
8484         NumCalls =  1
8485         IsRecursive = 0
8486         Parents =  7
8487         Children = [](1x0)
8488
8489   Here we see the information from the table again, but have additional
8490fields ‘Parents’ and ‘Children’.  Those are both arrays, which contain
8491the indices of functions which have directly called the function in
8492question (which is entry 7, ‘expm’, in this case) or been called by it
8493(no functions).  Hence, the backslash operator has been used internally
8494by ‘expm’.
8495
8496   Now let’s take a look at ‘bar’.  For this, we start a fresh profiling
8497session (‘profile on’ does this; the old data is removed before the
8498profiler is restarted):
8499
8500     profile on;
8501     bar (20);
8502     profile off;
8503
8504     profshow (profile ("info"));
8505
8506   This gives:
8507
8508        #            Function Attr     Time (s)        Calls
8509     -------------------------------------------------------
8510        1                 bar    R        2.091        13529
8511        2           binary <=             0.062        13529
8512        3            binary -             0.042        13528
8513        4            binary +             0.023         6764
8514        5             profile             0.000            1
8515        8               false             0.000            1
8516        6              nargin             0.000            1
8517        7           binary !=             0.000            1
8518        9 __profiler_enable__             0.000            1
8519
8520   Unsurprisingly, ‘bar’ is also recursive.  It has been called 13,529
8521times in the course of recursively calculating the Fibonacci number in a
8522suboptimal way, and most of the time was spent in ‘bar’ itself.
8523
8524   Finally, let’s say we want to profile the execution of both ‘foo’ and
8525‘bar’ together.  Since we already have the run-time data collected for
8526‘bar’, we can restart the profiler without clearing the existing data
8527and collect the missing statistics about ‘foo’.  This is done by:
8528
8529     profile resume;
8530     foo;
8531     profile off;
8532
8533     profshow (profile ("info"), 10);
8534
8535   As you can see in the table below, now we have both profiles mixed
8536together.
8537
8538        #  Function Attr     Time (s)        Calls
8539     ---------------------------------------------
8540        1       bar    R        2.091        13529
8541       16      expm             1.122            1
8542       12  binary *             0.798          117
8543       46  binary \             0.185            1
8544       45  binary ^             0.124            2
8545       48 timesteps    R        0.115          101
8546        2 binary <=             0.062        13529
8547        3  binary -             0.045        13629
8548        4  binary +             0.041         6772
8549       49        NA             0.036          101
8550
8551   ---------- Footnotes ----------
8552
8553   (1) We only know it is the binary multiplication operator, but
8554fortunately this operator appears only at one place in the code and thus
8555we know which occurrence takes so much time.  If there were multiple
8556places, we would have to use the hierarchical profile to find out the
8557exact place which uses up the time which is not covered in this example.
8558
8559