File: func.texi

package info (click to toggle)
octave3.2 3.2.4-8
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 62,936 kB
  • ctags: 37,353
  • sloc: cpp: 219,497; fortran: 116,336; ansic: 10,264; sh: 5,508; makefile: 4,245; lex: 3,573; yacc: 3,062; objc: 2,042; lisp: 1,692; awk: 860; perl: 844
file content (1926 lines) | stat: -rw-r--r-- 60,170 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
@c DO NOT EDIT!  Generated automatically by munge-texi.

@c Copyright (C) 1996, 1997, 2007, 2008, 2009 John W. Eaton
@c
@c This file is part of Octave.
@c
@c Octave is free software; you can redistribute it and/or modify it
@c under the terms of the GNU General Public License as published by the
@c Free Software Foundation; either version 3 of the License, or (at
@c your option) any later version.
@c 
@c Octave is distributed in the hope that it will be useful, but WITHOUT
@c ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
@c FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
@c for more details.
@c 
@c You should have received a copy of the GNU General Public License
@c along with Octave; see the file COPYING.  If not, see
@c <http://www.gnu.org/licenses/>.

@node Functions and Scripts
@chapter Functions and Scripts
@cindex defining functions
@cindex user-defined functions
@cindex functions, user-defined
@cindex script files

Complicated Octave programs can often be simplified by defining
functions.  Functions can be defined directly on the command line during
interactive Octave sessions, or in external files, and can be called just
like built-in functions.

@menu
* Defining Functions::          
* Multiple Return Values::      
* Variable-length Argument Lists::  
* Variable-length Return Lists::  
* Returning From a Function::   
* Default Arguments::   
* Function Files::              
* Script Files::                
* Function Handles Inline Functions and Anonymous Functions::
* Commands::
* Organization of Functions::   
@end menu

@node Defining Functions
@section Defining Functions
@cindex @code{function} statement
@cindex @code{endfunction} statement

In its simplest form, the definition of a function named @var{name}
looks like this:

@example
@group
function @var{name}
  @var{body}
endfunction
@end group
@end example

@noindent
A valid function name is like a valid variable name: a sequence of
letters, digits and underscores, not starting with a digit.  Functions
share the same pool of names as variables.

The function @var{body} consists of Octave statements.  It is the
most important part of the definition, because it says what the function
should actually @emph{do}.

For example, here is a function that, when executed, will ring the bell
on your terminal (assuming that it is possible to do so):

@example
@group
function wakeup
  printf ("\a");
endfunction
@end group
@end example

The @code{printf} statement (@pxref{Input and Output}) simply tells
Octave to print the string @code{"\a"}.  The special character @samp{\a}
stands for the alert character (ASCII 7).  @xref{Strings}.

Once this function is defined, you can ask Octave to evaluate it by
typing the name of the function.

Normally, you will want to pass some information to the functions you
define.  The syntax for passing parameters to a function in Octave is

@example
@group
function @var{name} (@var{arg-list})
  @var{body}
endfunction
@end group
@end example

@noindent
where @var{arg-list} is a comma-separated list of the function's
arguments.  When the function is called, the argument names are used to
hold the argument values given in the call.  The list of arguments may
be empty, in which case this form is equivalent to the one shown above.

To print a message along with ringing the bell, you might modify the
@code{wakeup} to look like this:

@example
@group
function wakeup (message)
  printf ("\a%s\n", message);
endfunction
@end group
@end example

Calling this function using a statement like this

@example
wakeup ("Rise and shine!");
@end example

@noindent
will cause Octave to ring your terminal's bell and print the message
@samp{Rise and shine!}, followed by a newline character (the @samp{\n}
in the first argument to the @code{printf} statement).

In most cases, you will also want to get some information back from the
functions you define.  Here is the syntax for writing a function that
returns a single value:

@example
@group
function @var{ret-var} = @var{name} (@var{arg-list})
  @var{body}
endfunction
@end group
@end example

@noindent
The symbol @var{ret-var} is the name of the variable that will hold the
value to be returned by the function.  This variable must be defined
before the end of the function body in order for the function to return
a value.

Variables used in the body of a function are local to the
function.  Variables named in @var{arg-list} and @var{ret-var} are also
local to the function.  @xref{Global Variables}, for information about
how to access global variables inside a function.

For example, here is a function that computes the average of the
elements of a vector:

@example
@group
function retval = avg (v)
  retval = sum (v) / length (v);
endfunction
@end group
@end example

If we had written @code{avg} like this instead,

@example
@group
function retval = avg (v)
  if (isvector (v))
    retval = sum (v) / length (v);
  endif
endfunction
@end group
@end example

@noindent
and then called the function with a matrix instead of a vector as the
argument, Octave would have printed an error message like this:

@example
@group
error: value on right hand side of assignment is undefined
@end group
@end example

@noindent
because the body of the @code{if} statement was never executed, and
@code{retval} was never defined.  To prevent obscure errors like this,
it is a good idea to always make sure that the return variables will
always have values, and to produce meaningful error messages when
problems are encountered.  For example, @code{avg} could have been
written like this:

@example
@group
function retval = avg (v)
  retval = 0;
  if (isvector (v))
    retval = sum (v) / length (v);
  else
    error ("avg: expecting vector argument");
  endif
endfunction
@end group
@end example

There is still one additional problem with this function.  What if it is
called without an argument?  Without additional error checking, Octave
will probably print an error message that won't really help you track
down the source of the error.  To allow you to catch errors like this,
Octave provides each function with an automatic variable called
@code{nargin}.  Each time a function is called, @code{nargin} is
automatically initialized to the number of arguments that have actually
been passed to the function.  For example, we might rewrite the
@code{avg} function like this:

@example
@group
function retval = avg (v)
  retval = 0;
  if (nargin != 1)
    usage ("avg (vector)");
  endif
  if (isvector (v))
    retval = sum (v) / length (v);
  else
    error ("avg: expecting vector argument");
  endif
endfunction
@end group
@end example

Although Octave does not automatically report an error if you call a
function with more arguments than expected, doing so probably indicates
that something is wrong.  Octave also does not automatically report an
error if a function is called with too few arguments, but any attempt to
use a variable that has not been given a value will result in an error.
To avoid such problems and to provide useful messages, we check for both
possibilities and issue our own error message.

@c ov-usr-fcn.cc
@anchor{doc-nargin}
@deftypefn {Built-in Function} {} nargin ()
@deftypefnx {Built-in Function} {} nargin (@var{fcn_name})
Within a function, return the number of arguments passed to the function.
At the top level, return the number of command line arguments passed to
Octave.  If called with the optional argument @var{fcn_name}, return the
maximum number of arguments the named function can accept, or -1 if the
function accepts a variable number of arguments.
@seealso{@ref{doc-nargout,,nargout}, @ref{doc-varargin,,varargin}, @ref{doc-varargout,,varargout}}
@end deftypefn


