File: external.texi

package info (click to toggle)
octave 10.3.0-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 145,388 kB
  • sloc: cpp: 335,976; ansic: 82,241; fortran: 20,963; objc: 9,402; sh: 8,756; yacc: 4,392; lex: 4,333; perl: 1,544; java: 1,366; awk: 1,259; makefile: 659; xml: 192
file content (3750 lines) | stat: -rw-r--r-- 120,497 bytes parent folder | download | duplicates (2)
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
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
@c DO NOT EDIT!  Generated automatically by munge-texi.pl.

@c Copyright (C) 2007-2025 The Octave Project Developers
@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
@c the Free Software Foundation, either version 3 of the License, or
@c (at your option) any later version.
@c
@c Octave is distributed in the hope that it will be useful, but
@c WITHOUT ANY WARRANTY; without even the implied warranty of
@c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
@c GNU General Public License 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 <https://www.gnu.org/licenses/>.

@node External Code Interface
@appendix External Code Interface
@cindex dynamic-linking
@cindex Dynamically Linked Functions
@cindex Octave API

"The sum of human wisdom is not contained in any one language"

                                               --- Ezra Pound

Octave is a fantastic language for solving many problems in science and
engineering.  However, it is not the only computer language and there are times
when you may want to use code written in other languages.  Good reasons for
doing so include: 1) not re-inventing the wheel; existing function libraries
which have been thoroughly tested and debugged or large scale simulation
codebases are a good example, 2) accessing unique capabilities of a different
language; for example the well-known regular expression functions of Perl (but
don't do that because @code{regexp} already exists in Octave).

Performance should generally @strong{not} be a reason for using compiled
extensions.  Although compiled extensions can run faster, particularly if they
replace a loop in Octave code, this is almost never the best path to take.
First, there are many techniques to speed up Octave performance while remaining
within the language.  Second, Octave is a high-level language that makes it
easy to perform common mathematical tasks.  Giving that up means shifting the
focus from solving the real problem to solving a computer programming problem.
It means returning to low-level constructs such as pointers, memory management,
mathematical overflow/underflow, etc.  Because of the low level nature, and the
fact that the compiled code is executed outside of Octave, there is the very
real possibility of crashing the interpreter and losing work.

Before going further, you should first determine if you really need to bother
writing code outside of Octave.

@itemize @bullet
@item
Can I get the same functionality using the Octave scripting language alone?

Even when a function already exists outside the language, it may be better to
simply reproduce the behavior in an m-file rather than attempt to interface to
the outside code.

@item
Is the code thoroughly optimized for Octave?

If performance is an issue you should always start with the in-language
techniques for getting better performance.  Chief among these is vectorization
(@pxref{Vectorization and Faster Code Execution}) which not only makes the code
concise and more understandable but improves performance (10X-100X).  If loops
must be used, make sure that the allocation of space for variables takes place
outside the loops using an assignment to a matrix of the right size, or zeros.

@item
Does the code make as much use as possible of existing built-in library
routines?

These routines are highly optimized and many do not carry the overhead of being
interpreted.

@item
Does writing a dynamically linked function represent a useful investment of
your time, relative to staying in Octave?

It will take time to learn Octave's interface for external code and there will
inevitably be issues with tools such as compilers.
@end itemize

With that said, Octave offers a versatile interface for including chunks of
compiled code as dynamically linked extensions.  These dynamically linked
functions can be called from the interpreter in the same manner as any ordinary
function.  The interface is bi-directional and external code can call Octave
functions (like @code{plot}) which otherwise might be very difficult to
develop.

The interface is centered around supporting the languages C++, C, and Fortran.
Octave itself is written in C++ and can call external C++/C code through its
native oct-file interface.  The C language is also supported through the
mex-file interface for compatibility with @sc{matlab}.  Fortran code is easiest
to reach through the oct-file interface.

Because many other languages provide C or C++ APIs it is relatively simple to
build bridges between Octave and other languages.  This is also a way to bridge
to hardware resources which often have device drivers written in C.

@menu
* Oct-Files::
* Mex-Files::
* Standalone Programs::
* Java Interface::
@end menu

@node Oct-Files
@section Oct-Files
@cindex oct-files
@cindex mkoctfile
@cindex oct

@menu
* Getting Started with Oct-Files::
* Matrices and Arrays in Oct-Files::
* Character Strings in Oct-Files::
* Cell Arrays in Oct-Files::
* Structures in Oct-Files::
* Sparse Matrices in Oct-Files::
* Accessing Global Variables in Oct-Files::
* Calling Octave Functions from Oct-Files::
* Calling External Code from Oct-Files::
* Allocating Local Memory in Oct-Files::
* Input Parameter Checking in Oct-Files::
* Exception and Error Handling in Oct-Files::
* Documentation and Testing of Oct-Files::
@c * Application Programming Interface for Oct-Files::
@end menu

@node Getting Started with Oct-Files
@subsection Getting Started with Oct-Files

Oct-files are pieces of C++ code that have been compiled with the Octave API
into a dynamically loadable object.  They take their name from the file which
contains the object which has the extension @file{.oct}.

Finding a C++ compiler, using the correct switches, adding the right include
paths for header files, etc.@: is a difficult task.  Octave automates this by
providing the @code{mkoctfile} command with which to build oct-files.  The
command is available from within Octave or at the shell command line.

@c mkoctfile scripts/miscellaneous/mkoctfile.m
@anchor{XREFmkoctfile}
@html
<span style="display:block; margin-top:-4.5ex;">&nbsp;</span>
@end html


@deftypefn  {} {} mkoctfile [-options] file @dots{}
@deftypefnx {} {[@var{output}, @var{status}] =} mkoctfile (@dots{})

The @code{mkoctfile} function compiles source code written in C, C++, or
Fortran.  Depending on the options used with @code{mkoctfile}, the
compiled code can be called within Octave or can be used as a stand-alone
application.

@code{mkoctfile} can be called from the shell prompt or from the Octave
prompt.  Calling it from the Octave prompt simply delegates the call to
the shell prompt.  Any output is stored in the @var{output} variable and
the exit status in the @var{status} variable.  If called with no outputs
and the compilation fails then Octave will emit an error.  If the programmer
requests @var{output} or @var{status}, however, Octave will merely issue
a warning and it is the programmer's responsibility to verify the command
was successful.

@code{mkoctfile} accepts the following options, all of which are optional
except for the filename of the code you wish to compile:

@table @samp
@item -I DIR
Add the include directory DIR to compile commands.

@item -D DEF
Add the definition DEF to the compiler call.

@item -l LIB
Add the library LIB to the link command.

@item -L DIR
Add the library directory DIR to the link command.

@item  -M
@itemx --depend
Generate dependency files (.d) for C and C++ source files.

@item -R DIR
Add the run-time path to the link command.

@item @nospell{-Wl,@dots{}}
Pass options to the linker like @nospell{"-Wl,-rpath=@dots{}"}.
The quotes are needed since commas are interpreted as command
separators.

@item -W@dots{}
Pass options to the assembler like @nospell{"-Wa,OPTION"}.

@item -c
Compile but do not link.

@item -g
Enable debugging options for compilers.

@item  -o FILE
@itemx --output FILE
Output filename.  Default extension is @file{.oct} (or @file{.mex} if
@samp{--mex} is specified) unless linking a stand-alone executable.

@item  -p VAR
@itemx --print VAR
Print configuration variable VAR@.  There are three categories of
variables:

Octave configuration variables that users may override with environment
variables.  These are used in commands that @code{mkoctfile} executes.

@example
   ALL_CFLAGS                  INCLUDEDIR
   ALL_CXXFLAGS                LAPACK_LIBS
   ALL_FFLAGS                  LDFLAGS
   ALL_LDFLAGS                 LD_STATIC_FLAG
   BLAS_LIBS                   LIBDIR
   CC                          LIBOCTAVE
   CFLAGS                      LIBOCTINTERP
   CPICFLAG                    LIBOCTMEX
   CPPFLAGS                    OCTAVE_LINK_OPTS
   CXX                         OCTINCLUDEDIR
   CXXFLAGS                    OCTAVE_LIBS
   CXXLD                       OCTAVE_LINK_DEPS
   CXXPICFLAG                  OCTLIBDIR
   DL_LDFLAGS                  OCT_LINK_DEPS
   F77                         OCT_LINK_OPTS
   F77_INTEGER8_FLAG           RDYNAMIC_FLAG
   FFLAGS                      SPECIAL_MATH_LIB
   FPICFLAG                    XTRA_CFLAGS
   INCFLAGS                    XTRA_CXXFLAGS
@end example

Octave configuration variables as above, but currently unused by
@code{mkoctfile}.

@example
@group
   AR
   DEPEND_EXTRA_SED_PATTERN
   DEPEND_FLAGS
   FFTW3F_LDFLAGS
   FFTW3F_LIBS
   FFTW3_LDFLAGS
   FFTW3_LIBS
   FFTW_LIBS
   FLIBS
   LIBS
   RANLIB
   READLINE_LIBS
@end group
@end example

Octave configuration variables that are provided for informational
purposes only.  Except for @samp{OCTAVE_HOME} and @samp{OCTAVE_EXEC_HOME},
users may not override these variables.

If @w{@env{OCTAVE_HOME}}@ or @w{@env{OCTAVE_EXEC_HOME}}@ are set in the
environment, then other variables are adjusted accordingly with
@w{@env{OCTAVE_HOME}}@ or @w{@env{OCTAVE_EXEC_HOME}}@ substituted for the
original value of the directory specified by the @option{--prefix} or
@option{--exec-prefix} options that were used when Octave was configured.

@example
@group
   API_VERSION                 LOCALARCHLIBDIR
   ARCHLIBDIR                  LOCALFCNFILEDIR
   BINDIR                      LOCALOCTFILEDIR
   CANONICAL_HOST_TYPE         LOCALSTARTUPFILEDIR
   DATADIR                     LOCALVERARCHLIBDIR
   DATAROOTDIR                 LOCALVERFCNFILEDIR
   DEFAULT_PAGER               LOCALVEROCTFILEDIR
   EXEC_PREFIX                 MAN1DIR
   EXEEXT                      MAN1EXT
   FCNFILEDIR                  MANDIR
   IMAGEDIR                    OCTAVE_EXEC_HOME
   INCLUDEDIR                  OCTAVE_HOME
   INFODIR                     OCTDATADIR
   INFOFILE                    OCTDOCDIR
   LIBDIR                      OCTFILEDIR
   LIBEXECDIR                  OCTFONTSDIR
   LOCALAPIARCHLIBDIR          OCTINCLUDEDIR
   LOCALAPIFCNFILEDIR          OCTLIBDIR
   LOCALAPIOCTFILEDIR          STARTUPFILEDIR
   LOCALAPIPKGDIR              VERSION
@end group
@end example

@item --link-stand-alone
Link a stand-alone executable file.

@item --mex
Assume creation of a MEX file.  Set the default output extension to
@file{.mex}.  Link to liboctmex instead of liboctinterp and liboctave.

@item  -s
@itemx --strip
Strip the output file.

@item  -v
@itemx --verbose
Echo commands as they are executed.

@item file
The file to compile or link.  Recognized file types are:

@example
@group
   .c    C source
   .cc   C++ source
   .cp   C++ source
   .cpp  C++ source
   .CPP  C++ source
   .cxx  C++ source
   .c++  C++ source
   .C    C++ source
   .f    Fortran source (fixed form)
   .F    Fortran source (fixed form)
   .f90  Fortran source (free form)
   .F90  Fortran source (free form)
   .o    object file
   .a    library file
@end group
@end example

@end table
@end deftypefn


Consider the following short example which introduces the basics of writing a
C++ function that can be linked to Octave.

@example
@group
@verbatim
#include <octave/oct.h>

DEFUN_DLD (helloworld, args, nargout,
           "Hello World Help String")
{
  octave_stdout << "Hello World has "
                << args.length () << " input arguments and "
                << nargout << " output arguments.\n";

  // Return empty matrices for any outputs
  octave_value_list retval (nargout);
  for (int i = 0; i < nargout; i++)
    retval(i) = octave_value (Matrix ());

  return retval;
}
@end verbatim
@end group
@end example

The first critical line is @code{#include <octave/oct.h>} which makes available
most of the definitions necessary for a C++ oct-file.  Note that
@file{octave/oct.h} is a C++ header and cannot be directly @code{#include}'ed
in a C source file, nor any other language.

Included by @file{oct.h} is a definition for the macro
@w{@code{DEFUN_DLD}}@ which creates a dynamically loaded function.  This macro
takes four arguments:

@enumerate 1
@item The function name as it will be seen in Octave,

@item The list of arguments to the function of type @code{octave_value_list},

@item The number of output arguments, which can be---and often is---omitted if
not used, and

@item The string to use for the help text of the function.
@end enumerate

The return type of functions defined with @w{@code{DEFUN_DLD}}@ is always
@code{octave_value_list}.

There are a couple of important considerations in the choice of function name.
First, it must be a valid Octave function name and so must be a sequence of
letters, digits, and underscores not starting with a digit.  Second, as Octave
uses the function name to define the filename it attempts to find the function
in, the function name in the @w{@code{DEFUN_DLD}}@ macro must match the filename
of the oct-file.  Therefore, the above function should be in a file
@file{helloworld.cc}, and would be compiled to an oct-file using the command

@example
mkoctfile helloworld.cc
@end example

This will create a file called @file{helloworld.oct} that is the compiled
version of the function.  It should be noted that it is perfectly acceptable to
have more than one @w{@code{DEFUN_DLD}}@ function in a source file.  However,
there must either be a symbolic link to the oct-file for each of the functions
defined in the source code with the @w{@code{DEFUN_DLD}}@ macro or the
@code{autoload} (@ref{Function Files}) function should be used.

The rest of the function shows how to find the number of input arguments, how
to print through the Octave pager, and how to return from the function.  After
compiling this function as above, an example of its use is

@example
@group
helloworld (1, 2, 3)
@print{} Hello World has 3 input arguments and 0 output arguments.
@end group
@end example

Subsequent sections show how to use specific classes from Octave's core
internals.  Base classes like @code{dMatrix} (a matrix of double values) are
found in the directory @file{liboctave/array}.  The definitive reference for
how to use a particular class is the header file itself.  However, it is often
enough simply to study the examples in the manual in order to be able to use a
class.

@node Matrices and Arrays in Oct-Files
@subsection Matrices and Arrays in Oct-Files

Octave supports a number of different array and matrix classes, the majority of
which are based on the @code{Array} class.  The exception are the sparse matrix
types discussed separately below.  There are three basic matrix types:

@table @code
@item Matrix
A double precision matrix class defined in @file{dMatrix.h}

@item ComplexMatrix
A complex matrix class defined in @file{CMatrix.h}

@item BoolMatrix
A boolean matrix class defined in @file{boolMatrix.h}
@end table

These are the basic two-dimensional matrix types of Octave.  In addition there
are a number of multi-dimensional array types including

@table @code
@item NDArray
A double precision array class defined in @file{dNDArray.h}

@item ComplexNDarray
A complex array class defined in @file{CNDArray.h}

@item boolNDArray
A boolean array class defined in @file{boolNDArray.h}

@item  int8NDArray
@itemx int16NDArray
@itemx int32NDArray
@itemx int64NDArray
8, 16, 32, and 64-bit signed array classes defined in
@file{int8NDArray.h}, @file{int16NDArray.h}, etc.

@item  uint8NDArray
@itemx uint16NDArray
@itemx uint32NDArray
@itemx uint64NDArray
8, 16, 32, and 64-bit unsigned array classes defined in
@file{uint8NDArray.h}, @file{uint16NDArray.h}, etc.
@end table

There are several basic ways of constructing matrices or multi-dimensional
arrays.  Using the class @code{Matrix} as an example one can

@itemize @bullet
@item
Create an empty matrix or array with the empty constructor.  For example:

@example
Matrix a;
@end example

This can be used for all matrix and array types.

@item
Define the dimensions of the matrix or array with a dim_vector which has the
same characteristics as the vector returned from @code{size}.  For example:

@example
@group
dim_vector dv (2, 3);  // 2 rows, 3 columns
Matrix a (dv);
@end group
@end example

This can be used for all matrix and array types.

@item
Define the number of rows and columns in the matrix.  For example:

@example
Matrix a (2, 2)
@end example

This constructor can @strong{only} be used with matrix types.
@end itemize

These types all share a number of basic methods and operators.  Many bear a
resemblance to functions that exist in the interpreter.  A selection of useful
methods include

@deftypefn  {Method} {T&} operator () (octave_idx_type)
@deftypefnx {Method} {T&} elem (octave_idx_type)
The @code{()} operator or @code{elem} method allow the values of the matrix or
array to be read or set.  These methods take a single argument, which is of
type @code{octave_idx_type}, that is the index into the matrix or array.
Additionally, the matrix type allows two argument versions of the @code{()}
operator and @code{elem} method, giving the row and column index of the value
to get or set.
@end deftypefn

Note that these functions do significant error checking and so in some
circumstances the user might prefer to access the data of the array or matrix
directly through the @code{rwdata} method discussed below.

@deftypefn {Method} {octave_idx_type} numel () const
The total number of elements in the matrix or array.
@end deftypefn

@deftypefn {Method} {size_t} byte_size () const
The number of bytes used to store the matrix or array.
@end deftypefn

@deftypefn {Method} {dim_vector} dims () const
The dimensions of the matrix or array in value of type @code{dim_vector}.
@end deftypefn

@deftypefn {Method} {int} ndims () const
The number of dimensions of the matrix or array.  Matrices are always 2-D, but
arrays can be N-dimensional.
@end deftypefn

@deftypefn  {Method} {void} resize (const dim_vector&)
@deftypefnx {Method} {void} resize (nrows, ncols)
A method taking either an argument of type @code{dim_vector}, or, in the case
of a matrix, two arguments of type @code{octave_idx_type} defining the number
of rows and columns in the matrix.
@end deftypefn

@deftypefn {Method} {T *} rwdata ()
This method returns a pointer to the underlying data of the matrix or array so
that it can be manipulated directly, either within Octave or by an external
library.
@end deftypefn

Operators such as @code{+}, @code{-}, or @code{*} can be used on the majority
of the matrix and array types.  In addition there are a number of methods that
are of interest only for matrices such as @code{transpose}, @code{hermitian},
@code{solve}, etc.

The typical way to extract a matrix or array from the input arguments of
@w{@code{DEFUN_DLD}}@ function is as follows

@example
@group
@verbatim
#include <octave/oct.h>

DEFUN_DLD (addtwomatrices, args, , "Add A to B")
{
  if (args.length () != 2)
    print_usage ();

  NDArray A = args(0).array_value ();
  NDArray B = args(1).array_value ();

  return octave_value (A + B);
}
@end verbatim
@end group
@end example

To avoid segmentation faults causing Octave to abort, this function explicitly
checks that there are sufficient arguments available before accessing these
arguments.  It then obtains two multi-dimensional arrays of type @code{NDArray}
and adds these together.  Note that the @code{array_value} method is called
without using the @code{is_matrix_type} method.  If an error occurs when
attempting to extract the value, Octave will print a message and throw an
exception.  The reason to prefer this coding structure is that the arguments
might be a type which is not an @code{NDArray}, but for which it would make
sense to convert them to one.  The @code{array_value} method allows this
conversion to be performed transparently when possible.  If you need to catch
errors like this, and perform some kind of cleanup or other operation, you can
catch the @code{octave_execution_error} exception.

@code{A + B}, operating on two @code{NDArray} objects returns an
@code{NDArray}, which is cast to an @code{octave_value} on the return from the
function.  An example of the use of this demonstration function is

@example
@group
addtwomatrices (ones (2, 2), eye (2, 2))
      @result{}  2  1
          1  2
@end group
@end example

A list of the basic @code{Matrix} and @code{Array} types, the methods to
extract these from an @code{octave_value}, and the associated header file is
listed below.

@multitable @columnfractions .3 .4 .3
@headitem Type @tab Function @tab Source Code
@item @code{RowVector} @tab @code{row_vector_value} @tab @file{dRowVector.h}
@item @code{ComplexRowVector} @tab @code{complex_row_vector_value} @tab @file{CRowVector.h}
@item @code{ColumnVector} @tab @code{column_vector_value} @tab @file{dColVector.h}
@item @code{ComplexColumnVector} @tab @code{complex_column_vector_value} @tab @file{CColVector.h}
@item @code{Matrix} @tab @code{matrix_value} @tab @file{dMatrix.h}
@item @code{ComplexMatrix} @tab @code{complex_matrix_value} @tab @file{CMatrix.h}
@item @code{boolMatrix} @tab @code{bool_matrix_value} @tab @file{boolMatrix.h}
@item @code{charMatrix} @tab @code{char_matrix_value} @tab @file{chMatrix.h}
@item @code{NDArray} @tab @code{array_value} @tab @file{dNDArray.h}
@item @code{ComplexNDArray} @tab @code{complex_array_value} @tab @file{CNDArray.h}
@item @code{boolNDArray} @tab @code{bool_array_value} @tab @file{boolNDArray.h}
@item @code{charNDArray} @tab @code{char_array_value} @tab @file{charNDArray.h}
@item @code{int8NDArray} @tab @code{int8_array_value} @tab @file{int8NDArray.h}
@item @code{int16NDArray} @tab @code{int16_array_value} @tab @file{int16NDArray.h}
@item @code{int32NDArray} @tab @code{int32_array_value} @tab @file{int32NDArray.h}
@item @code{int64NDArray} @tab @code{int64_array_value} @tab @file{int64NDArray.h}
@item @code{uint8NDArray} @tab @code{uint8_array_value} @tab @file{uint8NDArray.h}
@item @code{uint16NDArray} @tab @code{uint16_array_value} @tab @file{uint16NDArray.h}
@item @code{uint32NDArray} @tab @code{uint32_array_value} @tab @file{uint32NDArray.h}
@item @code{uint64NDArray} @tab @code{uint64_array_value} @tab @file{uint64NDArray.h}
@end multitable

@node Character Strings in Oct-Files
@subsection Character Strings in Oct-Files

A character string in Octave is just a special @code{Array} class.  Consider
the example:

@example
@verbatim
#include <octave/oct.h>

DEFUN_DLD (stringdemo, args, , "String Demo")
{
  if (args.length () != 1)
    print_usage ();

  octave_value_list retval;

  charMatrix ch = args(0).char_matrix_value ();

  retval(1) = octave_value (ch, '\'');  // Single Quote String

  octave_idx_type nr = ch.rows ();

  for (octave_idx_type i = 0; i < nr / 2; i++)
    {
      std::string tmp = ch.row_as_string (i);

      ch.insert (ch.row_as_string (nr-i-1).c_str (), i, 0);
      ch.insert (tmp.c_str (), nr-i-1, 0);
    }

  retval(0) = octave_value (ch, '"');  // Double Quote String

  return retval;
}
@end verbatim
@end example

An example of the use of this function is

@example
@group
s0 = ["First String"; "Second String"];
[s1,s2] = stringdemo (s0)
@result{} s1 = Second String
        First String

@result{} s2 = First String
        Second String

typeinfo (s2)
@result{} sq_string
typeinfo (s1)
@result{} string
@end group
@end example

One additional complication of strings in Octave is the difference between
single quoted and double quoted strings.  To find out if an @code{octave_value}
contains a single or double quoted string use one of the predicate tests shown
below.

@example
@group
if (args(0).is_sq_string ())
  octave_stdout << "First argument is a single quoted string\n";
else if (args(0).is_dq_string ())
  octave_stdout << "First argument is a double quoted string\n";
@end group
@end example

Note, however, that both types of strings are represented by the
@code{charNDArray} type, and so when assigning to an @code{octave_value}, the
type of string should be specified.  For example:

@example
@group
octave_value_list retval;
charNDArray ch;
@dots{}
// Create single quoted string
retval(1) = octave_value (ch);   // default constructor is sq_string
           OR
retval(1) = octave_value (ch, '\'');  // explicitly create sq_string

// Create a double quoted string
retval(0) = octave_value (ch, '"');
@end group
@end example

@node Cell Arrays in Oct-Files
@subsection Cell Arrays in Oct-Files

Octave's cell type is also available from within oct-files.  A cell array is
just an @code{Array} of @code{octave_value}s, and thus each element of the cell
array can be treated like any other @code{octave_value}.  A simple example is

@example
@verbatim
#include <octave/oct.h>
#include <octave/Cell.h>

DEFUN_DLD (celldemo, args, , "Cell Demo")
{
  if (args.length () != 1)
    print_usage ();

  Cell c = args(0).cell_value ();

  octave_value_list retval;
  retval.resize (c.numel ());    // faster code by pre-declaring size

  for (octave_idx_type i = 0; i < c.numel (); i++)
    {
      retval(i) = c(i);          // using operator syntax
      //retval(i) = c.elem (i);  // using method syntax
    }

  return retval;
}
@end verbatim
@end example

Note that cell arrays are used less often in standard oct-files and so the
@file{Cell.h} header file must be explicitly included.  The rest of the example
extracts the @code{octave_value}s one by one from the cell array and returns
them as individual output arguments.  For example:

@example
@group
[b1, b2, b3] = celldemo (@{1, [1, 2], "test"@})
@result{}
b1 =  1
b2 =

   1   2

b3 = test
@end group
@end example

@node Structures in Oct-Files
@subsection Structures in Oct-Files

A structure in Octave is a map between a number of fields represented and their
values.  The Standard Template Library @code{map} class is used, with the pair
consisting of a @code{std::string} and an Octave @code{Cell} variable.

A simple example demonstrating the use of structures within oct-files is

@example
@verbatim
#include <octave/oct.h>
#include <octave/ov-struct.h>

DEFUN_DLD (structdemo, args, , "Struct Demo")
{
  if (args.length () != 2)
    print_usage ();

  if (! args(0).isstruct ())
    error ("structdemo: ARG1 must be a struct");

  octave_scalar_map arg0 = args(0).scalar_map_value ();
  //octave_map arg0 = args(0).map_value ();

  if (! args(1).is_string ())
    error ("structdemo: ARG2 must be a character string");

  std::string arg1 = args(1).string_value ();

  octave_value tmp = arg0.contents (arg1);
  //octave_value tmp = arg0.contents (arg1)(0);

  if (! tmp.is_defined ())
    error ("structdemo: struct does not have a field named '%s'\n",
           arg1.c_str ());

  octave_scalar_map st;

  st.assign ("selected", tmp);

  return octave_value (st);
}
@end verbatim
@end example

An example of its use is

@example
@group
x.a = 1; x.b = "test"; x.c = [1, 2];
structdemo (x, "b")
@result{} selected = test
@end group
@end example

The example above specifically uses the @code{octave_scalar_map} class which is
for representing a single struct.  For structure arrays, the @code{octave_map}
class is used instead.  The commented code shows how the demo could be modified
to handle a structure array.  In that case, the @code{contents} method returns
a @code{Cell} which may have more than one element.  Therefore, to obtain the
underlying @code{octave_value} in the single struct example we would write

@example
octave_value tmp = arg0.contents (arg1)(0);
@end example

@noindent
where the trailing @code{(0)} is the @code{()} operator on the @code{Cell}
object.  If this were a true structure array with multiple elements we could
iterate over the elements using the @code{()} operator.

Structures are a relatively complex data container and there are more functions
available in @file{oct-map.h} which make coding with them easier than relying
on just @code{contents}.

@node Sparse Matrices in Oct-Files
@subsection Sparse Matrices in Oct-Files

There are three classes of sparse objects that are of interest to the user.

@table @code
@item SparseMatrix
A double precision sparse matrix class

@item SparseComplexMatrix
A complex sparse matrix class

@item SparseBoolMatrix
A boolean sparse matrix class
@end table

All of these classes inherit from the @code{Sparse<T>} template class, and so
all have similar capabilities and usage.  The @code{Sparse<T>} class was based
on Octave's @code{Array<T>} class and users familiar with Octave's
@code{Array} classes will be comfortable with the use of the sparse classes.

The sparse classes will not be entirely described in this section, due to their
similarity with the existing @code{Array} classes.  However, there are a few
differences due the nature of sparse objects, and these will be described.
First, although it is fundamentally possible to have N-dimensional sparse
objects, the Octave sparse classes do not allow them at this time; All
instances of the sparse classes @strong{must} be 2-dimensional.  This means
that @code{SparseMatrix} is actually more similar to Octave's @code{Matrix}
class than it is to the @code{NDArray} class.

@menu
* Array and Sparse Class Differences::
* Creating Sparse Matrices in Oct-Files::
* Using Sparse Matrices in Oct-Files::
@end menu

@node Array and Sparse Class Differences
@subsubsection Array and Sparse Class Differences

The number of elements in a sparse matrix is considered to be the number
of nonzero elements, rather than the product of the dimensions.  Therefore,

@example
@group
SparseMatrix sm;
@dots{}
int nnz = sm.nelem ();
@end group
@end example

@noindent
returns the number of nonzero elements (like the interpreter function
@code{nnz}).  If the user really requires the number of elements in the matrix,
including the nonzero elements, they should use @code{numel} rather than
@code{nelem}.  Note that for very large matrices, where the product of the two
dimensions is larger than the representation of an unsigned int, @code{numel}
can overflow.  An example is @code{speye (1e6)} which will create a matrix with
a million rows and columns, but only a million nonzero elements.  In this case,
the number of rows multiplied by the number of columns is more than two hundred
times the maximum value that can be represented by an unsigned 32-bit int.  The
use of @code{numel} should, therefore, be avoided unless it is known that it
will not overflow.

Extreme care is also required when using the @code{elem} method or the
@code{()} operator which perform essentially the same function.  The reason is
that if a sparse object is non-const, then Octave will assume that a request
for a zero element in a sparse matrix is in fact a request to create this
element so it can be filled.  Therefore, a piece of code like

@example
@group
SparseMatrix sm;
@dots{}
for (int j = 0; j < nc; j++)
  for (int i = 0; i < nr; i++)
    std::cerr << " (" << i << "," << j << "): " << sm(i,j) << "\n";
@end group
@end example

@noindent
is a great way of turning a sparse matrix into a dense one, and a very slow
way at that since it reallocates the sparse object for each zero element in the
matrix.

A simple way of preventing the above from happening is to create a temporary
constant version of the sparse matrix.  Note that only the container for the
sparse matrix will be copied, while the actual representation of the data will
be shared between the two versions of the sparse matrix; This is not a costly
operation.  The example above, re-written to prevent sparse-to-dense
conversion, is

@example
@group
SparseMatrix sm;
@dots{}
const SparseMatrix tmp (sm);
for (int j = 0; j < nc; j++)
  for (int i = 0; i < nr; i++)
    std::cerr << " (" << i << "," << j << "): " << tmp(i,j) << "\n";
@end group
@end example

Finally, because the sparse types aren't represented by a contiguous block of
memory, the @nospell{@code{rwdata}} method of @code{Array<T>} is not
available.  It is, however, replaced by three separate methods @code{ridx},
@code{cidx}, and @code{data}, that access the raw compressed column format that
Octave sparse matrices are stored in.  These methods can be used in a manner
similar to @code{elem} to allow the matrix to be accessed or filled.  However,
it is up to the user to respect the sparse matrix compressed column format or
the matrix will become corrupted.

@node Creating Sparse Matrices in Oct-Files
@subsubsection Creating Sparse Matrices in Oct-Files

There are two useful strategies for creating a sparse matrix.  The first is to
create three vectors representing the row index, column index, and data values,
and from these create the matrix.  The second alternative is to create a sparse
matrix with the appropriate amount of space, and then fill in the values.  Both
techniques have their advantages and disadvantages.

Below is an example of creating a small sparse matrix using the first technique

@example
@group
int nz, nr, nc;
nz = 4, nr = 3, nc = 4;

ColumnVector ridx (nz);
ColumnVector cidx (nz);
ColumnVector data (nz);

ridx(0) = 1; cidx(0) = 1; data(0) = 1;
ridx(1) = 2; cidx(1) = 2; data(1) = 2;
ridx(2) = 2; cidx(2) = 4; data(2) = 3;
ridx(3) = 3; cidx(3) = 4; data(3) = 4;
SparseMatrix sm (data, ridx, cidx, nr, nc);
@end group
@end example

@noindent
which creates the matrix given in section @ref{Storage of Sparse Matrices}.
Note that the compressed matrix format is not used at the time of the creation
of the matrix itself, but is used internally.

As discussed in the chapter on Sparse Matrices, the values of the sparse matrix
are stored in increasing column-major ordering.  Although the data passed by
the user need not respect this requirement, pre-sorting the data will
significantly speed up creation of the sparse matrix.

The disadvantage of this technique for creating a sparse matrix is that there
is a brief time when two copies of the data exist.  For extremely memory
constrained problems this may not be the best technique for creating a sparse
matrix.

The alternative is to first create a sparse matrix with the desired number of
nonzero elements and then later fill those elements in.  Sample code:

@example
@group
int nz, nr, nc;
nz = 4, nr = 3, nc = 4;
SparseMatrix sm (nr, nc, nz);
sm(0,0) = 1; sm(0,1) = 2; sm(1,3) = 3; sm(2,3) = 4;
@end group
@end example

This creates the same matrix as previously.  Again, although not strictly
necessary, it is significantly faster if the sparse matrix is created and the
elements are added in column-major ordering.  The reason for this is that when
elements are inserted at the end of the current list of known elements then no
element in the matrix needs to be moved to allow the new element to be
inserted; Only the column indices need to be updated.

There are a few further points to note about this method of creating a sparse
matrix.  First, it is possible to create a sparse matrix with fewer elements
than are actually inserted in the matrix.  Therefore,

@example
@group
int nr, nc;
nr = 3, nc = 4;
SparseMatrix sm (nr, nc, 0);
sm(0,0) = 1; sm(0,1) = 2; sm(1,3) = 3; sm(2,3) = 4;
@end group
@end example

@noindent
is perfectly valid.  However, it is a very bad idea because as each new element
is added to the sparse matrix the matrix needs to request more space and
reallocate memory.  This is an expensive operation that will significantly slow
this means of creating a sparse matrix.  It is possible to create a sparse
matrix with excess storage, so having @var{nz} greater than 4 in this example
is also valid.  The disadvantage is that the matrix occupies more memory than
strictly needed.

Of course, it is not always possible to know the number of nonzero elements
prior to filling a matrix.  For this reason the additional unused storage of a
sparse matrix can be removed after its creation with the @code{maybe_compress}
function.  In addition to deallocating unused storage, @code{maybe_compress}
can also remove zero elements from the matrix.  The removal of zero elements
from the matrix is controlled by setting the argument of the
@code{maybe_compress} function to be @code{true}.  However, the cost of
removing the zeros is high because it implies re-sorting the elements.  If
possible, it is better for the user to avoid adding the unnecessary zeros in
the first place.  An example of the use of @code{maybe_compress} is

@example
@group
int nz, nr, nc;
nz = 6, nr = 3, nc = 4;

SparseMatrix sm1 (nr, nc, nz);
sm1(0,0) = 1; sm1(0,1) = 2; sm1(1,3) = 3; sm1(2,3) = 4;
sm1.maybe_compress ();   // No zero elements were added

SparseMatrix sm2 (nr, nc, nz);
sm2(0,0) = 1; sm2(0,1) = 2; sm(0,2) = 0; sm(1,2) = 0;
sm1(1,3) = 3; sm1(2,3) = 4;
sm2.maybe_compress (true);  // Zero elements were added
@end group
@end example

The use of the @code{maybe_compress} function should be avoided if possible as
it will slow the creation of the matrix.

A third means of creating a sparse matrix is to work directly with the data in
compressed row format.  An example of this advanced technique might be

@example
octave_value arg;
@dots{}
int nz, nr, nc;
nz = 6, nr = 3, nc = 4;   // Assume we know the max # nz
SparseMatrix sm (nr, nc, nz);
Matrix m = arg.matrix_value ();

int ii = 0;
sm.cidx (0) = 0;
for (int j = 1; j < nc; j++)
  @{
    for (int i = 0; i < nr; i++)
      @{
        double tmp = m(i,j);
        if (tmp != 0.)
          @{
            sm.data(ii) = tmp;
            sm.ridx(ii) = i;
            ii++;
          @}
      @}
    sm.cidx(j+1) = ii;
 @}
sm.maybe_compress ();  // If don't know a priori the final # of nz.
@end example

@noindent
which is probably the most efficient means of creating a sparse matrix.

Finally, it may sometimes arise that the amount of storage initially created is
insufficient to completely store the sparse matrix.  Therefore, the method
@code{change_capacity} exists to reallocate the sparse memory.  The above
example would then be modified as

@example
octave_value arg;
@dots{}
int nz, nr, nc;
nz = 6, nr = 3, nc = 4;   // Guess the number of nz elements
SparseMatrix sm (nr, nc, nz);
Matrix m = arg.matrix_value ();

int ii = 0;
sm.cidx (0) = 0;
for (int j = 1; j < nc; j++)
  @{
    for (int i = 0; i < nr; i++)
      @{
        double tmp = m(i,j);
        if (tmp != 0.)
          @{
            if (ii == nz)
              @{
                nz += 2;   // Add 2 more elements
                sm.change_capacity (nz);
              @}
            sm.data(ii) = tmp;
            sm.ridx(ii) = i;
            ii++;
          @}
      @}
    sm.cidx(j+1) = ii;
 @}
sm.maybe_compress ();  // If don't know a priori the final # of nz.
@end example

Note that both increasing and decreasing the number of nonzero elements in a
sparse matrix is expensive as it involves memory reallocation.  Also because
parts of the matrix, though not its entirety, exist as old and new copies at
the same time, additional memory is needed.  Therefore, if possible avoid
changing capacity.

@node Using Sparse Matrices in Oct-Files
@subsubsection Using Sparse Matrices in Oct-Files

Most of the same operators and functions for sparse matrices that are available
from the Octave interpreter are also available within oct-files.  The basic
means of extracting a sparse matrix from an @code{octave_value}, and returning
it as an @code{octave_value}, can be seen in the following example.

@example
@group
octave_value_list retval;

SparseMatrix sm = args(0).sparse_matrix_value ();
SparseComplexMatrix scm = args(1).sparse_complex_matrix_value ();
SparseBoolMatrix sbm = args(2).sparse_bool_matrix_value ();
@dots{}
retval(2) = sbm;
retval(1) = scm;
retval(0) = sm;
@end group
@end example

The conversion to an @code{octave_value} is handled by the sparse
@code{octave_value} constructors, and so no special care is needed.

@node Accessing Global Variables in Oct-Files
@subsection Accessing Global Variables in Oct-Files

Global variables allow variables in the global scope to be accessed.  Global
variables can be accessed within oct-files by using the support functions
@w{@code{global_varval}}@ and @w{@code{global_assign}}@ from the current
interpreter's symbol table.  Both functions take as first argument a string
representing the variable name to be obtained or assigned.  The second
argument of @w{@code{global_assign}}@ is the value to be assigned.  An
example of the use of these two functions is

@example
@verbatim
#include <octave/oct.h>
#include <octave/interpreter.h>

DEFMETHOD_DLD (globaldemo, interp, args, , "Global Demo")
{
  if (args.length () != 1)
    print_usage ();

  octave_value retval;

  std::string s = args(0).string_value ();

  octave::symbol_table& symtab = interp.get_symbol_table ();

  octave_value tmp = symtab.global_varval (s);

  if (tmp.is_defined ())
    retval = tmp;
  else
    retval = "Global variable not found";

  symtab.global_assign ("a", 42.0);

  return retval;
}
@end verbatim
@end example

An example of its use is

@example
@group
global a b
b = 10;
globaldemo ("b")
@result{} 10
globaldemo ("c")
@result{} "Global variable not found"
num2str (a)
@result{} 42
@end group
@end example

@node Calling Octave Functions from Oct-Files
@subsection Calling Octave Functions from Oct-Files

There is often a need to be able to call another Octave function from within an
oct-file, and there are many examples of such within Octave itself.  For
example, the @code{quad} function is an oct-file that calculates the definite
integral by quadrature over a user-supplied function.

There are also many ways in which a function could be given as input.  It might
be passed as one of

@enumerate 1
@item Function Handle

@item Anonymous Function Handle

@item String
@end enumerate

The code below demonstrates all four methods of passing a function to an
oct-file.

@example
@verbatim
#include <octave/oct.h>
#include <octave/parse.h>

DEFMETHOD_DLD (funcdemo, interp, args, nargout, "Function Demo")
{
  int nargin = args.length ();

  if (nargin < 2)
    print_usage ();

  octave_value_list newargs;

  for (octave_idx_type i = nargin - 1; i > 0; i--)
    newargs(i-1) = args(i);

  octave_value_list retval;

  if (args(0).is_function_handle () || args(0).is_inline_function ()
      || args(0).is_string ())
    retval = interp.feval (args(0), newargs, nargout);
  else
    error ("funcdemo: INPUT must be string, inline, or function handle");

  return retval;
}
@end verbatim
@end example

The first input to the demonstration code is a user-supplied function and the
remaining arguments are all passed to the function.

@example
@group
funcdemo (@@sin, 1)
@result{} 0.84147
funcdemo (@@(x) sin (x), 1)
@result{} 0.84147
funcdemo ("sin", 1)
@result{} 0.84147
funcdemo (@@atan2, 1, 1)
@result{} 0.78540
@end group
@end example

When the user function is passed as a string the treatment of the function is
different.  In some cases it is necessary to have the user supplied function as
an @code{octave_function} object.  In that case the string argument can be used
to create a temporary function as demonstrated below.

@example
@group
std::octave fcn_name = unique_symbol_name ("__fcn__");
std::string fcode = "function y = ";
fcode.append (fcn_name);
fcode.append ("(x) y = ");
fcn = extract_function (args(0), "funcdemo", fcn_name,
                        fcode, "; endfunction");
@dots{}
if (fcn_name.length ())
  clear_function (fcn_name);
@end group
@end example

There are two important things to know in this case.  First, the number of
input arguments to the user function is fixed, and in the above example is a
single argument.  Second, to avoid leaving the temporary function in the Octave
symbol table it should be cleared after use.  Also, by convention all internal
function names begin and end with the character sequence @samp{__}.

@node Calling External Code from Oct-Files
@subsection Calling External Code from Oct-Files

Linking external C code to Octave is relatively simple, as the C functions can
easily be called directly from C++.  One possible issue is that the
declarations of the external C functions may need to be explicitly defined as C
functions to the compiler.  If the declarations of the external C functions are
in the header @file{foo.h}, then the tactic to ensure that the C++ compiler
treats these declarations as C code is

@example
@group
#ifdef __cplusplus
extern "C"
@{
#endif
#include "foo.h"
#ifdef __cplusplus
@}  /* end extern "C" */
#endif
@end group
@end example

When calling functions that are implemented in Fortran code, some peculiarities
have to be taken into account.  Symbol names in Fortran are case-insensitive,
and depending on the used Fortran compiler, function names are either exported
with all lowercase or with all uppercase characters.  Additionally, some
compilers append none, one or two underscores "@code{_}" at the end of
exported function names.  This is called "name-mangling".

Octave supplies macros that allow writing code that automatically handles the
name-mangling for a number of different Fortran compilers.  These macros are
@w{@env{F77_FUNC}} and @w{@env{F77_FUNC_}}.  The former should be used for
Fortran functions that do not contain any underscores in their name.  The
latter should be used for Fortran functions with underscores in their names.
Both macros take two arguments: The first is the Fortran function name in all
lowercase characters.  The second is the same Fortran function name in all
uppercase characters.

Additionally to the name-mangling, different compilers are using different
calling conventions for some types.  Octave defines the following preprocessor
macros to allow writing code that can be used with different Fortran calling
conventions.

Note that we don't attempt to handle Fortran functions, we always use
subroutine wrappers for them and pass the return value as an extra argument.

Use the following macros to pass character strings from C to Fortran:

@example
@group
  F77_CHAR_ARG(x)
  F77_CONST_CHAR_ARG(x)
  F77_CXX_STRING_ARG(x)
  F77_CHAR_ARG_LEN(l)
  F77_CHAR_ARG_DECL
  F77_CONST_CHAR_ARG_DECL
  F77_CHAR_ARG_LEN_DECL
@end group
@end example

Use the following macros to write C-language functions that accept
Fortran-style character strings:

@example
@group
  F77_CHAR_ARG_DEF(s, len)
  F77_CONST_CHAR_ARG_DEF(s, len)
  F77_CHAR_ARG_LEN_DEF(len)
  F77_CHAR_ARG_USE(s)
  F77_CHAR_ARG_LEN_USE(s, len)
@end group
@end example

Use the following macros for Fortran types in C++ code:

@table @code
@item F77_INT4
Equivalent to Fortran @code{INTEGER*4} type

@item F77_DBLE
Equivalent to Fortran @code{DOUBLE PRECISION} type

@item F77_REAL
Equivalent to Fortran @code{REAL} type

@item F77_CMPLX
Equivalent to Fortran @code{COMPLEX} type

@item F77_DBLE_CMPLX
Equivalent to Fortran @code{DOUBLE COMPLEX} type

@item F77_LOGICAL
Equivalent to Fortran @code{LOGICAL} type

@item F77_RET_T
Return type of a C++ function that acts like a Fortran subroutine.
@end table

Use the following macros to return from C-language functions that are supposed
to act like Fortran subroutines.  @w{@env{F77_NORETURN}} is intended to be used
as the last statement of such a function that has been tagged with a
@nospell{@qcode{"noreturn"}} attribute.

@example
@group
  F77_RETURN(retval)
  F77_NORETURN(retval)
@end group
@end example

The underlying Fortran code should use the @code{XSTOPX} function to replace
the Fortran @code{STOP} function.  @code{XSTOPX} uses the Octave exception
handler to treat failing cases in the Fortran code explicitly.  Note that
Octave supplies its own replacement @sc{blas} @code{XERBLA} function, which
uses @code{XSTOPX}.

The following example shows the inclusion of a Fortran function in an oct-file,
where the C++ wrapper is

@example
@verbatim
#include <octave/oct.h>
#include <octave/f77-fcn.h>

extern "C"
{
  F77_RET_T
  F77_FUNC (fortransub, FORTRANSUB)
    (const F77_INT&, F77_DBLE*, F77_CHAR_ARG_DECL F77_CHAR_ARG_LEN_DECL);
}

DEFUN_DLD (fortrandemo, args, , "Fortran Demo")
{
  if (args.length () != 1)
    print_usage ();

  NDArray a = args(0).array_value ();

  double *av = a.rwdata ();
  octave_idx_type na = a.numel ();

  OCTAVE_LOCAL_BUFFER (char, ctmp, 128);

  F77_FUNC (fortransub, FORTRANSUB)
            (na, av, ctmp F77_CHAR_ARG_LEN (128));

  return ovl (a, std::string (ctmp));
}
@end verbatim
@end example

@noindent
and the Fortran function is

@example
@verbatim
      subroutine fortransub (n, a, s)
      implicit none
      character*(*) s
      real*8 a(*)
      integer*4 i, n, ioerr
      do i = 1, n
        if (a(i) .eq. 0d0) then
          call xstopx ('fortransub: divide by zero')
        else
          a(i) = 1d0 / a(i)
        endif
      enddo
      write (unit = s, fmt = '(a,i3,a,a)', iostat = ioerr)
     $       'There are ', n,
     $       ' values in the input vector', char(0)
      if (ioerr .ne. 0) then
        call xstopx ('fortransub: error writing string')
      endif
      return
      end
@end verbatim
@end example

This example demonstrates most of the features needed to link to an external
Fortran function, including passing arrays and strings, as well as exception
handling.  Both the Fortran and C++ files need to be compiled in order for the
example to work.

@example
@group
mkoctfile fortrandemo.cc fortransub.f
[b, s] = fortrandemo (1:3)
@result{}
  b = 1.00000   0.50000   0.33333
  s = There are   3 values in the input vector
[b, s] = fortrandemo (0:3)
error: fortrandemo: fortransub: divide by zero
@end group
@end example

@node Allocating Local Memory in Oct-Files
@subsection Allocating Local Memory in Oct-Files

Allocating memory within an oct-file might seem easy, as the C++ new/delete
operators can be used.  However, in that case great care must be taken to avoid
memory leaks.  The preferred manner in which to allocate memory for use locally
is to use the @w{@code{OCTAVE_LOCAL_BUFFER}}@ macro.  An example of its use is

@example
OCTAVE_LOCAL_BUFFER (double, tmp, len)
@end example

@noindent
that returns a pointer @code{tmp} of type @code{double *} of length @code{len}.

In this case, Octave itself will worry about reference counting and variable
scope and will properly free memory without programmer intervention.

@node Input Parameter Checking in Oct-Files
@subsection Input Parameter Checking in Oct-Files

Because oct-files are compiled functions they open up the possibility of
crashing Octave through careless function calls or memory faults.  It is quite
important that each and every function have a sufficient level of parameter
checking to ensure that Octave behaves well.

The minimum requirement, as previously discussed, is to check the number of
input arguments before using them to avoid referencing a nonexistent argument.
However, in some cases this might not be sufficient as the underlying code
imposes further constraints.  For example, an external function call might be
undefined if the input arguments are not integers, or if one of the arguments
is zero, or if the input is complex and a real value was expected.  Therefore,
oct-files often need additional input parameter checking.

There are several functions within Octave that can be useful for the purposes
of parameter checking.  These include the methods of the @code{octave_value}
class like @code{is_real_matrix}, @code{is_numeric_type}, etc. (see
@file{ov.h}).  Often, with a knowledge of the Octave m-file language, you can
guess at what the corresponding C++ routine will.  In addition there are some
more specialized input validation functions of which a few are demonstrated
below.

@example
@verbatim
#include <octave/oct.h>

DEFUN_DLD (paramdemo, args, nargout, "Parameter Check Demo")
{
  if (args.length () != 1)
    print_usage ();

  NDArray m = args(0).array_value ();

  double min_val = -10.0;
  double max_val = 10.0;

  octave_stdout << "Properties of input array:\n";

  if (m.any_element_is_negative ())
    octave_stdout << "  includes negative values\n";

  if (m.any_element_is_inf_or_nan ())
    octave_stdout << "  includes Inf or NaN values\n";

  if (m.any_element_not_one_or_zero ())
    octave_stdout << "  includes other values than 1 and 0\n";

  if (m.all_elements_are_int_or_inf_or_nan ())
    octave_stdout << "  includes only int, Inf or NaN values\n";

  if (m.all_integers (min_val, max_val))
    octave_stdout << "  includes only integers in [-10,10]\n";

  return octave_value_list ();
}
@end verbatim
@end example

@noindent
An example of its use is:

@example
@group
paramdemo ([1, 2, NaN, Inf])
@result{} Properties of input array:
     includes Inf or NaN values
     includes other values than 1 and 0
     includes only int, Inf or NaN values
@end group
@end example

@node Exception and Error Handling in Oct-Files
@subsection Exception and Error Handling in Oct-Files

Another important feature of Octave is its ability to react to the user typing
@key{Control-C} during extended calculations.  This ability is based on the C++
exception handler, where memory allocated by the C++ new/delete methods is
automatically released when the exception is treated.  When writing an oct-file
which may run for a long time the programmer must periodically use the macro
@w{@code{OCTAVE_QUIT}}, in order to allow Octave to check and possibly respond
to a user typing @key{Control-C}.  For example:

@example
@group
for (octave_idx_type i = 0; i < a.nelem (); i++)
  @{
    OCTAVE_QUIT;
    b.elem (i) = 2. * a.elem (i);
  @}
@end group
@end example

The presence of the @w{@code{OCTAVE_QUIT}}@ macro in the inner loop allows
Octave to detect and acknowledge a @key{Control-C} key sequence.  Without this
macro, the user must either wait for the oct-file function to return before the
interrupt is processed, or the user must press @key{Control-C} three times
which will force Octave to exit completely.

The @w{@code{OCTAVE_QUIT}}@ macro does impose a very small performance penalty;
For loops that are known to be small it may not make sense to include
@w{@code{OCTAVE_QUIT}}.

When creating an oct-file that uses an external library, the function might
spend a significant portion of its time in the external library.  It is not
generally possible to use the @w{@code{OCTAVE_QUIT}}@ macro in this case.  The
alternative code in this case is

@example
@group
BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
@dots{} some code that calls a "foreign" function @dots{}
END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
@end group
@end example

The disadvantage of this is that if the foreign code allocates any memory
internally, then this memory might be lost during an interrupt, without being
deallocated.  Therefore, ideally Octave itself should allocate any memory that
is needed by the foreign code, with either the @nospell{@code{rwdata}}
method or the @w{@code{OCTAVE_LOCAL_BUFFER}}@ macro.

The Octave @code{unwind_protect} mechanism (@ref{The unwind_protect Statement})
can also be used in oct-files.  In conjunction with the exception handling of
Octave, it ensures that certain recovery code is always run even if an
exception occurs.  An example of the use of this mechanism is

@example
@verbatim
#include <octave/oct.h>
#include <octave/unwind-prot.h>

void
my_err_handler (const char *fmt, ...)
{
  // Do nothing!!
}

void
my_err_with_id_handler (const char *id, const char *fmt, ...)
{
  // Do nothing!!
}

DEFUN_DLD (unwinddemo, args, nargout, "Unwind Demo")
{
  if (args.length () < 2)
    print_usage ();

  NDArray a = args(0).array_value ();
  NDArray b = args(1).array_value ();

  // Create unwind_action objects.  At the end of the enclosing scope,
  // destructors for these objects will call the given functions with
  // the specified arguments.

  octave::unwind_action restore_warning_handler
    (set_liboctave_warning_handler, current_liboctave_warning_handler);

  octave::unwind_action restore_warning_with_id_handler
    (set_liboctave_warning_with_id_handler,
     current_liboctave_warning_with_id_handler);

  set_liboctave_warning_handler (my_err_handler);
  set_liboctave_warning_with_id_handler (my_err_with_id_handler);

  return octave_value (quotient (a, b));
}
@end verbatim
@end example

As can be seen in the example:

@example
@group
unwinddemo (1, 0)
@result{} Inf
1 / 0
@result{} warning: division by zero
   Inf
@end group
@end example

The warning for division by zero (and in fact all warnings) are disabled in the
@code{unwinddemo} function.

@node Documentation and Testing of Oct-Files
@subsection Documentation and Testing of Oct-Files

The documentation for an oct-file is contained in the fourth string parameter
of the @w{@code{DEFUN_DLD}}@ macro.  This string can be formatted in the same
manner as the help strings for user functions, however there are some issues
that are particular to the formatting of help strings within oct-files.

The major issue is that the help string will typically be longer than a single
line of text, and so the formatting of long multi-line help strings needs to be
taken into account.  There are several possible solutions, but the most common
is illustrated in the following example,

@example
@group
DEFUN_DLD (do_what_i_want, args, nargout,
  "-*- texinfo -*-\n\
@@deftypefn @{@} @{@} do_what_i_say (@@var@{n@})\n\
A function that does what the user actually wants rather\n\
than what they requested.\n\
@@end deftypefn")
@{
@dots{}
@}
@end group
@end example

@noindent
where each line of text is terminated by @code{\n\} which is an embedded
newline in the string together with a C++ string continuation character.  Note
that the final @code{\} must be the last character on the line.

Octave also includes the ability to embed test and demonstration code for a
function within the code itself (@pxref{Test and Demo Functions}).  This can be
used from within oct-files (or in fact any file) with certain provisos.  First,
the test and demo functions of Octave look for @code{%!} as the first two
characters of a line to identify test and demonstration code.  This is a
requirement for oct-files as well.  In addition, the test and demonstration
code must be wrapped in a comment block to avoid it being interpreted by the
compiler.  Finally, the Octave test and demonstration code must have access to
the original source code of the oct-file---not just the compiled code---as the
tests are stripped from the compiled code.  An example in an oct-file might be

@example
@group
/*
%!assert (sin ([1,2]), [sin(1),sin(2)])
%!error (sin ())
%!error (sin (1,1))
*/
@end group
@end example

@c @node Application Programming Interface for Oct-Files
@c @subsection Application Programming Interface for Oct-Files
@c
@c WRITE ME, using Coda section 1.3 as a starting point.

@node Mex-Files
@section Mex-Files
@cindex mex-files
@cindex mex

Octave includes an interface to allow legacy mex-files to be compiled and used
with Octave.  This interface can also be used to share compiled code between
Octave and @sc{matlab} users.  However, as mex-files expose @sc{matlab}'s
internal API, and the internal structure of Octave is different, a mex-file can
never have the same performance in Octave as the equivalent oct-file.  In
particular, to support the manner in which variables are passed to mex
functions there are a significant number of additional copies of memory blocks
when invoking or returning from a mex-file function.  For this reason, it is
recommended that any new code be written with the oct-file interface previously
discussed.

@menu
* Getting Started with Mex-Files::
* Working with Matrices and Arrays in Mex-Files::
* Character Strings in Mex-Files::
* Cell Arrays with Mex-Files::
* Structures with Mex-Files::
* Sparse Matrices with Mex-Files::
* Calling Other Functions in Mex-Files::
@c * Application Programming Interface for Mex-Files::
@end menu

@node Getting Started with Mex-Files
@subsection Getting Started with Mex-Files

The basic command to build a mex-file is either @code{mkoctfile --mex} or
@code{mex}.  The first command can be used either from within Octave or from
the command line.  To avoid issues with @sc{matlab}'s own @code{mex} command,
the use of the command @code{mex} is limited to within Octave.  Compiled
mex-files have the extension @file{.mex}.

@c mex scripts/miscellaneous/mex.m
@anchor{XREFmex}
@html
<span style="display:block; margin-top:-4.5ex;">&nbsp;</span>
@end html


@deftypefn  {} {} mex [-options] file @dots{}
@deftypefnx {} {@code{status} =} mex (@dots{})
Compile source code written in C, C++, or Fortran, to a MEX file.

@var{status} is the return status of the @code{mkoctfile} function.

If the compilation fails, and the output argument is not requested,
an error is raised.  If the programmer requests @var{status}, however,
Octave will merely issue a warning and it is the programmer's responsibility
to verify the command was successful.

This is equivalent to @code{mkoctfile --mex [-options] file}.

@xseealso{@ref{XREFmkoctfile,,mkoctfile}, @ref{XREFmexext,,mexext}}
@end deftypefn


@c mexext scripts/miscellaneous/mexext.m
@anchor{XREFmexext}
@html
<span style="display:block; margin-top:-4.5ex;">&nbsp;</span>
@end html


@deftypefn {} {@var{ext} =} mexext ()
Return the filename extension used for MEX files.

Programming Note: Octave uses the extension @file{mex} for all MEX files
regardless of the operating system (Linux, Windows, Apple) or the bit-width
(32-bit or 64-bit) of the hardware.
@xseealso{@ref{XREFmex,,mex}}
@end deftypefn


Consider the following short example:

@example
@group
@verbatim
#include "mex.h"

void
mexFunction (int nlhs, mxArray *plhs[],
             int nrhs, const mxArray *prhs[])
{
  mexPrintf ("Hello, World!\n");

  mexPrintf ("I have %d inputs and %d outputs\n", nrhs, nlhs);

  /* Return empty matrices for any outputs */
  int i;
  for (i = 0; i < nlhs; i++)
    plhs[i] = mxCreateDoubleMatrix (0, 0, mxREAL);
}
@end verbatim
@end group
@end example

The first line @code{#include "mex.h"} makes available all of the definitions
necessary for a mex-file.  One important difference between Octave and
@sc{matlab} is that the header file @qcode{"matrix.h"} is implicitly included
through the inclusion of @qcode{"mex.h"}.  This is necessary to avoid a
conflict with the Octave file @qcode{"Matrix.h"} for operating systems and
compilers that don't distinguish between filenames in upper and lower case.

The entry point into the mex-file is defined by @code{mexFunction}.  The
function takes four arguments:

@enumerate 1
@item The number of return arguments (# of left-hand side args).

@item An array of pointers to return arguments.

@item The number of input arguments (# of right-hand side args).

@item An array of pointers to input arguments.
@end enumerate

Note that the function name definition is not explicitly included in
@code{mexFunction} and so there can only be a single @code{mexFunction} entry
point per file.  Instead, the name of the function as seen in Octave is
determined by the name of the mex-file itself minus the extension.  If the
above function is in the file @file{myhello.c}, it can be compiled with

@example
mkoctfile --mex myhello.c
@end example

@noindent
which creates a file @file{myhello.mex}.  The function can then be run from
Octave as

@example
@group
myhello (1,2,3)
@result{} Hello, World!
@result{} I have 3 inputs and 0 outputs
@end group
@end example

It should be noted that the mex-file contains no help string.  To document
mex-files, there should exist an m-file in the same directory as the mex-file
itself.  Taking the above as an example, there would need to be a file
@file{myhello.m} which might contain the text

@example
%MYHELLO Simple test of the functionality of a mex-file.
@end example

In this case, the function that will be executed within Octave will be given by
the mex-file, while the help string will come from the m-file.  This can also
be useful to allow a sample implementation of the mex-file within the Octave
language itself for testing purposes.

Although there cannot be multiple entry points in a single mex-file, one can
use the @code{mexFunctionName} function to determine what name the mex-file was
called with.  This can be used to alter the behavior of the mex-file based on
the function name.  For example, if

@example
@group
@verbatim
#include "mex.h"

void
mexFunction (int nlhs, mxArray *plhs[],
             int nrhs, const mxArray *prhs[])
{
  const char *nm;

  nm = mexFunctionName ();
  mexPrintf ("You called function: %s\n", nm);
  if (strcmp (nm, "myfunc") == 0)
    mexPrintf ("This is the principal function\n", nm);

  return;
}
@end verbatim
@end group
@end example

@noindent
is in the file @file{myfunc.c}, and is compiled with

@example
@group
mkoctfile --mex myfunc.c
ln -s myfunc.mex myfunc2.mex
@end group
@end example

@noindent
then as can be seen by

@example
@group
myfunc ()
@result{} You called function: myfunc
    This is the principal function
myfunc2 ()
@result{} You called function: myfunc2
@end group
@end example

@noindent
the behavior of the mex-file can be altered depending on the function's name.

Although the user should only include @file{mex.h} in their code, Octave
declares additional functions, typedefs, etc., available to the user to write
mex-files in the headers @file{mexproto.h} and @file{mxarray.h}.

@node Working with Matrices and Arrays in Mex-Files
@subsection Working with Matrices and Arrays in Mex-Files

The basic mex type of all variables is @code{mxArray}.  Any object, such as a
matrix, cell array, or structure, is stored in this basic type.  @code{mxArray}
serves essentially the same purpose as the @code{octave_value} class in
oct-files in that it acts as a container for all the more specialized types.

The @code{mxArray} structure contains at a minimum, the name of the variable it
represents, its dimensions, its type, and whether the variable is real or
complex.  It can also contain a number of additional fields depending on the
type of the @code{mxArray}.  There are a number of functions to create
@code{mxArray} structures, including @code{mxCreateDoubleMatrix},
@code{mxCreateCellArray}, @code{mxCreateSparse}, and the generic
@code{mxCreateNumericArray}.

The basic function to access the data in an array is @code{mxGetPr}.  Because
the mex interface assumes that real and imaginary parts of a complex array are
stored separately, there is an equivalent function @code{mxGetPi} that gets the
imaginary part.  Both of these functions are only for use with double precision
matrices.  The generic functions @code{mxGetData} and @code{mxGetImagData}
perform the same operation for all matrix types.  For example:

@example
@group
mxArray *m;
mwSize *dims;
UINT32_T *pr;

dims = (mwSize *) mxMalloc (2 * sizeof (mwSize));
dims[0] = 2; dims[1] = 2;
m = mxCreateNumericArray (2, dims, mxUINT32_CLASS, mxREAL);
pr = (UINT32_T *) mxGetData (m);
@end group
@end example

There are also the functions @code{mxSetPr}, etc., that perform the inverse,
and set the data of an array to use the block of memory pointed to by the
argument of @code{mxSetPr}.

Note the type @code{mwSize} used above, and also @code{mwIndex}, are defined as
the native precision of the indexing in Octave on the platform on which the
mex-file is built.  This allows both 32- and 64-bit platforms to support
mex-files.  @code{mwSize} is used to define array dimensions and the maximum
number or elements, while @code{mwIndex} is used to define indexing into
arrays.

An example that demonstrates how to work with arbitrary real or complex double
precision arrays is given by the file @file{mypow2.c} shown below.

@example
@verbatim
#include "mex.h"

void
mexFunction (int nlhs, mxArray *plhs[],
             int nrhs, const mxArray *prhs[])
{
  mwSize n;
  mwIndex i;
  double *vri, *vro;

  if (nrhs != 1 || ! mxIsDouble (prhs[0]))
    mexErrMsgTxt ("ARG1 must be a double matrix");

  n = mxGetNumberOfElements (prhs[0]);
  plhs[0] = mxCreateNumericArray (mxGetNumberOfDimensions (prhs[0]),
                                  mxGetDimensions (prhs[0]),
                                  mxGetClassID (prhs[0]),
                                  mxIsComplex (prhs[0]));
  vri = mxGetPr (prhs[0]);
  vro = mxGetPr (plhs[0]);

  if (mxIsComplex (prhs[0]))
    {
      double *vii, *vio;
      vii = mxGetPi (prhs[0]);
      vio = mxGetPi (plhs[0]);

      for (i = 0; i < n; i++)
        {
          vro[i] = vri[i] * vri[i] - vii[i] * vii[i];
          vio[i] = 2 * vri[i] * vii[i];
        }
    }
  else
    {
      for (i = 0; i < n; i++)
        vro[i] = vri[i] * vri[i];
    }
}
@end verbatim
@end example

@noindent
An example of its use is

@example
@group
b = randn (4,1) + 1i * randn (4,1);
all (b.^2 == mypow2 (b))
@result{} 1
@end group
@end example

The example above uses the functions @code{mxGetDimensions},
@code{mxGetNumberOfElements}, and @code{mxGetNumberOfDimensions} to work with
the dimensions of multi-dimensional arrays.  The functions @code{mxGetM}, and
@code{mxGetN} are also available to find the number of rows and columns in a
2-D matrix (@nospell{MxN} matrix).

@node Character Strings in Mex-Files
@subsection Character Strings in Mex-Files

As mex-files do not make the distinction between single and double quoted
strings that Octave does, there is perhaps less complexity in the use of
strings and character matrices.  An example of their use that parallels the
demo in @file{stringdemo.cc} is given in the file @file{mystring.c}, as shown
below.

@smallexample
@verbatim
#include <string.h>
#include "mex.h"

void
mexFunction (int nlhs, mxArray *plhs[],
             int nrhs, const mxArray *prhs[])
{
  mwSize m, n;
  mwIndex i, j;
  mxChar *pi, *po;

  if (nrhs != 1 || ! mxIsChar (prhs[0])
      || mxGetNumberOfDimensions (prhs[0]) > 2)
    mexErrMsgTxt ("ARG1 must be a char matrix");

  m = mxGetM (prhs[0]);
  n = mxGetN (prhs[0]);
  pi = mxGetChars (prhs[0]);
  plhs[0] = mxCreateNumericMatrix (m, n, mxCHAR_CLASS, mxREAL);
  po = mxGetChars (plhs[0]);

  for (j = 0; j < n; j++)
    for (i = 0; i < m; i++)
      po[j*m + m - 1 - i] = pi[j*m + i];
}
@end verbatim
@end smallexample

@noindent
An example of its expected output is

@example
@group
mystring (["First String"; "Second String"])
@result{} Second String
   First String
@end group
@end example

Other functions in the mex interface for handling character strings are
@code{mxCreateString}, @code{mxArrayToString}, and
@code{mxCreateCharMatrixFromStrings}.  In a mex-file, a character string is
considered to be a vector rather than a matrix.  This is perhaps an arbitrary
distinction as the data in the @code{mxArray} for the matrix is consecutive in
any case.

@node Cell Arrays with Mex-Files
@subsection Cell Arrays with Mex-Files

One can perform exactly the same operations on Cell arrays in mex-files as in
oct-files.  An example that duplicates the function of the @file{celldemo.cc}
oct-file in a mex-file is given by @file{mycell.c} as shown below.

@example
@verbatim
#include "mex.h"

void
mexFunction (int nlhs, mxArray *plhs[],
             int nrhs, const mxArray *prhs[])
{
  mwSize n;
  mwIndex i;

  if (nrhs != 1 || ! mxIsCell (prhs[0]))
    mexErrMsgTxt ("ARG1 must be a cell");

  n = mxGetNumberOfElements (prhs[0]);
  n = (n > nlhs ? nlhs : n);

  for (i = 0; i < n; i++)
    plhs[i] = mxDuplicateArray (mxGetCell (prhs[0], i));
}
@end verbatim
@end example

@noindent
The output is identical to the oct-file version as well.

@example
@group
[b1, b2, b3] = mycell (@{1, [1, 2], "test"@})
@result{}
b1 =  1
b2 =

   1   2

b3 = test
@end group
@end example

Note in the example the use of the @code{mxDuplicateArray} function.  This is
needed as the @code{mxArray} pointer returned by @code{mxGetCell} might be
deallocated.  The inverse function to @code{mxGetCell}, used for setting Cell
values, is @code{mxSetCell} and is defined as

@example
void mxSetCell (mxArray *ptr, int idx, mxArray *val);
@end example

Finally, to create a cell array or matrix, the appropriate functions are

@example
@group
mxArray *mxCreateCellArray (int ndims, const int *dims);
mxArray *mxCreateCellMatrix (int m, int n);
@end group
@end example

@node Structures with Mex-Files
@subsection Structures with Mex-Files

The basic function to create a structure in a mex-file is
@code{mxCreateStructMatrix} which creates a structure array with a two
dimensional matrix, or @code{mxCreateStructArray}.

@example
@group
mxArray *mxCreateStructArray (int ndims, int *dims,
                              int num_keys,
                              const char **keys);
mxArray *mxCreateStructMatrix (int rows, int cols,
                               int num_keys,
                               const char **keys);
@end group
@end example

Accessing the fields of the structure can then be performed with
@code{mxGetField} and @code{mxSetField} or alternatively with the
@code{mxGetFieldByNumber} and @code{mxSetFieldByNumber} functions.

@example
@group
mxArray *mxGetField (const mxArray *ptr, mwIndex index,
                     const char *key);
mxArray *mxGetFieldByNumber (const mxArray *ptr,
                             mwIndex index, int key_num);
void mxSetField (mxArray *ptr, mwIndex index,
                 const char *key, mxArray *val);
void mxSetFieldByNumber (mxArray *ptr, mwIndex index,
                         int key_num, mxArray *val);
@end group
@end example

A difference between the oct-file interface to structures and the mex-file
version is that the functions to operate on structures in mex-files directly
include an @code{index} over the elements of the arrays of elements per
@code{field}; Whereas, the oct-file structure includes a Cell Array per field
of the structure.

An example that demonstrates the use of structures in a mex-file can be found
in the file @file{mystruct.c} shown below.

@smallexample
@verbatim
#include "mex.h"

void
mexFunction (int nlhs, mxArray *plhs[],
             int nrhs, const mxArray *prhs[])
{
  int i;
  mwIndex j;
  mxArray *v;
  const char *keys[] = { "this", "that" };

  if (nrhs != 1 || ! mxIsStruct (prhs[0]))
    mexErrMsgTxt ("ARG1 must be a struct");

  for (i = 0; i < mxGetNumberOfFields (prhs[0]); i++)
    for (j = 0; j < mxGetNumberOfElements (prhs[0]); j++)
      {
        mexPrintf ("field %s(%d) = ", mxGetFieldNameByNumber (prhs[0], i), j);
        v = mxGetFieldByNumber (prhs[0], j, i);
        mexCallMATLAB (0, NULL, 1, &v, "disp");
      }

  v = mxCreateStructMatrix (2, 2, 2, keys);

  mxSetFieldByNumber (v, 0, 0, mxCreateString ("this1"));
  mxSetFieldByNumber (v, 0, 1, mxCreateString ("that1"));
  mxSetFieldByNumber (v, 1, 0, mxCreateString ("this2"));
  mxSetFieldByNumber (v, 1, 1, mxCreateString ("that2"));
  mxSetFieldByNumber (v, 2, 0, mxCreateString ("this3"));
  mxSetFieldByNumber (v, 2, 1, mxCreateString ("that3"));
  mxSetFieldByNumber (v, 3, 0, mxCreateString ("this4"));
  mxSetFieldByNumber (v, 3, 1, mxCreateString ("that4"));

  if (nlhs)
    plhs[0] = v;
}
@end verbatim
@end smallexample

An example of the behavior of this function within Octave is then

@example
@group
a(1).f1 = "f11"; a(1).f2 = "f12";
a(2).f1 = "f21"; a(2).f2 = "f22";
b = mystruct (a);
@result{}  field f1(0) = f11
    field f1(1) = f21
    field f2(0) = f12
    field f2(1) = f22
b
@result{} 2x2 struct array containing the fields:

     this
     that

b(3)
@result{} scalar structure containing the fields:

     this = this3
     that = that3
@end group
@end example

@node Sparse Matrices with Mex-Files
@subsection Sparse Matrices with Mex-Files

The Octave format for sparse matrices is identical to the mex format in that it
is a compressed column sparse format.  Also, in both implementations sparse
matrices are required to be two-dimensional.  The only difference of importance
to the programmer is that the real and imaginary parts of the matrix are stored
separately.

The mex-file interface, in addition to using @code{mxGetM}, @code{mxGetN},
@code{mxSetM}, @code{mxSetN}, @code{mxGetPr}, @code{mxGetPi}, @code{mxSetPr},
and @code{mxSetPi}, also supplies the following functions.

@example
@group
mwIndex *mxGetIr (const mxArray *ptr);
mwIndex *mxGetJc (const mxArray *ptr);
mwSize mxGetNzmax (const mxArray *ptr);

void mxSetIr (mxArray *ptr, mwIndex *ir);
void mxSetJc (mxArray *ptr, mwIndex *jc);
void mxSetNzmax (mxArray *ptr, mwSize nzmax);
@end group
@end example

@noindent
@code{mxGetNzmax} gets the maximum number of elements that can be stored in the
sparse matrix.  This is not necessarily the number of nonzero elements in the
sparse matrix.  @code{mxGetJc} returns an array with one additional value than
the number of columns in the sparse matrix.  The difference between consecutive
values of the array returned by @code{mxGetJc} define the number of nonzero
elements in each column of the sparse matrix.  Therefore,

@example
@group
mwSize nz, n;
mwIndex *Jc;
mxArray *m;
@dots{}
n = mxGetN (m);
Jc = mxGetJc (m);
nz = Jc[n];
@end group
@end example

@noindent
returns the actual number of nonzero elements stored in the matrix in
@code{nz}.  As the arrays returned by @code{mxGetPr} and @code{mxGetPi} only
contain the nonzero values of the matrix, we also need a pointer to the rows of
the nonzero elements, and this is given by @code{mxGetIr}.  A complete example
of the use of sparse matrices in mex-files is given by the file
@file{mysparse.c} shown below.

@example
@verbatim
#include "mex.h"

void
mexFunction (int nlhs, mxArray *plhs[],
             int nrhs, const mxArray *prhs[])
{
  mwSize m, n, nz;
  mxArray *v;
  mwIndex i;
  double *pr, *pi;
  double *pr2, *pi2;
  mwIndex *ir, *jc;
  mwIndex *ir2, *jc2;

  if (nrhs != 1 || ! mxIsSparse (prhs[0]))
    mexErrMsgTxt ("ARG1 must be a sparse matrix");

  m = mxGetM (prhs[0]);
  n = mxGetN (prhs[0]);
  nz = mxGetNzmax (prhs[0]);

  if (mxIsComplex (prhs[0]))
    {
      mexPrintf ("Matrix is %d-by-%d complex sparse matrix", m, n);
      mexPrintf (" with %d elements\n", nz);

      pr = mxGetPr (prhs[0]);
      pi = mxGetPi (prhs[0]);
      ir = mxGetIr (prhs[0]);
      jc = mxGetJc (prhs[0]);

      i = n;
      while (jc[i] == jc[i-1] && i != 0) i--;

      mexPrintf ("last nonzero element (%d, %d) = (%g, %g)\n",
                 ir[nz-1]+ 1, i, pr[nz-1], pi[nz-1]);

      v = mxCreateSparse (m, n, nz, mxCOMPLEX);
      pr2 = mxGetPr (v);
      pi2 = mxGetPi (v);
      ir2 = mxGetIr (v);
      jc2 = mxGetJc (v);

      for (i = 0; i < nz; i++)
        {
          pr2[i] = 2 * pr[i];
          pi2[i] = 2 * pi[i];
          ir2[i] = ir[i];
        }
      for (i = 0; i < n + 1; i++)
        jc2[i] = jc[i];

      if (nlhs > 0)
        plhs[0] = v;
    }
  else if (mxIsLogical (prhs[0]))
    {
      mxLogical *pbr, *pbr2;
      mexPrintf ("Matrix is %d-by-%d logical sparse matrix", m, n);
      mexPrintf (" with %d elements\n", nz);

      pbr = mxGetLogicals (prhs[0]);
      ir = mxGetIr (prhs[0]);
      jc = mxGetJc (prhs[0]);

      i = n;
      while (jc[i] == jc[i-1] && i != 0) i--;
      mexPrintf ("last nonzero element (%d, %d) = %d\n",
                 ir[nz-1]+ 1, i, pbr[nz-1]);

      v = mxCreateSparseLogicalMatrix (m, n, nz);
      pbr2 = mxGetLogicals (v);
      ir2 = mxGetIr (v);
      jc2 = mxGetJc (v);

      for (i = 0; i < nz; i++)
        {
          pbr2[i] = pbr[i];
          ir2[i] = ir[i];
        }
      for (i = 0; i < n + 1; i++)
        jc2[i] = jc[i];

      if (nlhs > 0)
        plhs[0] = v;
    }
  else
    {
      mexPrintf ("Matrix is %d-by-%d real sparse matrix", m, n);
      mexPrintf (" with %d elements\n", nz);

      pr = mxGetPr (prhs[0]);
      ir = mxGetIr (prhs[0]);
      jc = mxGetJc (prhs[0]);

      i = n;
      while (jc[i] == jc[i-1] && i != 0) i--;
      mexPrintf ("last nonzero element (%d, %d) = %g\n",
                 ir[nz-1]+ 1, i, pr[nz-1]);

      v = mxCreateSparse (m, n, nz, mxREAL);
      pr2 = mxGetPr (v);
      ir2 = mxGetIr (v);
      jc2 = mxGetJc (v);

      for (i = 0; i < nz; i++)
        {
          pr2[i] = 2 * pr[i];
          ir2[i] = ir[i];
        }
      for (i = 0; i < n + 1; i++)
        jc2[i] = jc[i];

      if (nlhs > 0)
        plhs[0] = v;
    }
}
@end verbatim
@end example

A sample usage of @code{mysparse} is

@example
@group
sm = sparse ([1, 0; 0, pi]);
mysparse (sm)
@result{}
Matrix is 2-by-2 real sparse matrix with 2 elements
last nonzero element (2, 2) = 3.14159
@end group
@end example

@node Calling Other Functions in Mex-Files
@subsection Calling Other Functions in Mex-Files

It is possible to call other Octave functions from within a mex-file using
@code{mexCallMATLAB}.  An example of the use of @code{mexCallMATLAB} can be see
in the example below.

@smallexample
@verbatim
#include "mex.h"

void
mexFunction (int nlhs, mxArray *plhs[],
             int nrhs, const mxArray *prhs[])
{
  char *str;

  mexPrintf ("Starting file myfeval.mex\n");

  mexPrintf ("I have %d inputs and %d outputs\n", nrhs, nlhs);

  if (nrhs < 1 || ! mxIsChar (prhs[0]))
    mexErrMsgTxt ("ARG1 must be a function name");

  str = mxArrayToString (prhs[0]);

  mexPrintf ("I'm going to call the function %s\n", str);

  if (nlhs == 0)
    nlhs = 1;  // Octave's automatic 'ans' variable

  /* Cast prhs just to get rid of 'const' qualifier and stop compile warning */
  mexCallMATLAB (nlhs, plhs, nrhs-1, (mxArray**)prhs+1, str);

  mxFree (str);
}
@end verbatim
@end smallexample

If this code is in the file @file{myfeval.c}, and is compiled to
@file{myfeval.mex}, then an example of its use is

@example
@group
a = myfeval ("sin", 1)
@result{} Starting file myfeval.mex
   I have 2 inputs and 1 outputs
   I'm going to call the interpreter function sin
   a =  0.84147
@end group
@end example

Note that it is not possible to use function handles within a mex-file.

@c @node Application Programming Interface for Mex-Files
@c @subsection Application Programming Interface for Mex-Files
@c
@c WRITE ME, refer to mex.h and mexproto.h

@node Standalone Programs
@section Standalone Programs

The libraries Octave uses itself can be utilized in standalone applications.
These applications then have access, for example, to the array and matrix
classes, as well as to all of the Octave algorithms.  The following C++
program, uses class Matrix from @file{liboctave.a} or @file{liboctave.so}.

@example
@verbatim
#include <iostream>
#include <octave/oct.h>

int
main ()
{
  std::cout << "Hello Octave world!\n";

  int n = 2;
  Matrix a_matrix = Matrix (n, n);

  for (octave_idx_type i = 0; i < n; i++)
    for (octave_idx_type j = 0; j < n; j++)
      a_matrix(i,j) = (i + 1) * 10 + (j + 1);

  std::cout << a_matrix;

  return 0;
}
@end verbatim
@end example

@noindent
mkoctfile can be used to build a standalone application with a command like

@example
@group
$ mkoctfile --link-stand-alone standalone.cc -o standalone
$ ./standalone
Hello Octave world!
  11 12
  21 22
$
@end group
@end example

Note that the application @code{standalone} will be dynamically linked against
the Octave libraries and any Octave support libraries.  The above allows the
Octave math libraries to be used by an application.  It does not, however,
allow the script files, oct-files, or built-in functions of Octave to be used
by the application.  To do that, the Octave interpreter needs to be initialized
first.  An example of how to do this can then be seen in the code

@example
@verbatim
#include <iostream>
#include <octave/oct.h>
#include <octave/octave.h>
#include <octave/parse.h>
#include <octave/interpreter.h>

int
main ()
{
  // Create interpreter.

  octave::interpreter interpreter;

  try
    {
      // Inhibit reading history file by calling
      //
      //   interpreter.initialize_history (false);

      // Set custom load path here if you wish by calling
      //
      //   interpreter.initialize_load_path (false);

      // Perform final initialization of interpreter, including
      // executing commands from startup files by calling
      //
      //   interpreter.initialize ();
      //
      //   if (! interpreter.is_initialized ())
      //     {
      //       std::cerr << "Octave interpreter initialization failed!"
      //                 << std::endl;
      //       exit (1);
      //     }
      //
      // You may skip this step if you don't need to do anything
      // between reading the startup files and telling the interpreter
      // that you are ready to execute commands.

      // Tell the interpreter that we're ready to execute commands:

      int status = interpreter.execute ();

      if (status != 0)
        {
          std::cerr << "creating embedded Octave interpreter failed!"
                    << std::endl;
          return status;
        }

      octave_idx_type n = 2;
      octave_value_list in;

      for (octave_idx_type i = 0; i < n; i++)
        in(i) = octave_value (5 * (i + 2));

      octave_value_list out = octave::feval ("gcd", in, 1);

      if (out.length () > 0)
        std::cout << "GCD of ["
                  << in(0).int_value ()
                  << ", "
                  << in(1).int_value ()
                  << "] is " << out(0).int_value ()
                  << std::endl;
      else
        std::cout << "invalid\n";
    }
  catch (const octave::exit_exception& ex)
    {
      std::cerr << "Octave interpreter exited with status = "
                << ex.exit_status () << std::endl;
    }
  catch (const octave::execution_exception&)
    {
      std::cerr << "error encountered in Octave evaluator!" << std::endl;
    }

  return 0;
}
@end verbatim
@end example

@noindent
which, as before, is compiled and run as a standalone application with

@example
@group
$ mkoctfile --link-stand-alone embedded.cc -o embedded
$ ./embedded
GCD of [10, 15] is 5
$
@end group
@end example

It is worth re-iterating that, if only built-in functions are to be called from
a C++ standalone program then it does not need to initialize the interpreter.
The general rule is that for a built-in function named @code{function_name} in
the interpreter, there will be a C++ function named @code{Ffunction_name} (note
the prepended capital @code{F}) accessible in the C++ API@.  The declarations
for all built-in functions are collected in the header file
@code{builtin-defun-decls.h}.  This feature should be used with care as the
list of built-in functions can change.  No guarantees can be made that a
function that is currently a built-in won't be implemented as a @file{.m} file
or as a dynamically linked function in the future.  An example of how to call
built-in functions from C++ can be seen in the code

@example
@verbatim
#include <iostream>
#include <octave/oct.h>
#include <octave/builtin-defun-decls.h>

int
main ()
{
  int n = 2;
  Matrix a_matrix = Matrix (n, n);

  for (octave_idx_type i = 0; i < n; i++)
    for (octave_idx_type j = 0; j < n; j++)
      a_matrix(i,j) = (i + 1) * 10 + (j + 1);

  std::cout << "This is a matrix:" << std::endl
            << a_matrix            << std::endl;

  octave_value_list in;
  in(0) = a_matrix;

  octave_value_list out = octave::Fnorm (in, 1);
  double norm_of_the_matrix = out(0).double_value ();

  std::cout << "This is the norm of the matrix:" << std::endl
            << norm_of_the_matrix                << std::endl;

  return 0;
}
@end verbatim
@end example

@noindent
which is compiled and run as a standalone application with

@example
@group
$ mkoctfile --link-stand-alone standalonebuiltin.cc -o standalonebuiltin
$ ./standalonebuiltin
This is a matrix:
 11 12
 21 22

This is the norm of the matrix:
34.4952
$
@end group
@end example

@node Java Interface
@section Java Interface

@cindex using Octave with Java
@cindex Java, using with Octave
@cindex calling Java from Octave
@cindex Java, calling from Octave
@cindex calling Octave from Java
@cindex Octave, calling from Java

The Java Interface is designed for calling Java functions from within Octave.
If you want to do the reverse, and call Octave from within Java, try a library
like @code{joPas} (@url{http://jopas.sourceforge.net}).

@menu
* Making Java Classes Available::
* How to use Java from within Octave::
* Set up the JVM::
* Java Interface Functions::
@end menu


@node Making Java Classes Available
@subsection Making Java Classes Available

@c - index -
@cindex classpath, setting
@cindex classpath, difference between static and dynamic
@cindex static classpath
@cindex dynamic classpath
@cindex @file{javaclasspath.txt}
@cindex @file{classpath.txt}
@cindex classes, making available to Octave
@c - index -

Java finds classes by searching a @var{classpath} which is a list of Java
archive files and/or directories containing class files.  In Octave the
@var{classpath} is composed of two parts:

@itemize
@item the @var{static classpath} is initialized once at startup of the JVM, and

@item the @var{dynamic classpath} which can be modified at runtime.
@end itemize

Octave searches the @var{static classpath} first, and then the
@var{dynamic classpath}.  Classes appearing in the @var{static classpath}, as
well as in the @var{dynamic classpath}, will therefore be found in the
@var{static classpath} and loaded from this location.  Classes which will be
used frequently, or must be available to all users, should be added to the
@var{static classpath}.  The @var{static classpath} is populated once from the
contents of a plain text file named @file{javaclasspath.txt} (or
@file{classpath.txt} historically) when the Java Virtual Machine starts.  This
file contains one line for each individual classpath to be added to the
@var{static classpath}.  These lines can identify directories containing class
files, or Java archives with complete class file hierarchies.  Comment lines
starting with a @samp{#} or a @samp{%} character are ignored.

The search rules for the file @file{javaclasspath.txt} (or
@file{classpath.txt}) are:

@itemize
@item
First, Octave tries to locate it in the current directory (where Octave was
started from).  If such a file is found, it is read and defines the initial
@var{static classpath}.  Thus, it is possible to define a static classpath on a
'per Octave invocation' basis.

@item
Next, Octave searches in the user's home directory.  If a file
@file{javaclasspath.txt} exists here, its contents are appended to the static
classpath (if any).  Thus, it is possible to build an initial static classpath
on a @nospell{'per user'} basis.

@item
Finally, Octave looks for a @file{javaclasspath.txt} in the m-file directory
where Octave Java functions live.  This is where the function
@file{javaclasspath.m} resides, usually something like
@file{@w{@env{OCTAVE_HOME}}/share/octave/@w{@env{OCTAVE_VERSION}}/m/java/}.
You can find this directory by executing the command

@example
which javaclasspath
@end example

If this file exists here, its contents are also appended to the
@var{static classpath}.  Note that the archives and class directories defined
in this last step will affect all users.
@end itemize

Classes which are used only by a specific script should be placed in the
@var{dynamic classpath}.  This portion of the classpath can be modified at
runtime using the @code{javaaddpath} and @code{javarmpath} functions.

Example:

@example
octave> base_path = "C:/Octave/java_files";

octave> # add two JAR archives to the dynamic classpath
octave> javaaddpath ([base_path, "/someclasses.jar"]);
octave> javaaddpath ([base_path, "/moreclasses.jar"]);

octave> # check the dynamic classpath
octave> p = javaclasspath;
octave> disp (p@{1@});
C:/Octave/java_files/someclasses.jar
octave> disp (p@{2@});
C:/Octave/java_files/moreclasses.jar

octave> # remove the first element from the classpath
octave> javarmpath ([base_path, "/someclasses.jar"]);
octave> p = javaclasspath;
octave> disp (p@{1@});
C:/Octave/java_files/moreclasses.jar

octave> # provoke an error
octave> disp (p@{2@});
error: A(I): Index exceeds matrix dimension.
@end example

Another way to add files to the @var{dynamic classpath} exclusively for your
user account is to use the file @file{.octaverc} which is stored in your home
directory.  All Octave commands in this file are executed each time you start a
new instance of Octave.  The following example adds the directory @file{octave}
to Octave's search path and the archive @file{myclasses.jar} in this directory
to the Java search path.

@example
@group
# contents of .octaverc:
addpath ("~/octave");
javaaddpath ("~/octave/myclasses.jar");
@end group
@end example

@c ------------------------------------------------------------------------
@node How to use Java from within Octave
@subsection How to use Java from within Octave

The function @ref{XREFjavaObject,javaObject,javaObject} creates Java objects.
In fact it invokes the public constructor of the class with the given name
and with the given parameters.

The following example shows how to invoke the constructors
@code{BigDecimal(double)} and @code{BigDecimal(String)} of the builtin Java
class @code{java.math.BigDecimal}.

@example
@group
javaObject ("java.math.BigDecimal",  1.001 );
javaObject ("java.math.BigDecimal", "1.001");
@end group
@end example

Note that parameters of the Octave type @code{double} are implicitly converted
into the Java type @code{double} and the Octave type (array of) @code{char} is
converted into the java type @code{String}.  A Java object created by
@ref{XREFjavaObject,javaObject,javaObject} is never automatically converted
into an Octave type but remains a Java object.  It can be assigned to an
Octave variable.

@example
@group
a = 1.001;
b = javaObject ("java.math.BigDecimal", a);
@end group
@end example

Using @ref{XREFisjava,isjava,isjava}, it is possible to check whether a
variable is a Java object and its class can be determined as well.  In
addition to the previous example:

@example
@group
isjava (a)
@result{} ans = 0
class (a)
@result{} ans = double
isjava (b)
@result{} ans = 1
class (b)
@result{} ans = java.math.BigDecimal
@end group
@end example

The example above can be carried out using only Java objects:

@example
@group
a = javaObject ("java.lang.Double", 1.001);
b = javaObject ("java.math.BigDecimal", a);

isjava (a)
@result{} ans = 1
class (a)
@result{} ans = java.lang.Double
isjava (b)
@result{} ans = 1
class (b)
@result{} ans = java.math.BigDecimal
@end group
@end example

One can see, that even a @code{java.lang.Double} is not converted to an Octave
@code{double}, when created by @ref{XREFjavaObject,javaObject,javaObject}.
But ambiguities might arise, if the Java classes @code{java.lang.Double} or
@code{double} are parameters of a method (or a constructor).  In this case
they can be converted into one another, depending on the context.


Via @ref{XREFjavaObject,javaObject,javaObject} one may create all kinds of
Java objects but arrays.  The latter are created through
@ref{XREFjavaArray,javaArray,javaArray}.

It is possible to invoke public member methods on Java objects in Java syntax:

@example
@group
a.toString
@result{} ans = 1.001
b.toString
@result{} ans = 1.000999999999999889865...
@end group
@end example

The second result may be surprising, but simply comes from the fact, that
@code{1.001} cannot exactly be represented as @code{double}, due to rounding.
Note that unlike in Java, in Octave methods without arguments can be invoked
with and without parentheses @code{()}.

Currently it is not possible to invoke static methods with a Java like syntax
from within Octave.  Instead, one has to use the function
@ref{XREFjavaMethod,javaMethod,javaMethod} as in the following example:

@example
@group
java.math.BigDecimal.valueOf(1.001);                    # does not work
javaMethod ("valueOf", "java.math.BigDecimal", 1.001);  # workaround
@end group
@end example

As mentioned before, method and constructor parameters are converted
automatically between Octave and Java types, if appropriate.  For functions
this is also true with return values, whereas for constructors this is not.

It is also possible to access public fields of Java objects from within Octave
using Java syntax, with the limitation of static fields:

@example
@group
java.math.BigDecimal.ONE;                  # does not work
java_get ("java.math.BigDecimal", "ONE");  # workaround
@end group
@end example

Accordingly, with @ref{XREFjava_set,java_set,java_set} the value of a field
can be set.  Note that only public Java fields are accessible from within
Octave.

The following example indicates that in Octave empty brackets @code{[]}
represent Java's @code{null} value and how Java exceptions are represented.

@example
@group
javaObject ("java.math.BigDecimal", []);
@result{} error: [java] java.lang.NullPointerException
@end group
@end example

It is not recommended to represent Java's @code{null} value by empty brackets
@code{[]}, because @code{null} has no type whereas @code{[]} has type
@code{double}.

In Octave it is possible to provide limited Java reflection by listing the
public fields and methods of a Java object, both static or not.

@example
@group
fieldnames (<Java object>)
methods (<Java object>)
@end group
@end example

Finally, an examples is shown how to access the stack trace from within
Octave, where the function @ref{XREFdebug_java,debug_java,debug_java} is used
to set and to get the current debug state.  In debug mode, the Java error and
the stack trace are displayed.

@example
@group
debug_java (true)  # use "false" to omit display of stack trace
debug_java ()
@result{} ans = 1
javaObject ("java.math.BigDecimal", "1") ...
  .divide (javaObject ("java.math.BigDecimal", "0"))
@end group
@end example


@node Set up the JVM
@subsection Set up the JVM
@cindex memory, limitations on JVM
@cindex select JVM version

In order to execute Java code Octave creates a Java Virtual Machine (JVM).  By
default the version of the JVM is used that was detected during configuration
on Unix-like systems or that is pointed to from the registry keys at
@file{HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\JRE} or
@file{HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment} on
Windows.  The default path to the JVM can be overridden by setting the
environment variable @w{@env{JAVA_HOME}}@ to the path where the JVM is
installed.  On Windows that might be, for example,
@file{C:\Program Files\Java\jre-10.0.2}.  Make sure that you select a directory
that contains the JVM with a @nospell{bit-ness} that matches Octave's.

The JVM is only loaded once per Octave session.  Thus, to change the used
version of the JVM, you might have to re-start Octave.  To check which version
of the JVM is currently being used, run @code{version -java}.

The JVM allocates a fixed amount of initial memory and may expand this pool up
to a fixed maximum memory limit.  The default values depend on the Java version
(@pxref{XREFjavamem,,javamem}).  The memory pool is shared by all Java objects
running in the JVM@.  This strict memory limit is intended mainly to avoid
runaway applications inside web browsers or in enterprise servers which can
consume all memory and crash the system.  When the maximum memory limit is hit,
Java code will throw exceptions so that applications will fail or behave
unexpectedly.

You can specify options for the creation of the JVM inside a file named
@file{java.opts}.  This is a text file where enter you enter lines containing
@option{-X} and @option{-D} options that are then passed to the JVM during
initialization.

The directory where the Java options file is located is specified by the
environment variable @w{@env{OCTAVE_JAVA_DIR}}.  If unset the directory where
@file{javaclasspath.m} resides is used instead (typically
@file{@w{@env{OCTAVE_HOME}}/share/octave/@w{@env{OCTAVE_VERSION}}/m/java/}).
You can find this directory by executing

@example
which javaclasspath
@end example

The @option{-X} options allow you to increase the maximum amount of memory
available to the JVM@.  The following example allows up to 256 Megabytes to be
used by adding the following line to the @file{java.opts} file:

@example
-Xmx256m
@end example

The maximum possible amount of memory depends on your system.  On a Windows
system with 2 Gigabytes main memory you should be able to set this maximum to
about 1 Gigabyte.

If your application requires a large amount of memory from the beginning, you
can also specify the initial amount of memory allocated to the JVM@.  Adding
the following line to the @file{java.opts} file starts the JVM with 64
Megabytes of initial memory:

@example
-Xms64m
@end example

For more details on the available @option{-X} options of your Java Virtual
Machine issue the command @samp{java -X} at the operating system command prompt
and consult the Java documentation.

The @option{-D} options can be used to define system properties which can then
be used by Java classes inside Octave.  System properties can be retrieved by
using the @code{getProperty()} methods of the @code{java.lang.System} class.
The following example line defines the property @var{MyProperty} and assigns it
the string @code{12.34}.

@example
-DMyProperty=12.34
@end example

The value of this property can then be retrieved as a string by a Java object
or in Octave:

@example
@group
octave> javaMethod ("getProperty", "java.lang.System", "MyProperty");
ans = 12.34
@end group
@end example


@node Java Interface Functions
@subsection Java Interface Functions

The following functions are the core of the Java Interface.  They provide a way
to create a Java object, get and set its data fields, and call Java methods
which return results to Octave.

@cindex object, creating a Java object
@cindex instance, creating a Java instance
@c javaObject libinterp/octave-value/ov-java.cc
@anchor{XREFjavaObject}
@html
<span style="display:block; margin-top:-4.5ex;">&nbsp;</span>
@end html


@deftypefn  {} {@var{jobj} =} javaObject (@var{classname})
@deftypefnx {} {@var{jobj} =} javaObject (@var{classname}, @var{arg1}, @dots{})
Create a Java object of class @var{classsname}, by calling the class
constructor with the arguments @var{arg1}, @enddots{}

The first example below creates an uninitialized object, while the second
example supplies an initial argument to the constructor.

@example
@group
x = javaObject ("java.lang.StringBuffer")
x = javaObject ("java.lang.StringBuffer", "Initial string")
@end group
@end example

@xseealso{@ref{XREFjavaMethod,,javaMethod}, @ref{XREFjavaArray,,javaArray}}
@end deftypefn


@cindex array, creating a Java array
@c javaArray scripts/java/javaArray.m
@anchor{XREFjavaArray}
@html
<span style="display:block; margin-top:-4.5ex;">&nbsp;</span>
@end html


@deftypefn  {} {@var{jary} =} javaArray (@var{classname}, @var{sz})
@deftypefnx {} {@var{jary} =} javaArray (@var{classname}, @var{m}, @var{n}, @dots{})

Create a Java array of size @var{sz} with elements of class @var{classname}.

@var{classname} may be a Java object representing a class or a string
containing the fully qualified class name.  The size of the object may
also be specified with individual integer arguments @var{m}, @var{n}, etc.

The generated array is uninitialized.  All elements are set to null if
@var{classname} is a reference type, or to a default value (usually 0) if
@var{classname} is a primitive type.

Sample code:

@example
@group
jary = javaArray ("java.lang.String", 2, 2);
jary(1,1) = "Hello";
@end group
@end example
@xseealso{@ref{XREFjavaObject,,javaObject}}
@end deftypefn


There are many different variable types in Octave, but only ones created
through @code{javaObject} can use Java functions.  Before using Java with an
unknown object the type can be checked with @code{isjava}.

@c isjava libinterp/octave-value/ov-java.cc
@anchor{XREFisjava}
@html
<span style="display:block; margin-top:-4.5ex;">&nbsp;</span>
@end html


@deftypefn {} {@var{tf} =} isjava (@var{x})
Return true if @var{x} is a Java object.
@xseealso{@ref{XREFclass,,class}, @ref{XREFtypeinfo,,typeinfo}, @ref{XREFisa,,isa}, @ref{XREFjavaObject,,javaObject}}
@end deftypefn


Once an object has been created it is natural to find out what fields the
object has, and to read (get) and write (set) them.

@cindex fields, displaying available fields of a Java object
In Octave the @code{fieldnames} function for structures has been overloaded
to return the fields of a Java object.  For example:

@example
@group
dobj = javaObject ("java.lang.Double", pi);
fieldnames (dobj)
@result{}
@{
  [1,1] = public static final double java.lang.Double.POSITIVE_INFINITY
  [1,2] = public static final double java.lang.Double.NEGATIVE_INFINITY
  [1,3] = public static final double java.lang.Double.NaN
  [1,4] = public static final double java.lang.Double.MAX_VALUE
  [1,5] = public static final double java.lang.Double.MIN_NORMAL
  [1,6] = public static final double java.lang.Double.MIN_VALUE
  [1,7] = public static final int java.lang.Double.MAX_EXPONENT
  [1,8] = public static final int java.lang.Double.MIN_EXPONENT
  [1,9] = public static final int java.lang.Double.SIZE
  [1,10] = public static final java.lang.Class java.lang.Double.TYPE
@}
@end group
@end example

@cindex field, returning value of Java object field
The analogy of objects with structures is carried over into reading and writing
object fields.  To read a field the object is indexed with the @samp{.}
operator from structures.  This is the preferred method for reading fields, but
Octave also provides a function interface to read fields with @code{java_get}.
An example of both styles is shown below.

@example
@group
dobj = javaObject ("java.lang.Double", pi);
dobj.MAX_VALUE
@result{}  1.7977e+308
java_get ("java.lang.Float", "MAX_VALUE")
@result{}  3.4028e+38
@end group
@end example

@c java_get scripts/java/java_get.m
@anchor{XREFjava_get}
@html
<span style="display:block; margin-top:-4.5ex;">&nbsp;</span>
@end html


@deftypefn {} {@var{val} =} java_get (@var{obj}, @var{name})
Get the value of the field @var{name} of the Java object @var{obj}.

For static fields, @var{obj} can be a string representing the fully
qualified name of the corresponding class.

When @var{obj} is a regular Java object, structure-like indexing can be
used as a shortcut syntax.  For instance, the following two statements are
equivalent

@example
@group
  java_get (x, "field1")
  x.field1
@end group
@end example

@xseealso{@ref{XREFjava_set,,java_set}, @ref{XREFjavaMethod,,javaMethod}, @ref{XREFjavaObject,,javaObject}}
@end deftypefn


@cindex field, setting value of Java object field
@c java_set scripts/java/java_set.m
@anchor{XREFjava_set}
@html
<span style="display:block; margin-top:-4.5ex;">&nbsp;</span>
@end html


@deftypefn {} {@var{obj} =} java_set (@var{obj}, @var{name}, @var{val})
Set the value of the field @var{name} of the Java object @var{obj} to
@var{val}.

For static fields, @var{obj} can be a string representing the fully
qualified named of the corresponding Java class.

When @var{obj} is a regular Java object, structure-like indexing can be
used as a shortcut syntax.  For instance, the following two statements are
equivalent

@example
@group
  java_set (x, "field1", val)
  x.field1 = val
@end group
@end example

@xseealso{@ref{XREFjava_get,,java_get}, @ref{XREFjavaMethod,,javaMethod}, @ref{XREFjavaObject,,javaObject}}
@end deftypefn


@cindex methods, displaying available methods of a Java object
To see what functions can be called with an object use @code{methods}.  For
example, using the previously created @var{dobj}:

@example
@group
methods (dobj)
@result{}
Methods for class java.lang.Double:
boolean equals(java.lang.Object)
java.lang.String toString(double)
java.lang.String toString()
@dots{}
@end group
@end example

To call a method of an object the same structure indexing operator @samp{.} is
used.  Octave also provides a functional interface to calling the methods of an
object through @code{javaMethod}.  An example showing both styles is shown
below.

@example
@group
dobj = javaObject ("java.lang.Double", pi);
dobj.equals (3)
@result{}  0
javaMethod ("equals", dobj, pi)
@result{}  1
@end group
@end example

@cindex method, invoking a method of a Java object
@c javaMethod libinterp/octave-value/ov-java.cc
@anchor{XREFjavaMethod}
@html
<span style="display:block; margin-top:-4.5ex;">&nbsp;</span>
@end html


@deftypefn  {} {@var{ret} =} javaMethod (@var{methodname}, @var{obj})
@deftypefnx {} {@var{ret} =} javaMethod (@var{methodname}, @var{obj}, @var{arg1}, @dots{})
Invoke the method @var{methodname} on the Java object @var{obj} with the
arguments @var{arg1}, @enddots{}

For static methods, @var{obj} can be a string representing the fully
qualified name of the corresponding class.

When @var{obj} is a regular Java object, structure-like indexing can be
used as a shortcut syntax.  For instance, the two following statements are
equivalent

@example
@group
  ret = javaMethod ("method1", x, 1.0, "a string")
  ret = x.method1 (1.0, "a string")
@end group
@end example

@code{javaMethod} returns the result of the method invocation.

@xseealso{@ref{XREFmethods,,methods}, @ref{XREFjavaObject,,javaObject}}
@end deftypefn


The following three functions are used to display and modify the class path
used by the Java Virtual Machine.  This is entirely separate from Octave's
@env{PATH} variable and is used by the JVM to find the correct code to execute.

@cindex classpath, displaying
@cindex classpath, dynamic
@cindex dynamic classpath
@cindex classpath, static
@cindex static classpath
@c javaclasspath scripts/java/javaclasspath.m
@anchor{XREFjavaclasspath}
@html
<span style="display:block; margin-top:-4.5ex;">&nbsp;</span>
@end html


@deftypefn  {} {} javaclasspath ()
@deftypefnx {} {@var{dpath} =} javaclasspath ()
@deftypefnx {} {[@var{dpath}, @var{spath}] =} javaclasspath ()
@deftypefnx {} {@var{clspath} =} javaclasspath (@var{what})
Return the class path of the Java virtual machine in the form of a cell
array of strings.

If called with no inputs:

@itemize
@item If no output is requested, the dynamic and static classpaths are
printed to the standard output.

@item If one output value @var{dpath} is requested, the result is the
dynamic classpath.

@item If two output values@var{dpath} and @var{spath} are requested, the
first variable will contain the dynamic classpath and the second will
contain the static classpath.
@end itemize

If called with a single input parameter @var{what}:

@table @asis
@item @qcode{"-dynamic"}
Return the dynamic classpath.

@item @qcode{"-static"}
Return the static classpath.

@item @qcode{"-all"}
Return both the static and dynamic classpath in a single cellstr.
@end table
@xseealso{@ref{XREFjavaaddpath,,javaaddpath}, @ref{XREFjavarmpath,,javarmpath}}
@end deftypefn


@findex javaaddpath
@cindex classpath, adding new path
@cindex path, adding to classpath
@cindex classpath, dynamic
@cindex dynamic classpath, adding new path
@c javaaddpath scripts/java/javaaddpath.m
@anchor{XREFjavaaddpath}
@html
<span style="display:block; margin-top:-4.5ex;">&nbsp;</span>
@end html


@deftypefn  {} {} javaaddpath (@var{clspath})
@deftypefnx {} {} javaaddpath (@var{clspath1}, @dots{})
@deftypefnx {} {} javaaddpath (@{@var{clspath1}, @dots{}@})
@deftypefnx {} {} javaaddpath (@dots{}, "-end")
Add @var{clspath} to the beginning of the dynamic class path of the
Java virtual machine.

@var{clspath} may either be a directory where @file{.class} files are
found, or a @file{.jar} file containing Java classes.  Multiple paths may
be added at once by specifying additional arguments, or by using a cell
array of strings.

If the final argument is @qcode{"-end"}, append the new element to the
end of the current classpath.

@xseealso{@ref{XREFjavarmpath,,javarmpath}, @ref{XREFjavaclasspath,,javaclasspath}}
@end deftypefn


@cindex classpath, removing path
@cindex path, removing from classpath
@c javarmpath scripts/java/javarmpath.m
@anchor{XREFjavarmpath}
@html
<span style="display:block; margin-top:-4.5ex;">&nbsp;</span>
@end html


@deftypefn  {} {} javarmpath (@var{clspath})
@deftypefnx {} {} javarmpath (@var{clspath1}, @dots{})
@deftypefnx {} {} javarmpath (@{@var{clspath1}, @dots{}@})
Remove @var{clspath} from the dynamic class path of the Java virtual
machine.

@var{clspath} may either be a directory where @file{.class} files are found,
or a @file{.jar} file containing Java classes.  Multiple paths may be
removed at once by specifying additional arguments, or by using a cell array
of strings.
@xseealso{@ref{XREFjavaaddpath,,javaaddpath}, @ref{XREFjavaclasspath,,javaclasspath}}
@end deftypefn


The following functions provide information and control over the interface
between Octave and the Java Virtual Machine.

@c javachk scripts/java/javachk.m
@anchor{XREFjavachk}
@html
<span style="display:block; margin-top:-4.5ex;">&nbsp;</span>
@end html


@deftypefn  {} {@var{msg} =} javachk (@var{feature})
@deftypefnx {} {@var{msg} =} javachk (@var{feature}, @var{caller})
Check for the presence of the Java @var{feature} in the current session.
Return an error structure if @var{feature} is not available, not enabled,
or not recognized.

Possible recognized features are:

@table @asis
@item @nospell{@qcode{"awt"}}
Abstract Window Toolkit for GUIs.

@item @qcode{"desktop"}
Interactive desktop is running.

@item @qcode{"jvm"}
Java Virtual Machine.

@item @qcode{"swing"}
Swing components for lightweight GUIs.
@end table

If @var{feature} is not supported, a scalar struct with field
@qcode{"message"} and @qcode{"identifier"} is returned.  The field
@qcode{"message"} contains an error message mentioning @var{feature} as
well as the optional user-specified @var{caller}.  This structure is
suitable for passing in to the @code{error} function.

If @var{feature} is supported and available, an empty struct array is
returned with fields @qcode{"message"} and @qcode{"identifier"}.

@code{javachk} determines if specific Java features are available in an
Octave session.  This function is provided for scripts which may alter
their behavior based on the availability of Java or specific Java runtime
features.

Compatibility Note: The feature @qcode{"desktop"} is never available since
Octave has no Java-based desktop.

@xseealso{@ref{XREFusejava,,usejava}, @ref{XREFerror,,error}}
@end deftypefn


@c usejava scripts/java/usejava.m
@anchor{XREFusejava}
@html
<span style="display:block; margin-top:-4.5ex;">&nbsp;</span>
@end html


@deftypefn {} {@var{tf} =} usejava (@var{feature})
Return true if the Java element @var{feature} is available.

Possible features are:

@table @asis
@item @nospell{@qcode{"awt"}}
Abstract Window Toolkit for GUIs.

@item @qcode{"desktop"}
Interactive desktop is running.

@item @qcode{"jvm"}
Java Virtual Machine.

@item @qcode{"swing"}
Swing components for lightweight GUIs.
@end table

@code{usejava} determines if specific Java features are available in an
Octave session.  This function is provided for scripts which may alter
their behavior based on the availability of Java.  The feature
@qcode{"desktop"} always returns @code{false} as Octave has no Java-based
desktop.  Other features may be available if Octave was compiled with the
Java Interface and Java is installed.
@xseealso{@ref{XREFjavachk,,javachk}}
@end deftypefn


@cindex memory, displaying Java memory status
@c javamem scripts/java/javamem.m
@anchor{XREFjavamem}
@html
<span style="display:block; margin-top:-4.5ex;">&nbsp;</span>
@end html


@deftypefn  {} {} javamem ()
@deftypefnx {} {@var{jmem} =} javamem ()
Show the current memory usage of the Java virtual machine (JVM) and run the
garbage collector.

When no return argument is given the info is printed to the screen.
Otherwise, the output cell array @var{jmem} contains Maximum, Total, and
Free memory (in bytes).

All Java-based routines are run in the JVM's shared memory pool, a
dedicated and separate part of memory claimed by the JVM from your
computer's total memory (which comprises physical RAM and virtual memory /
swap space on hard disk).

The maximum allowable memory usage can be configured using the file
@file{java.opts}.  The directory where this file resides is determined by
the environment variable @w{@env{OCTAVE_JAVA_DIR}}.  If unset, the directory
where @file{javaaddpath.m} resides is used instead (typically
@file{@w{@env{OCTAVE_HOME}}/share/octave/@w{@env{OCTAVE_VERSION}}/m/java/}).

@file{java.opts} is a plain text file with one option per line.  The default
initial memory size and default maximum memory size (which are both system
dependent) can be overridden like so:

@nospell{-Xms64m}

@nospell{-Xmx512m}

(in megabytes in this example).
You can adapt these values to your own requirements if your system has
limited available physical memory or if you get Java memory errors.

@qcode{"Total memory"} is what the operating system has currently assigned
to the JVM and depends on actual and active memory usage.
@qcode{"Free memory"} is self-explanatory.  During operation of Java-based
Octave functions the amount of Total and Free memory will vary, due to
Java's own cleaning up and your operating system's memory management.
@end deftypefn


@c java_matrix_autoconversion libinterp/octave-value/ov-java.cc
@anchor{XREFjava_matrix_autoconversion}
@html
<span style="display:block; margin-top:-4.5ex;">&nbsp;</span>
@end html


@deftypefn  {} {@var{val} =} java_matrix_autoconversion ()
@deftypefnx {} {@var{old_val} =} java_matrix_autoconversion (@var{new_val})
@deftypefnx {} {@var{old_val} =} java_matrix_autoconversion (@var{new_val}, "local")
Query or set the internal variable that controls whether Java arrays are
automatically converted to Octave matrices.

The default value is false.

When called from inside a function with the @qcode{"local"} option, the
variable is changed locally for the function and any subroutines it calls.
The original variable value is restored when exiting the function.
@xseealso{@ref{XREFjava_unsigned_autoconversion,,java_unsigned_autoconversion}, @ref{XREFdebug_java,,debug_java}}
@end deftypefn


@c java_unsigned_autoconversion libinterp/octave-value/ov-java.cc
@anchor{XREFjava_unsigned_autoconversion}
@html
<span style="display:block; margin-top:-4.5ex;">&nbsp;</span>
@end html


@deftypefn  {} {@var{val} =} java_unsigned_autoconversion ()
@deftypefnx {} {@var{old_val} =} java_unsigned_autoconversion (@var{new_val})
@deftypefnx {} {@var{old_val} =} java_unsigned_autoconversion (@var{new_val}, "local")
Query or set the internal variable that controls how integer classes are
converted when @code{java_matrix_autoconversion} is enabled.

When enabled, Java arrays of class Byte or Integer are converted to matrices
of class uint8 or uint32 respectively.  The default value is true.

When called from inside a function with the @qcode{"local"} option, the
variable is changed locally for the function and any subroutines it calls.
The original variable value is restored when exiting the function.
@xseealso{@ref{XREFjava_matrix_autoconversion,,java_matrix_autoconversion}, @ref{XREFdebug_java,,debug_java}}
@end deftypefn


@c debug_java libinterp/octave-value/ov-java.cc
@anchor{XREFdebug_java}
@html
<span style="display:block; margin-top:-4.5ex;">&nbsp;</span>
@end html


@deftypefn  {} {@var{val} =} debug_java ()
@deftypefnx {} {@var{old_val} =} debug_java (@var{new_val})
@deftypefnx {} {@var{old_val} =} debug_java (@var{new_val}, "local")
Query or set the internal variable that determines whether extra debugging
information regarding the initialization of the JVM and any Java exceptions
is printed.

When called from inside a function with the @qcode{"local"} option, the
variable is changed locally for the function and any subroutines it calls.
The original variable value is restored when exiting the function.
@xseealso{@ref{XREFjava_matrix_autoconversion,,java_matrix_autoconversion}, @ref{XREFjava_unsigned_autoconversion,,java_unsigned_autoconversion}}
@end deftypefn