@c ./miscellaneous/inputname.m
@anchor{doc-inputname}
@deftypefn {Function File} {} inputname (@var{n})
Return the text defining @var{n}-th input to the function.
@end deftypefn


@c pt-eval.cc
@anchor{doc-silent_functions}
@deftypefn {Built-in Function} {@var{val} =} silent_functions ()
@deftypefnx {Built-in Function} {@var{old_val} =} silent_functions (@var{new_val})
Query or set the internal variable that controls whether internal
output from a function is suppressed.  If this option is disabled,
Octave will display the results produced by evaluating expressions
within a function body that are not terminated with a semicolon.
@end deftypefn


@node Multiple Return Values
@section Multiple Return Values

Unlike many other computer languages, Octave allows you to define
functions that return more than one value.  The syntax for defining
functions that return multiple values is

@example
@group
function [@var{ret-list}] = @var{name} (@var{arg-list})
  @var{body}
endfunction
@end group
@end example

@noindent
where @var{name}, @var{arg-list}, and @var{body} have the same meaning
as before, and @var{ret-list} is a comma-separated list of variable
names that will hold the values returned from the function.  The list of
return values must have at least one element.  If @var{ret-list} has
only one element, this form of the @code{function} statement is
equivalent to the form described in the previous section.

Here is an example of a function that returns two values, the maximum
element of a vector and the index of its first occurrence in the vector.

@example
@group
function [max, idx] = vmax (v)
  idx = 1;
  max = v (idx);
  for i = 2:length (v)
    if (v (i) > max)
      max = v (i);
      idx = i;
    endif
  endfor
endfunction
@end group
@end example

In this particular case, the two values could have been returned as
elements of a single array, but that is not always possible or
convenient.  The values to be returned may not have compatible
dimensions, and it is often desirable to give the individual return
values distinct names.

In addition to setting @code{nargin} each time a function is called,
Octave also automatically initializes @code{nargout} to the number of
values that are expected to be returned.  This allows you to write
functions that behave differently depending on the number of values that
the user of the function has requested.  The implicit assignment to the
built-in variable @code{ans} does not figure in the count of output
arguments, so the value of @code{nargout} may be zero.

The @code{svd} and @code{lu} functions are examples of built-in
functions that behave differently depending on the value of
@code{nargout}.

It is possible to write functions that only set some return values.  For
example, calling the function

@example
@group
function [x, y, z] = f ()
  x = 1;
  z = 2;
endfunction
@end group
@end example

@noindent
as

@example
[a, b, c] = f ()
@end example

@noindent
produces:

@example
@group
a = 1

b = [](0x0)

c = 2
@end group
@end example

@noindent
along with a warning.

@c ov-usr-fcn.cc
@anchor{doc-nargout}
@deftypefn {Built-in Function} {} nargout ()
@deftypefnx {Built-in Function} {} nargout (@var{fcn_name})
Within a function, return the number of values the caller expects to
receive.  If called with the optional argument @var{fcn_name}, return the
maximum number of values the named function can produce, or -1 if the
function can produce a variable number of values.

For example,

@example
f ()
@end example

@noindent
will cause @code{nargout} to return 0 inside the function @code{f} and

@example
[s, t] = f ()
@end example

@noindent
will cause @code{nargout} to return 2 inside the function
@code{f}.

At the top level, @code{nargout} is undefined.
@seealso{@ref{doc-nargin,,nargin}, @ref{doc-varargin,,varargin}, @ref{doc-varargout,,varargout}}
@end deftypefn


@c ./general/nargchk.m
@anchor{doc-nargchk}
@deftypefn {Function File} {@var{msgstr} =} nargchk (@var{minargs}, @var{maxargs}, @var{nargs})
@deftypefnx {Function File} {@var{msgstr} =} nargchk (@var{minargs}, @var{maxargs}, @var{nargs}, "string")
@deftypefnx {Function File} {@var{msgstruct} =} nargchk (@var{minargs}, @var{maxargs}, @var{nargs}, "struct")
Return an appropriate error message string (or structure) if the
number of inputs requested is invalid.

This is useful for checking to see that the number of input arguments
supplied to a function is within an acceptable range.
@seealso{@ref{doc-nargoutchk,,nargoutchk}, @ref{doc-error,,error}, @ref{doc-nargin,,nargin}, @ref{doc-nargout,,nargout}}
@end deftypefn


@c ./general/nargoutchk.m
@anchor{doc-nargoutchk}
@deftypefn {Function File} {@var{msgstr} =} nargoutchk (@var{minargs}, @var{maxargs}, @var{nargs})
@deftypefnx {Function File} {@var{msgstr} =} nargoutchk (@var{minargs}, @var{maxargs}, @var{nargs}, "string")
@deftypefnx {Function File} {@var{msgstruct} =} nargoutchk (@var{minargs}, @var{maxargs}, @var{nargs}, "struct")
Return an appropriate error message string (or structure) if the
number of outputs requested is invalid.

This is useful for checking to see that the number of output
arguments supplied to a function is within an acceptable range.
@seealso{@ref{doc-nargchk,,nargchk}, @ref{doc-error,,error}, @ref{doc-nargout,,nargout}, @ref{doc-nargin,,nargin}}
@end deftypefn


@anchor{doc-varargin} @anchor{doc-varargout}
@node Variable-length Argument Lists
@section Variable-length Argument Lists
@cindex variable-length argument lists
@cindex @code{varargin}

Sometimes the number of input arguments is not known when the function
is defined.  As an example think of a function that returns the smallest
of all its input arguments.  For example,

@example
@group
a = smallest (1, 2, 3);
b = smallest (1, 2, 3, 4);
@end group
@end example

@noindent
In this example both @code{a} and @code{b} would be 1.  One way to write
the @code{smallest} function is

@example
@group
function val = smallest (arg1, arg2, arg3, arg4, arg5)
  @var{body}
endfunction
@end group
@end example

@noindent
and then use the value of @code{nargin} to determine which of the input
arguments should be considered.  The problem with this approach is
that it can only handle a limited number of input arguments.

If the special parameter name @code{varargin} appears at the end of a
function parameter list it indicates that the function takes a variable
number of input arguments.  Using @code{varargin} the function
looks like this

@example
@group
function val = smallest (varargin)
  @var{body}
endfunction
@end group
@end example

@noindent
In the function body the input arguments can be accessed through the
variable @code{varargin}.  This variable is a cell array containing
all the input arguments.  @xref{Cell Arrays}, for details on working
with cell arrays.  The @code{smallest} function can now be defined
like this

@example
@group
function val = smallest (varargin)
  val = min ([varargin@{:@}]);
endfunction
@end group
@end example

@noindent
This implementation handles any number of input arguments, but it's also
a very simple solution to the problem.

A slightly more complex example of @code{varargin} is a function 
@code{print_arguments} that prints all input arguments.  Such a function
can be defined like this

@example
@group
function print_arguments (varargin)
  for i = 1:length (varargin)
    printf ("Input argument %d: ", i);
    disp (varargin@{i@});
  endfor
endfunction
@end group
@end example

@noindent
This function produces output like this

@example
@group
print_arguments (1, "two", 3);
     @print{} Input argument 1:  1
     @print{} Input argument 2: two
     @print{} Input argument 3:  3
@end group
@end example

@c ./miscellaneous/parseparams.m
@anchor{doc-parseparams}
@deftypefn {Function File} {[@var{reg}, @var{prop}] =} parseparams (@var{params})
Return in @var{reg} the cell elements of @var{param} up to the first
string element and in @var{prop} all remaining elements beginning
with the first string element.  For example 

@example
@group
[reg, prop] = parseparams (@{1, 2, "linewidth", 10@})
reg =
@{
  [1,1] = 1
  [1,2] = 2
@}
prop =
@{
  [1,1] = linewidth
  [1,2] = 10
@}
@end group
@end example

The parseparams function may be used to separate 'regular'
arguments and additional arguments given as property/value pairs of
the @var{varargin} cell array.
@seealso{@ref{doc-varargin,,varargin}}
@end deftypefn


@node Variable-length Return Lists
@section Variable-length Return Lists
@cindex variable-length return lists
@cindex @code{varargout}

It is possible to return a variable number of output arguments from a
function using a syntax that's similar to the one used with the
special @code{varargin} parameter name.  To let a function return a
variable number of output arguments the special output parameter name
@code{varargout} is used.  As with @code{varargin}, @code{varargout} is
a cell array that will contain the requested output arguments.

As an example the following function sets the first output argument to
1, the second to 2, and so on.

@example
@group
function varargout = one_to_n ()
  for i = 1:nargout
    varargout@{i@} = i;
  endfor
endfunction
@end group
@end example

@noindent
When called this function returns values like this

@example
@group
[a, b, c] = one_to_n ()
     @result{} a =  1
     @result{} b =  2
     @result{} c =  3
@end group
@end example

If @code{varargin} (@code{varargout}) does not appear as the last
element of the input (output) parameter list, then it is not special,
and is handled the same as any other parameter name.

@c ./general/deal.m
@anchor{doc-deal}
@deftypefn {Function File} {[@var{r1}, @var{r2}, @dots{}, @var{rn}] =} deal (@var{a})
@deftypefnx {Function File} {[@var{r1}, @var{r2}, @dots{}, @var{rn}] =} deal (@var{a1}, @var{a2}, @dots{}, @var{an})

Copy the input parameters into the corresponding output parameters.
If only one input parameter is supplied, its value is copied to each
of the outputs.

For example,

@example
[a, b, c] = deal (x, y, z);
@end example

@noindent
is equivalent to

@example
@group
a = x;
b = y;
c = z;
@end group
@end example

@noindent
and

@example
[a, b, c] = deal (x);
@end example

@noindent
is equivalent to

@example
a = b = c = x;
@end example
@end deftypefn


@node Returning From a Function
@section Returning From a Function

The body of a user-defined function can contain a @code{return} statement.
This statement returns control to the rest of the Octave program.  It
looks like this:

@example
return
@end example

Unlike the @code{return} statement in C, Octave's @code{return}
statement cannot be used to return a value from a function.  Instead,
you must assign values to the list of return variables that are part of
the @code{function} statement.  The @code{return} statement simply makes
it easier to exit a function from a deeply nested loop or conditional
statement.

Here is an example of a function that checks to see if any elements of a
vector are nonzero.

@example
@group
function retval = any_nonzero (v)
  retval = 0;
  for i = 1:length (v)
    if (v (i) != 0)
      retval = 1;
      return;
    endif
  endfor
  printf ("no nonzero elements found\n");
endfunction
@end group
@end example

Note that this function could not have been written using the
@code{break} statement to exit the loop once a nonzero value is found
without adding extra logic to avoid printing the message if the vector
does contain a nonzero element.

@deffn {Keyword} return
When Octave encounters the keyword @code{return} inside a function or
script, it returns control to the caller immediately.  At the top level,
the return statement is ignored.  A @code{return} statement is assumed
at the end of every function definition.
@end deffn

@node Default Arguments
@section Default Arguments
@cindex default arguments

Since Octave supports variable number of input arguments, it is very useful
to assign default values to some input arguments.  When an input argument
is declared in the argument list it is possible to assign a default
value to the argument like this

@example
@group
function @var{name} (@var{arg1} = @var{val1}, @dots{})
  @var{body}
endfunction
@end group
@end example

@noindent
If no value is assigned to @var{arg1} by the user, it will have the
value @var{val1}.

As an example, the following function implements a variant of the classic
``Hello, World'' program.
@example
@group
function hello (who = "World")
  printf ("Hello, %s!\n", who);
endfunction
@end group
@end example

@noindent
When called without an input argument the function prints the following
@example
@group
hello ();
     @print{} Hello, World!
@end group
@end example

@noindent
and when it's called with an input argument it prints the following
@example
@group
hello ("Beautiful World of Free Software");
     @print{} Hello, Beautiful World of Free Software!
@end group
@end example

Sometimes it is useful to explicitly tell Octave to use the default value
of an input argument.  This can be done writing a @samp{:} as the value
of the input argument when calling the function.
@example
@group
hello (:);
     @print{} Hello, World!
@end group
@end example

@node Function Files
@section Function Files
@cindex function file

Except for simple one-shot programs, it is not practical to have to
define all the functions you need each time you need them.  Instead, you
will normally want to save them in a file so that you can easily edit
them, and save them for use at a later time.

Octave does not require you to load function definitions from files
before using them.  You simply need to put the function definitions in a
place where Octave can find them.

When Octave encounters an identifier that is undefined, it first looks
for variables or functions that are already compiled and currently
listed in its symbol table.  If it fails to find a definition there, it
searches a list of directories (the @dfn{path}) for files ending in
@file{.m} that have the same base name as the undefined
identifier.@footnote{The @samp{.m} suffix was chosen for compatibility
with @sc{matlab}.}  Once Octave finds a file with a name that matches,
the contents of the file are read.  If it defines a @emph{single}
function, it is compiled and executed.  @xref{Script Files}, for more
information about how you can define more than one function in a single
file.

When Octave defines a function from a function file, it saves the full
name of the file it read and the time stamp on the file.  If the time
stamp on the file changes, Octave may reload the file.  When Octave is
running interactively, time stamp checking normally happens at most once
each time Octave prints the prompt.  Searching for new function
definitions also occurs if the current working directory changes.

Checking the time stamp allows you to edit the definition of a function
while Octave is running, and automatically use the new function
definition without having to restart your Octave session.

To avoid degrading performance unnecessarily by checking the time stamps
on functions that are not likely to change, Octave assumes that function
files in the directory tree
@file{@var{octave-home}/share/octave/@var{version}/m}
will not change, so it doesn't have to check their time stamps every time the
functions defined in those files are used.  This is normally a very good
assumption and provides a significant improvement in performance for the
function files that are distributed with Octave.

If you know that your own function files will not change while you are
running Octave, you can improve performance by calling
@code{ignore_function_time_stamp ("all")}, so that Octave will
ignore the time stamps for all function files.  Passing
@code{"system"} to this function resets the default behavior.

@c FIXME -- note about time stamps on files in NFS environments?

@c ./miscellaneous/edit.m
@anchor{doc-edit}
@deftypefn {Command} edit @var{name}
@deftypefnx {Command} edit @var{field} @var{value}
@deftypefnx {Command} {@var{value} =} edit get @var{field}
Edit the named function, or change editor settings.

If @code{edit} is called with the name of a file or function as
its argument it will be opened in a text editor.

@itemize @bullet
@item
If the function @var{name} is available in a file on your path and
that file is modifiable, then it will be edited in place.  If it 
is a system function, then it will first be copied to the directory
@code{HOME} (see further down) and then edited.  
If no file is found, then the m-file 
variant, ending with ".m", will be considered.  If still no file
is found, then variants with a leading "@@" and then with both a
leading "@@" and trailing ".m" will be considered.

@item
If @var{name} is the name of a function defined in the interpreter but 
not in an m-file, then an m-file will be created in @code{HOME}
to contain that function along with its current definition.  

@item
If @code{name.cc} is specified, then it will search for @code{name.cc}
in the path and try to modify it, otherwise it will create a new
@file{.cc} file in @code{HOME}.  If @var{name} happens to be an
m-file or interpreter defined function, then the text of that
function will be inserted into the .cc file as a comment.

@item
If @var{name.ext} is on your path then it will be edited, otherwise
the editor will be started with @file{HOME/name.ext} as the
filename.  If @file{name.ext} is not modifiable, it will be copied to
@code{HOME} before editing.

@strong{WARNING!} You may need to clear name before the new definition
is available.  If you are editing a .cc file, you will need
to mkoctfile @file{name.cc} before the definition will be available.
@end itemize

If @code{edit} is called with @var{field} and @var{value} variables,
the value of the control field @var{field} will be @var{value}.
If an output argument is requested and the first argument is @code{get}
then @code{edit} will return the value of the control field @var{field}.
If the control field does not exist, edit will return a structure 
containing all fields and values.  Thus, @code{edit get all} returns
a complete control structure.
The following control fields are used:

@table @samp
@item editor
This is the editor to use to modify the functions.  By default it uses
Octave's @code{EDITOR} built-in function, which comes from 
@code{getenv("EDITOR")} and defaults to @code{emacs}.  Use @code{%s}
In place of the function name.  For example,
@table @samp
@item [EDITOR, " %s"]
Use the editor which Octave uses for @code{bug_report}.
@item "xedit %s &"           
pop up simple X11 editor in a separate window
@item "gnudoit -q \"(find-file \\\"%s\\\")\""   
Send it to current Emacs; must have @code{(gnuserv-start)} in @file{.emacs}.
@end table

See also field 'mode', which controls how the editor is run by Octave.

On Cygwin, you will need to convert the Cygwin path to a Windows
path if you are using a native Windows editor.  For example
@c Set example in small font to prevent overfull line
@smallexample
'"C:/Program Files/Good Editor/Editor.exe" "$(cygpath -wa %s)"'
@end smallexample

@item home
This is the location of user local m-files.  Be be sure it is in your
path.  The default is @file{~/octave}.

@item author
This is the name to put after the "## Author:" field of new functions.
By default it guesses from the @code{gecos} field of password database.

@item email
This is the e-mail address to list after the name in the author field.
By default it guesses @code{<$LOGNAME@@$HOSTNAME>}, and if @code{$HOSTNAME}
is not defined it uses @code{uname -n}.  You probably want to override this.
Be sure to use @code{<user@@host>} as your format.

@item license
@table @samp
@item gpl
GNU General Public License (default).
@item bsd
BSD-style license without advertising clause.
@item pd
Public domain.
@item "text"
Your own default copyright and license.
@end table

Unless you specify @samp{pd}, edit will prepend the copyright statement 
with "Copyright (C) yyyy Function Author".

@item mode
This value determines whether the editor should be started in async mode
(editor is started in the background and Octave continues) or sync mode
(Octave waits until the editor exits).  Set it to "async" to start the editor
in async mode.  The default is "sync" (see also "system").

@item editinplace
Determines whether files should be edited in place, without regard to 
whether they are modifiable or not.  The default is @code{false}.
@end table
@end deftypefn


@c parse.cc
@anchor{doc-mfilename}
@deftypefn {Built-in Function} {} mfilename ()
@deftypefnx {Built-in Function} {} mfilename (@code{"fullpath"})
@deftypefnx {Built-in Function} {} mfilename (@code{"fullpathext"})
Return the name of the currently executing file.  At the top-level,
return the empty string.  Given the argument @code{"fullpath"},
include the directory part of the file name, but not the extension.
Given the argument @code{"fullpathext"}, include the directory part
of the file name and the extension.
@end deftypefn


@c symtab.cc
@anchor{doc-ignore_function_time_stamp}
@deftypefn {Built-in Function} {@var{val} =} ignore_function_time_stamp ()
@deftypefnx {Built-in Function} {@var{old_val} =} ignore_function_time_stamp (@var{new_val})
Query or set the internal variable that controls whether Octave checks
the time stamp on files each time it looks up functions defined in
function files.  If the internal variable is set to @code{"system"},
Octave will not automatically recompile function files in subdirectories of
@file{@var{octave-home}/lib/@var{version}} if they have changed since
they were last compiled, but will recompile other function files in the
search path if they change.  If set to @code{"all"}, Octave will not
recompile any function files unless their definitions are removed with
@code{clear}.  If set to "none", Octave will always check time stamps
on files to determine whether functions defined in function files
need to recompiled.
@end deftypefn


@menu
* Manipulating the load path::
* Subfunctions::
* Private Functions::
* Overloading and Autoloading::
* Function Locking::
* Function Precedence::
@end menu

@node Manipulating the load path
@subsection Manipulating the load path

When a function is called, Octave searches a list of directories for
a file that contains the function declaration.  This list of directories
is known as the load path.  By default the load path contains
a list of directories distributed with Octave plus the current
working directory.  To see your current load path call the @code{path}
function without any input or output arguments.

It is possible to add or remove directories to or from the load path
using @code{addpath} and @code{rmpath}.  As an example, the following
code adds @samp{~/Octave} to the load path.

@example
addpath("~/Octave")
@end example

@noindent
After this the directory @samp{~/Octave} will be searched for functions.
 
@c load-path.cc
@anchor{doc-addpath}
@deftypefn {Built-in Function} {} addpath (@var{dir1}, @dots{})
@deftypefnx {Built-in Function} {} addpath (@var{dir1}, @dots{}, @var{option})
Add @var{dir1}, @dots{} to the current function search path.  If
@var{option} is @samp{"-begin"} or 0 (the default), prepend the
directory name to the current path.  If @var{option} is @samp{"-end"}
or 1, append the directory name to the current path.
Directories added to the path must exist.
@seealso{@ref{doc-path,,path}, @ref{doc-rmpath,,rmpath}, @ref{doc-genpath,,genpath}, @ref{doc-pathdef,,pathdef}, @ref{doc-savepath,,savepath}, @ref{doc-pathsep,,pathsep}}
@end deftypefn


@c load-path.cc
@anchor{doc-genpath}
@deftypefn {Built-in Function} {} genpath (@var{dir})
Return a path constructed from @var{dir} and all its subdirectories.
@end deftypefn


@c load-path.cc
@anchor{doc-rmpath}
@deftypefn {Built-in Function} {} rmpath (@var{dir1}, @dots{})
Remove @var{dir1}, @dots{} from the current function search path.

@seealso{@ref{doc-path,,path}, @ref{doc-addpath,,addpath}, @ref{doc-genpath,,genpath}, @ref{doc-pathdef,,pathdef}, @ref{doc-savepath,,savepath}, @ref{doc-pathsep,,pathsep}}
@end deftypefn


@c ./path/savepath.m
@anchor{doc-savepath}
@deftypefn {Function File} {} savepath (@var{file})
Save the portion of the current function search path, that is
not set during Octave's initialization process, to @var{file}.
If @var{file} is omitted, @file{~/.octaverc} is used.  If successful,
@code{savepath} returns 0.
@seealso{@ref{doc-path,,path}, @ref{doc-addpath,,addpath}, @ref{doc-rmpath,,rmpath}, @ref{doc-genpath,,genpath}, @ref{doc-pathdef,,pathdef}, @ref{doc-pathsep,,pathsep}}
@end deftypefn


@c load-path.cc
@anchor{doc-path}
@deftypefn {Built-in Function} {} path (@dots{})
Modify or display Octave's load path.

If @var{nargin} and @var{nargout} are zero, display the elements of
Octave's load path in an easy to read format.

If @var{nargin} is zero and nargout is greater than zero, return the
current load path.

If @var{nargin} is greater than zero, concatenate the arguments,
separating them with @code{pathsep()}.  Set the internal search path
to the result and return it.

No checks are made for duplicate elements.
@seealso{@ref{doc-addpath,,addpath}, @ref{doc-rmpath,,rmpath}, @ref{doc-genpath,,genpath}, @ref{doc-pathdef,,pathdef}, @ref{doc-savepath,,savepath}, @ref{doc-pathsep,,pathsep}}
@end deftypefn


@c ./path/pathdef.m
@anchor{doc-pathdef}
@deftypefn {Function File} {@var{val} =} pathdef ()
Return the default path for Octave.
The path information is extracted from one of three sources.
In order of preference, those are;

@enumerate
@item @file{~/.octaverc}
@item @file{<octave-home>/@dots{}/<version>/m/startup/octaverc}
@item Octave's path prior to changes by any octaverc.
@end enumerate
@seealso{@ref{doc-path,,path}, @ref{doc-addpath,,addpath}, @ref{doc-rmpath,,rmpath}, @ref{doc-genpath,,genpath}, @ref{doc-savepath,,savepath}, @ref{doc-pathsep,,pathsep}}
@end deftypefn


@c dirfns.cc
@anchor{doc-pathsep}
@deftypefn {Built-in Function} {@var{val} =} pathsep ()
@deftypefnx {Built-in Function} {@var{old_val} =} pathsep (@var{new_val})
Query or set the character used to separate directories in
a path.
@seealso{@ref{doc-filesep,,filesep}, @ref{doc-dir,,dir}, @ref{doc-ls,,ls}}
@end deftypefn


@c load-path.cc
@anchor{doc-rehash}
@deftypefn {Built-in Function} {} rehash ()
Reinitialize Octave's load path directory cache.
@end deftypefn


@c utils.cc
@anchor{doc-file_in_loadpath}
@deftypefn {Built-in Function} {} file_in_loadpath (@var{file})
@deftypefnx {Built-in Function} {} file_in_loadpath (@var{file}, "all")

Return the absolute name of @var{file} if it can be found in
the list of directories specified by @code{path}.
If no file is found, return an empty matrix.

If the first argument is a cell array of strings, search each
directory of the loadpath for element of the cell array and return
the first that matches.

If the second optional argument @code{"all"} is supplied, return
a cell array containing the list of all files that have the same
name in the path.  If no files are found, return an empty cell array.
@seealso{@ref{doc-file_in_path,,file_in_path}, @ref{doc-path,,path}}
@end deftypefn


@c load-path.cc
@anchor{doc-restoredefaultpath}
@deftypefn {Built-in Function} {} restoredefaultpath (@dots{})
Restore Octave's path to it's initial state at startup.

@seealso{@ref{doc-path,,path}, @ref{doc-addpath,,addpath}, @ref{doc-rmpath,,rmpath}, @ref{doc-genpath,,genpath}, @ref{doc-pathdef,,pathdef}, @ref{doc-savepath,,savepath}, @ref{doc-pathsep,,pathsep}}
@end deftypefn


@c load-path.cc
@anchor{doc-command_line_path}
@deftypefn {Built-in Function} {} command_line_path (@dots{})
Return the command line path variable.

@seealso{@ref{doc-path,,path}, @ref{doc-addpath,,addpath}, @ref{doc-rmpath,,rmpath}, @ref{doc-genpath,,genpath}, @ref{doc-pathdef,,pathdef}, @ref{doc-savepath,,savepath}, @ref{doc-pathsep,,pathsep}}
@end deftypefn


@c utils.cc
@anchor{doc-find_dir_in_path}
@deftypefn {Built-in Function} {} find_dir_in_path (@var{dir})
Return the full name of the path element matching @var{dir}.  The
match is performed at the end of each path element.  For example, if
@var{dir} is @code{"foo/bar"}, it matches the path element
@code{"/some/dir/foo/bar"}, but not @code{"/some/dir/foo/bar/baz"}
or @code{"/some/dir/allfoo/bar"}.
@end deftypefn


@node Subfunctions
@subsection Subfunctions

A function file may contain secondary functions called
@dfn{subfunctions}.  These secondary functions are only visible to the
other functions in the same function file.  For example, a file
@file{f.m} containing

@example
@group
function f ()
  printf ("in f, calling g\n");
  g ()
endfunction
function g ()
  printf ("in g, calling h\n");
  h ()
endfunction
function h ()
  printf ("in h\n")
endfunction
@end group
@end example

@noindent
defines a main function @code{f} and two subfunctions.  The
subfunctions @code{g} and @code{h} may only be called from the main
function @code{f} or from the other subfunctions, but not from outside
the file @file{f.m}.

@node Private Functions
@subsection Private Functions

In many cases one function needs to access one or more helper
functions.  If the helper function is limited to the scope of a single
function, then subfunctions as discussed above might be used.  However,
if a single helper function is used by more than one function, then
this is no longer possible.  In this case the helper functions might
be placed in a subdirectory, called "private", of the directory in which
the functions needing access to this helper function are found.

As a simple example, consider a function @code{func1}, that calls a helper
function @code{func2} to do much of the work.  For example

@example
@group
function y = func1 (x)
  y = func2 (x);
endfunction
@end group
@end example

@noindent
Then if the path to @code{func1} is @code{<directory>/func1.m}, and if
@code{func2} is found in the directory @code{<directory>/private/func2.m}, 
then @code{func2} is only available for use of the functions, like 
@code{func1}, that are found in @code{<directory>}.

@node Overloading and Autoloading
@subsection Overloading and Autoloading

The @code{dispatch} function can be used to alias one function name to
another.  It can be used to alias all calls to a particular function name
to another function, or the alias can be limited to only a particular
variable type.  Consider the example

@example
@group
function y = spsin (x)
  printf ("Calling spsin\n");
  fflush(stdout);
  y = spfun ("sin", x);
endfunction

dispatch ("sin", "spsin", "sparse matrix");
y0 = sin(eye(3));
y1 = sin(speye(3));
@end group
@end example

@noindent
which aliases the user-defined function @code{spsin} to @code{sin}, but only for real sparse
matrices.  Note that the builtin @code{sin} already correctly treats
sparse matrices and so this example is only illustrative.

@c ./DLD-FUNCTIONS/dispatch.cc
@anchor{doc-dispatch}
@deftypefn {Loadable Function} {} dispatch (@var{f}, @var{r}, @var{type})

Replace the function @var{f} with a dispatch so that function @var{r}
is called when @var{f} is called with the first argument of the named
@var{type}.  If the type is @var{any} then call @var{r} if no other type
matches.  The original function @var{f} is accessible using
@code{builtin (@var{f}, @dots{})}.

If @var{r} is omitted, clear dispatch function associated with @var{type}.

If both @var{r} and @var{type} are omitted, list dispatch functions
for @var{f}.
@seealso{@ref{doc-builtin,,builtin}}
@end deftypefn


@c ./DLD-FUNCTIONS/dispatch.cc
@anchor{doc-builtin}
@deftypefn {Loadable Function} {[@dots{}]} builtin (@var{f}, @dots{})
Call the base function @var{f} even if @var{f} is overloaded to
some other function for the given type signature.
@seealso{@ref{doc-dispatch,,dispatch}}
@end deftypefn


A single dynamically linked file might define several
functions.  However, as Octave searches for functions based on the
functions filename, Octave needs a manner in which to find each of the
functions in the dynamically linked file.  On operating systems that
support symbolic links, it is possible to create a symbolic link to the
original file for each of the functions which it contains.

However, there is at least one well known operating system that doesn't
support symbolic links.  Making copies of the original file for each of
the functions is undesirable as it increases the
amount of disk space used by Octave.  Instead Octave supplies the
@code{autoload} function, that permits the user to define in which
file a certain function will be found.

@c parse.cc
@anchor{doc-autoload}
@deftypefn {Built-in Function} {} autoload (@var{function}, @var{file})
Define @var{function} to autoload from @var{file}.

The second argument, @var{file}, should be an absolute file name or
a file name in the same directory as the function or script from which
the autoload command was run.  @var{file} should not depend on the
Octave load path.

Normally, calls to @code{autoload} appear in PKG_ADD script files that
are evaluated when a directory is added to the Octave's load path.  To
avoid having to hardcode directory names in @var{file}, if @var{file}
is in the same directory as the PKG_ADD script then

@example
autoload ("foo", "bar.oct");
@end example

will load the function @code{foo} from the file @code{bar.oct}.  The above
when @code{bar.oct} is not in the same directory or uses like

@example
autoload ("foo", file_in_loadpath ("bar.oct"))
@end example

@noindent
are strongly discouraged, as their behavior might be unpredictable.

With no arguments, return a structure containing the current autoload map.
@seealso{@ref{doc-PKG_ADD,,PKG_ADD}}
@end deftypefn


@node Function Locking
@subsection Function Locking

It is sometime desirable to lock a function into memory with the
@code{mlock} function.  This is typically used for dynamically linked
functions in Oct-files or mex-files that contain some initialization,
and it is desirable that calling @code{clear} does not remove this
initialization.

As an example,

@example
mlock ("my_function");
@end example

@noindent
prevents @code{my_function} from being removed from memory, even if
@code{clear} is called.  It is possible to determine if a function is
locked into memory with the @code{mislocked}, and to unlock a function
with @code{munlock}, which the following illustrates.

@example
@group
mlock ("my_function");
mislocked ("my_function")
@result{} ans = 1
munlock ("my_function");
mislocked ("my_function")
@result{} ans = 0
@end group
@end example

A common use of @code{mlock} is to prevent persistent variables from
being removed from memory, as the following example shows:

@example
@group
function count_calls()
  persistent calls = 0;
  printf ("'count_calls' has been called %d times\n",
          ++calls);
endfunction
mlock ("count_calls");

count_calls ();
@print{} 'count_calls' has been called 1 times

clear count_calls
count_calls ();
@print{} 'count_calls' has been called 2 times
@end group
@end example

@noindent
It is, however, often inconvenient to lock a function from the prompt,
so it is also possible to lock a function from within its body.  This
is simply done by calling @code{mlock} from within the function.

@example
@group
function count_calls ()
  mlock ();
  persistent calls = 0;
  printf ("'count_calls' has been called %d times\n",
          ++calls);
endfunction
@end group
@end example

@code{mlock} might equally be used to prevent changes to a function from having
effect in Octave, though a similar effect can be had with the
@code{ignore_function_time_stamp} function.

@c variables.cc
@anchor{doc-mlock}
@deftypefn {Built-in Function} {} mlock ()
Lock the current function into memory so that it can't be cleared.
@seealso{@ref{doc-munlock,,munlock}, @ref{doc-mislocked,,mislocked}, @ref{doc-persistent,,persistent}}
@end deftypefn


@c variables.cc
@anchor{doc-munlock}
@deftypefn {Built-in Function} {} munlock (@var{fcn})
Unlock the named function.  If no function is named
then unlock the current function.
@seealso{@ref{doc-mlock,,mlock}, @ref{doc-mislocked,,mislocked}, @ref{doc-persistent,,persistent}}
@end deftypefn


@c variables.cc
@anchor{doc-mislocked}
@deftypefn {Built-in Function} {} mislocked (@var{fcn})
Return true if the named function is locked.  If no function is named
then return true if the current function is locked.
@seealso{@ref{doc-mlock,,mlock}, @ref{doc-munlock,,munlock}, @ref{doc-persistent,,persistent}}
@end deftypefn


@node Function Precedence
@subsection Function Precedence

Given the numerous different ways that Octave can define a function, it
is possible and even likely that multiple versions of a function, might be
defined within a particular scope.  The precedence of which function will be
used within a particular scope is given by

@enumerate 1
@item Subfunction
A subfunction with the required function name in the given scope.

@item Private function
A function defined within a private directory of the directory 
which contains the current function.

@item Class constructor
A function that constuctors a user class as defined in chapter 
@ref{Object Oriented Programming}.

@item Class method
An overloaded function of a class as in chapter
@ref{Object Oriented Programming}.

@item Legacy Dispatch
An overloaded function as defined by @xref{doc-dispatch}.

@item Command-line Function
A function that has been defined on the command-line.

@item Autoload function
A function that is marked as autoloaded with @xref{doc-autoload}.

@item A Function on the Path
A function that can be found on the users load-path.  There can also be
Oct-file, mex-file or m-file versions of this function and the precedence
between these versions are in that order.

@item Built-in function
A function that is builtin to Octave itself such as @code{numel},
@code{size}, etc.
@end enumerate

@node Script Files
@section Script Files

A script file is a file containing (almost) any sequence of Octave
commands.  It is read and evaluated just as if you had typed each
command at the Octave prompt, and provides a convenient way to perform a
sequence of commands that do not logically belong inside a function.

Unlike a function file, a script file must @emph{not} begin with the
keyword @code{function}.  If it does, Octave will assume that it is a
function file, and that it defines a single function that should be
evaluated as soon as it is defined.

A script file also differs from a function file in that the variables
named in a script file are not local variables, but are in the same
scope as the other variables that are visible on the command line.

Even though a script file may not begin with the @code{function}
keyword, it is possible to define more than one function in a single
script file and load (but not execute) all of them at once.  To do 
this, the first token in the file (ignoring comments and other white
space) must be something other than @code{function}.  If you have no
other statements to evaluate, you can use a statement that has no
effect, like this:

@example
@group
# Prevent Octave from thinking that this
# is a function file:

1;

# Define function one:

function one ()
  @dots{}
@end group
@end example

To have Octave read and compile these functions into an internal form,
you need to make sure that the file is in Octave's load path
(accessible through the @code{path} function), then simply type the
base name of the file that contains the commands.  (Octave uses the
same rules to search for script files as it does to search for
function files.)

If the first token in a file (ignoring comments) is @code{function},
Octave will compile the function and try to execute it, printing a
message warning about any non-whitespace characters that appear after
the function definition.

Note that Octave does not try to look up the definition of any identifier
until it needs to evaluate it.  This means that Octave will compile the
following statements if they appear in a script file, or are typed at
the command line,

@example
@group
# not a function file:
1;
function foo ()
  do_something ();
endfunction
function do_something ()
  do_something_else ();
endfunction
@end group
@end example

@noindent
even though the function @code{do_something} is not defined before it is
referenced in the function @code{foo}.  This is not an error because
Octave does not need to resolve all symbols that are referenced by a
function until the function is actually evaluated.

Since Octave doesn't look for definitions until they are needed, the
following code will always print @samp{bar = 3} whether it is typed
directly on the command line, read from a script file, or is part of a
function body, even if there is a function or script file called
@file{bar.m} in Octave's path.

@example
@group
eval ("bar = 3");
bar
@end group
@end example

Code like this appearing within a function body could fool Octave if
definitions were resolved as the function was being compiled.  It would
be virtually impossible to make Octave clever enough to evaluate this
code in a consistent fashion.  The parser would have to be able to
perform the call to @code{eval} at compile time, and that would be
impossible unless all the references in the string to be evaluated could
also be resolved, and requiring that would be too restrictive (the
string might come from user input, or depend on things that are not
known until the function is evaluated).

Although Octave normally executes commands from script files that have
the name @file{@var{file}.m}, you can use the function @code{source} to
execute commands from any file.

@c parse.cc
@anchor{doc-source}
@deftypefn {Built-in Function} {} source (@var{file})
Parse and execute the contents of @var{file}.  This is equivalent to
executing commands from a script file, but without requiring the file to
be named @file{@var{file}.m}.
@end deftypefn


@node Function Handles Inline Functions and Anonymous Functions
@section Function Handles, Inline Functions, and Anonymous Functions
@cindex handle, function handles
@cindex inline, inline functions
@cindex anonymous functions

It can be very convenient store a function in a variable so that it
can be passed to a different function.  For example, a function that
performs numerical minimization needs access to the function that 
should be minimized.

@menu
* Function Handles::
* Anonymous Functions::
* Inline Functions::
@end menu

@node Function Handles
@subsection Function Handles

A function handle is a pointer to another function and is defined with
the syntax

@example
@@@var{function-name}
@end example

@noindent
For example

@example
f = @@sin;
@end example

@noindent
Creates a function handle called @code{f} that refers to the
function @code{sin}.

Function handles are used to call other functions indirectly, or to pass
a function as an argument to another function like @code{quad} or
@code{fsolve}.  For example

@example
@group
f = @@sin;
quad (f, 0, pi)
    @result{} 2
@end group
@end example

You may use @code{feval} to call a function using function handle, or
simply write the name of the function handle followed by an argument
list.  If there are no arguments, you must use an empty argument list
@samp{()}.  For example

@example
@group
f = @@sin;
feval (f, pi/4)
    @result{} 0.70711
f (pi/4)
    @result{} 0.70711
@end group
@end example

@c ov-fcn-handle.cc
@anchor{doc-functions}
@deftypefn {Built-in Function} {} functions (@var{fcn_handle})
Return a struct containing information about the function handle
@var{fcn_handle}.
@end deftypefn


@c ov-fcn-handle.cc
@anchor{doc-func2str}
@deftypefn {Built-in Function} {} func2str (@var{fcn_handle})
Return a string containing the name of the function referenced by
the function handle @var{fcn_handle}.
@end deftypefn


@c ov-fcn-handle.cc
@anchor{doc-str2func}
@deftypefn {Built-in Function} {} str2func (@var{fcn_name})
Return a function handle constructed from the string @var{fcn_name}.
@end deftypefn


@node Anonymous Functions
@subsection Anonymous Functions

Anonymous functions are defined using the syntax

@example
@@(@var{argument-list}) @var{expression}
@end example

@noindent
Any variables that are not found in the argument list are inherited from
the enclosing scope.  Anonymous functions are useful for creating simple
unnamed functions from expressions or for wrapping calls to other
functions to adapt them for use by functions like @code{quad}.  For
example,

@example
@group
f = @@(x) x.^2;
quad (f, 0, 10)
    @result{} 333.33
@end group
@end example

@noindent
creates a simple unnamed function from the expression @code{x.^2} and
passes it to @code{quad},

@example
@group
quad (@@(x) sin (x), 0, pi)
    @result{} 2
@end group
@end example

@noindent
wraps another function, and

@example
@group
a = 1;
b = 2;
quad (@@(x) betainc (x, a, b), 0, 0.4)
    @result{} 0.13867
@end group
@end example

@noindent
adapts a function with several parameters to the form required by
@code{quad}.  In this example, the values of @var{a} and @var{b} that
are passed to @code{betainc} are inherited from the current
environment.

@node Inline Functions
@subsection Inline Functions

An inline function is created from a string containing the function
body using the @code{inline} function.  The following code defines the
function @math{f(x) = x^2 + 2}.

@example
f = inline("x^2 + 2");
@end example

@noindent
After this it is possible to evaluate @math{f} at any @math{x} by
writing @code{f(x)}.

@c ov-fcn-inline.cc
@anchor{doc-inline}
@deftypefn {Built-in Function} {} inline (@var{str})
@deftypefnx {Built-in Function} {} inline (@var{str}, @var{arg1}, @dots{})
@deftypefnx {Built-in Function} {} inline (@var{str}, @var{n})
Create an inline function from the character string @var{str}.
If called with a single argument, the arguments of the generated
function are extracted from the function itself.  The generated
function arguments will then be in alphabetical order.  It should
be noted that i, and j are ignored as arguments due to the
ambiguity between their use as a variable or their use as an inbuilt
constant.  All arguments followed by a parenthesis are considered
to be functions.

If the second and subsequent arguments are character strings,
they are the names of the arguments of the function.

If the second argument is an integer @var{n}, the arguments are
@code{"x"}, @code{"P1"}, @dots{}, @code{"P@var{N}"}.
@seealso{@ref{doc-argnames,,argnames}, @ref{doc-formula,,formula}, @ref{doc-vectorize,,vectorize}}
@end deftypefn


@c ov-fcn-inline.cc
@anchor{doc-argnames}
@deftypefn {Built-in Function} {} argnames (@var{fun})
Return a cell array of character strings containing the names of
the arguments of the inline function @var{fun}.
@seealso{@ref{doc-inline,,inline}, @ref{doc-formula,,formula}, @ref{doc-vectorize,,vectorize}}
@end deftypefn


@c ov-fcn-inline.cc
@anchor{doc-formula}
@deftypefn {Built-in Function} {} formula (@var{fun})
Return a character string representing the inline function @var{fun}.
Note that @code{char (@var{fun})} is equivalent to
@code{formula (@var{fun})}.
@seealso{@ref{doc-argnames,,argnames}, @ref{doc-inline,,inline}, @ref{doc-vectorize,,vectorize}}
@end deftypefn


@c ov-fcn-inline.cc
@anchor{doc-vectorize}
@deftypefn {Built-in Function} {} vectorize (@var{fun})
Create a vectorized version of the inline function @var{fun}
by replacing all occurrences of @code{*}, @code{/}, etc., with
@code{.*}, @code{./}, etc.
@end deftypefn


@c ./miscellaneous/symvar.m
@anchor{doc-symvar}
@deftypefn {Function File} {} symvar (@var{s})
Identifies the argument names in the function defined by a string.
Common constant names such as @code{pi}, @code{NaN}, @code{Inf},
@code{eps}, @code{i} or @code{j} are ignored.  The arguments that are
found are returned in a cell array of strings.  If no variables are
found then the returned cell array is empty.
@end deftypefn


@node Commands
@section Commands

Commands are a special class of functions that only accept string
input arguments.  A command can be called as an ordinary function, but
it can also be called without the parentheses like the following example
shows

@example
my_command hello world
@end example

@noindent
which is the same as

@example
my_command("hello", "world")
@end example

The general form of a command call is

@example
@var{name} @var{arg1} @var{arg2} @dots{}
@end example

@noindent
which translates directly to

@example
@var{name} ("@var{arg1}", "@var{arg2}", @dots{})
@end example

A function can be used as a command if it accepts string input arguments.
To do this, the function must be marked as a command, which can be done
with the @code{mark_as_command} command like this

@example
mark_as_command name
@end example

@noindent
where @code{name} is the function to be marked as a command.

One difficulty of commands occurs when one of the string input arguments
are stored in a variable.  Since Octave can't tell the difference between
a variable name, and an ordinary string, it is not possible to pass a
variable as input to a command.  In such a situation a command must be
called as a function.

@c ./deprecated/mark_as_command.m
@anchor{doc-mark_as_command}
@deftypefn {Built-in Function} {} mark_as_command (@var{name})
This function is obsolete and will be removed from a future
version of Octave.
@end deftypefn


@c ./deprecated/unmark_command.m
@anchor{doc-unmark_command}
@deftypefn {Built-in Function} {} unmark_command (@var{name})
This function is obsolete and will be removed from a future
version of Octave.
@end deftypefn


@c ./deprecated/iscommand.m
@anchor{doc-iscommand}
@deftypefn {Built-in Function} {} iscommand (@var{name})
This function is obsolete and will be removed from a future
version of Octave.
@end deftypefn


@c ./deprecated/mark_as_rawcommand.m
@anchor{doc-mark_as_rawcommand}
@deftypefn {Built-in Function} {} mark_as_rawcommand (@var{name})
This function is obsolete and will be removed from a future
version of Octave.
@end deftypefn


@c ./deprecated/unmark_rawcommand.m
@anchor{doc-unmark_rawcommand}
@deftypefn {Built-in Function} {} unmark_rawcommand (@var{name})
This function is obsolete and will be removed from a future
version of Octave.
@end deftypefn


@c ./deprecated/israwcommand.m
@anchor{doc-israwcommand}
@deftypefn {Built-in Function} {} israwcommand (@var{name})
This function is obsolete and will be removed from a future
version of Octave.
@end deftypefn


@node Organization of Functions
@section Organization of Functions Distributed with Octave

Many of Octave's standard functions are distributed as function files.
They are loosely organized by topic, in subdirectories of
@file{@var{octave-home}/lib/octave/@var{version}/m}, to make it easier
to find them.

The following is a list of all the function file subdirectories, and the
types of functions you will find there.

@table @file
@item audio
Functions for playing and recording sounds.

@item control
Functions for design and simulation of automatic control systems.

@item elfun
Elementary functions.

@item finance
Functions for computing interest payments, investment values, and rates
of return.

@item general
Miscellaneous matrix manipulations, like @code{flipud}, @code{rot90},
and @code{triu}, as well as other basic functions, like
@code{ismatrix}, @code{nargchk}, etc.

@item image
Image processing tools.  These functions require the X Window System.

@item io
Input-output functions.

@item linear-algebra
Functions for linear algebra.

@item miscellaneous
Functions that don't really belong anywhere else.

@item optimization
Minimization of functions.

@item path
Functions to manage the directory path Octave uses to find functions.

@item pkg
Install external packages of functions in Octave.

@item plot
Functions for displaying and printing two- and three-dimensional graphs.

@item polynomial
Functions for manipulating polynomials.

@item set
Functions for creating and manipulating sets of unique values.

@item signal
Functions for signal processing applications.

@item sparse
Functions for handling sparse matrices.

@item specfun
Special functions.

@item special-matrix
Functions that create special matrix forms.

@item startup
Octave's system-wide startup file.

@item statistics
Statistical functions.

@item strings
Miscellaneous string-handling functions.

@item testfun
Perform unit tests on other functions.

@item time
Functions related to time keeping.
@end table