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 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315
|
@c DO NOT EDIT! Generated automatically by munge-texi.pl.
@c Copyright (C) 1996-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 Functions and Scripts
@chapter Functions and Scripts
@cindex defining functions
@cindex user-defined functions
@cindex functions, user-defined
@cindex script files
Complicated Octave programs can often be simplified by defining functions.
Functions can be defined directly on the command line during interactive
Octave sessions, or in external files, and can be called just like built-in
functions.
@menu
* Introduction to Function and Script Files::
* Defining Functions::
* Returning from a Function::
* Multiple Return Values::
* Variable-length Return Lists::
* Variable-length Argument Lists::
* Ignoring Arguments::
* Default Arguments::
* Validating Arguments::
* Function Files::
* Script Files::
* Function Handles and Anonymous Functions::
* Command Syntax and Function Syntax::
* Organization of Functions::
@end menu
@node Introduction to Function and Script Files
@section Introduction to Function and Script Files
There are seven different things covered in this section.
@enumerate
@item
Typing in a function at the command prompt.
@item
Storing a group of commands in a file --- called a script file.
@item
Storing a function in a file---called a function file.
@item
Subfunctions in function files.
@item
Multiple functions in one script file.
@item
Private functions.
@item
Nested functions.
@end enumerate
Both function files and script files end with an extension of .m, for
@sc{matlab} compatibility. If you want more than one independent
functions in a file, it must be a script file (@pxref{Script Files}),
and to use these functions you must execute the script file before you
can use the functions that are in the script file.
@node Defining Functions
@section Defining Functions
@cindex @code{function} statement
@cindex @code{endfunction} statement
In its simplest form, the definition of a function named @var{name}
looks like this:
@example
@group
function @var{name}
@var{body}
endfunction
@end group
@end example
@noindent
A valid function name is like a valid variable name: a sequence of
letters, digits and underscores, not starting with a digit. Functions
share the same pool of names as variables.
The function @var{body} consists of Octave statements. It is the
most important part of the definition, because it says what the function
should actually @emph{do}.
For example, here is a function that, when executed, will ring the bell
on your terminal (assuming that it is possible to do so):
@example
@group
function wakeup
printf ("\a");
endfunction
@end group
@end example
The @code{printf} statement (@pxref{Input and Output}) simply tells
Octave to print the string @qcode{"@backslashchar{}a"}. The special character
@samp{\a} stands for the alert character (ASCII 7). @xref{Strings}.
Once this function is defined, you can ask Octave to evaluate it by
typing the name of the function.
Normally, you will want to pass some information to the functions you
define. The syntax for passing parameters to a function in Octave is
@example
@group
function @var{name} (@var{arg-list})
@var{body}
endfunction
@end group
@end example
@noindent
where @var{arg-list} is a comma-separated list of the function's
arguments. When the function is called, the argument names are used to
hold the argument values given in the call. The list of arguments may
be empty, in which case this form is equivalent to the one shown above.
To print a message along with ringing the bell, you might modify the
@code{wakeup} to look like this:
@example
@group
function wakeup (message)
printf ("\a%s\n", message);
endfunction
@end group
@end example
Calling this function using a statement like this
@example
wakeup ("Rise and shine!");
@end example
@noindent
will cause Octave to ring your terminal's bell and print the message
@samp{Rise and shine!}, followed by a newline character (the @samp{\n}
in the first argument to the @code{printf} statement).
In most cases, you will also want to get some information back from the
functions you define. Here is the syntax for writing a function that
returns a single value:
@example
@group
function @var{ret-var} = @var{name} (@var{arg-list})
@var{body}
endfunction
@end group
@end example
@noindent
The symbol @var{ret-var} is the name of the variable that will hold the
value to be returned by the function. This variable must be defined
before the end of the function body in order for the function to return
a value.
Variables used in the body of a function are local to the
function. Variables named in @var{arg-list} and @var{ret-var} are also
local to the function. @xref{Global Variables}, for information about
how to access global variables inside a function.
For example, here is a function that computes the average of the
elements of a vector:
@example
@group
function retval = avg (v)
retval = sum (v) / length (v);
endfunction
@end group
@end example
If we had written @code{avg} like this instead,
@example
@group
function retval = avg (v)
if (isvector (v))
retval = sum (v) / length (v);
endif
endfunction
@end group
@end example
@noindent
and then called the function with a matrix instead of a vector as the
argument, Octave would have printed an error message like this:
@example
@group
error: value on right hand side of assignment is undefined
@end group
@end example
@noindent
because the body of the @code{if} statement was never executed, and
@code{retval} was never defined. To prevent obscure errors like this,
it is a good idea to always make sure that the return variables will
always have values, and to produce meaningful error messages when
problems are encountered. For example, @code{avg} could have been
written like this:
@example
@group
function retval = avg (v)
retval = 0;
if (isvector (v))
retval = sum (v) / length (v);
else
error ("avg: expecting vector argument");
endif
endfunction
@end group
@end example
There is still one remaining problem with this function. What if it is
called without an argument? Without additional error checking, Octave
will probably print an error message that won't really help you track
down the source of the error. To allow you to catch errors like this,
Octave provides each function with an automatic variable called
@code{nargin}. Each time a function is called, @code{nargin} is
automatically initialized to the number of arguments that have actually
been passed to the function. For example, we might rewrite the
@code{avg} function like this:
@example
@group
function retval = avg (v)
retval = 0;
if (nargin != 1)
usage ("avg (vector)");
endif
if (isvector (v))
retval = sum (v) / length (v);
else
error ("avg: expecting vector argument");
endif
endfunction
@end group
@end example
Octave automatically reports an error for functions written in .m file code
if they are called with more arguments than expected. Octave does not
automatically report an error if a function is called with too few arguments,
since functions in general may have default arguments, but any attempt to use
a variable that has not been given a value will result in an error.
Functions can check the arguments they are called with to avoid such problems
and to provide more context-specific error messages.
@c nargin libinterp/octave-value/ov-usr-fcn.cc
@anchor{XREFnargin}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {@var{n} =} nargin ()
@deftypefnx {} {@var{n} =} nargin (@var{fcn})
Report the number of input arguments to a function.
Called from within a function, return the number of arguments passed to the
function. At the top level, return the number of command line arguments
passed to Octave.
If called with the optional argument @var{fcn}---a function name or
handle---return the declared number of arguments that the function can
accept.
If the last argument to @var{fcn} is @var{varargin} the returned value is
negative. For example, the function @code{union} for sets is declared as
@example
@group
function [y, ia, ib] = union (a, b, varargin)
and
nargin ("union")
@result{} -3
@end group
@end example
Programming Note: @code{nargin} does not work on compiled functions
(@file{.oct} files) such as built-in or dynamically loaded functions.
@xseealso{@ref{XREFnargout,,nargout}, @ref{XREFnarginchk,,narginchk}, @ref{XREFvarargin,,varargin}, @ref{XREFinputname,,inputname}}
@end deftypefn
@c inputname libinterp/parse-tree/pt-eval.cc
@anchor{XREFinputname}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {@var{namestr} =} inputname (@var{n})
@deftypefnx {} {@var{namestr} =} inputname (@var{n}, @var{ids_only})
Return the name of the @var{n}-th argument to the calling function.
If the argument is not a simple variable name, return an empty string.
Examples which will return @qcode{""} are numbers (@code{5.1}), expressions
(@code{@var{y}/2}), and cell or structure indexing (@code{@var{c}@{1@}} or
@code{@var{s}.@var{field}}).
@code{inputname} is only useful within a function. When used at the command
line or within a script it always returns an empty string.
By default, return an empty string if the @var{n}-th argument is not a valid
variable name. If the optional argument @var{ids_only} is false, return the
text of the argument even if it is not a valid variable name. This is an
Octave extension that allows the programmer to view exactly how the function
was invoked even when the inputs are complex expressions.
@xseealso{@ref{XREFnargin,,nargin}, @ref{XREFnarginchk,,narginchk}}
@end deftypefn
@c silent_functions libinterp/parse-tree/pt-eval.cc
@anchor{XREFsilent_functions}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {@var{val} =} silent_functions ()
@deftypefnx {} {@var{old_val} =} silent_functions (@var{new_val})
@deftypefnx {} {@var{old_val} =} silent_functions (@var{new_val}, "local")
Query or set the internal variable that controls whether internal
output from a function is suppressed.
If this option is disabled, Octave will display the results produced by
evaluating expressions within a function body that are not terminated with
a semicolon.
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.
@end deftypefn
@node Returning from a Function
@section Returning from a Function
The body of a user-defined function can contain a @code{return} statement.
This statement returns control to the rest of the Octave program. It
looks like this:
@example
return
@end example
Unlike the @code{return} statement in C, Octave's @code{return}
statement cannot be used to return a value from a function. Instead,
you must assign values to the list of return variables that are part of
the @code{function} statement. The @code{return} statement simply makes
it easier to exit a function from a deeply nested loop or conditional
statement.
Here is an example of a function that checks to see if any elements of a
vector are nonzero.
@example
@group
function retval = any_nonzero (v)
retval = 0;
for i = 1:length (v)
if (v (i) != 0)
retval = 1;
return;
endif
endfor
printf ("no nonzero elements found\n");
endfunction
@end group
@end example
Note that this function could not have been written using the
@code{break} statement to exit the loop once a nonzero value is found
without adding extra logic to avoid printing the message if the vector
does contain a nonzero element.
@deftypefn {} {} return
When Octave encounters the keyword @code{return} inside a function or
script, it returns control to the caller immediately. At the top level,
the return statement is ignored. A @code{return} statement is assumed
at the end of every function definition.
@end deftypefn
@node Multiple Return Values
@section Multiple Return Values
Unlike many other computer languages, Octave allows you to define
functions that return more than one value. The syntax for defining
functions that return multiple values is
@example
@group
function [@var{ret-list}] = @var{name} (@var{arg-list})
@var{body}
endfunction
@end group
@end example
@noindent
where @var{name}, @var{arg-list}, and @var{body} have the same meaning
as before, and @var{ret-list} is a comma-separated list of variable
names that will hold the values returned from the function. The list of
return values must have at least one element. If @var{ret-list} has
only one element, this form of the @code{function} statement is
equivalent to the form described in the previous section.
Here is an example of a function that returns two values, the maximum
element of a vector and the index of its first occurrence in the vector.
@example
@group
function [max, idx] = vmax (v)
idx = 1;
max = v (idx);
for i = 2:length (v)
if (v (i) > max)
max = v (i);
idx = i;
endif
endfor
endfunction
@end group
@end example
In this particular case, the two values could have been returned as
elements of a single array, but that is not always possible or
convenient. The values to be returned may not have compatible
dimensions, and it is often desirable to give the individual return
values distinct names.
It is possible to use the @code{nthargout} function to obtain only some
of the return values or several at once in a cell array.
@xref{Cell Array Objects}.
@c nthargout scripts/miscellaneous/nthargout.m
@anchor{XREFnthargout}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {@var{arg} =} nthargout (@var{n}, @var{fcn}, @dots{})
@deftypefnx {} {@var{arg} =} nthargout (@var{n}, @var{ntot}, @var{fcn}, @dots{})
Return the @var{n}th output argument of the function specified by the
function handle or string @var{fcn}.
Any additional arguments are passed directly to @var{fcn}. The total
number of arguments to call @var{fcn} with can be passed in @var{ntot}; by
default @var{ntot} is @var{n}. The input @var{n} can also be a vector of
indices of the output, in which case the output will be a cell array of the
requested output arguments.
The intended use of @code{nthargout} is to avoid intermediate variables.
For example, when finding the indices of the maximum entry of a matrix, the
following two compositions of @code{nthargout}
@example
@group
@var{m} = magic (5);
cell2mat (nthargout ([1, 2], @@ind2sub, size (@var{m}),
nthargout (2, @@max, @var{m}(:))))
@result{} 5 3
@end group
@end example
@noindent
are completely equivalent to the following lines:
@example
@group
@var{m} = magic (5);
[~, idx] = max (@var{M}(:));
[i, j] = ind2sub (size (@var{m}), idx);
[i, j]
@result{} 5 3
@end group
@end example
It can also be helpful to have all output arguments collected in a single
cell array as the following code demonstrates:
@example
@var{USV} = nthargout ([1:3], @@svd, hilb (5));
@end example
Programming Note: Equivalent functionality to the @code{nthargout} function
is frequently possible by using the character @samp{~} in code to ignore
outputs. This functionality is implemented by the Octave interpreter and
is even more efficient than using this function.
Equivalent Code:
@example
@group
idx = nthargout (2, @@max, rand (100, 1));
@equiv{}
[~, idx] = max (rand (100, 1));
@end group
@end example
@xseealso{@ref{XREFnargin,,nargin}, @ref{XREFnargout,,nargout}, @ref{XREFvarargin,,varargin}, @ref{XREFvarargout,,varargout}, @ref{XREFisargout,,isargout}}
@end deftypefn
In addition to setting @code{nargin} each time a function is called,
Octave also automatically initializes @code{nargout} to the number of
values that are expected to be returned. This allows you to write
functions that behave differently depending on the number of values that
the user of the function has requested. The implicit assignment to the
built-in variable @code{ans} does not figure in the count of output
arguments, so the value of @code{nargout} may be zero.
The @code{svd} and @code{hist} functions are examples of built-in
functions that behave differently depending on the value of
@code{nargout}. For example, @code{hist} will draw a histogram when called
with no output variables, but if called with outputs it will return the
frequency counts and/or bin centers without creating a plot.
It is possible to write functions that only set some return values. For
example, calling the function
@example
@group
function [x, y, z] = f ()
x = 1;
z = 2;
endfunction
@end group
@end example
@noindent
as
@example
[a, b, c] = f ()
@end example
@noindent
produces:
@example
@group
a = 1
b = [](0x0)
c = 2
@end group
@end example
@noindent
along with a warning.
@c nargout libinterp/octave-value/ov-usr-fcn.cc
@anchor{XREFnargout}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {@var{n} =} nargout ()
@deftypefnx {} {@var{n} =} nargout (@var{fcn})
Report the number of output arguments from a function.
Called from within a function, return the number of values the caller
expects to receive. At the top level, @code{nargout} with no argument is
undefined and will produce an error.
If called with the optional argument @var{fcn}---a function name or
handle---return the number of declared output values that the function can
produce.
If the final output argument is @var{varargout} the returned value is
negative.
For example,
@example
f ()
@end example
@noindent
will cause @code{nargout} to return 0 inside the function @code{f} and
@example
[s, t] = f ()
@end example
@noindent
will cause @code{nargout} to return 2 inside the function @code{f}.
In the second usage,
@example
nargout (@@histc) # or nargout ("histc") using a string input
@end example
@noindent
will return 2, because @code{histc} has two outputs, whereas
@example
nargout (@@imread)
@end example
@noindent
will return -2, because @code{imread} has two outputs and the second is
@var{varargout}.
Programming Note. @code{nargout} does not work for built-in functions and
returns -1 for all anonymous functions.
@xseealso{@ref{XREFnargin,,nargin}, @ref{XREFvarargout,,varargout}, @ref{XREFisargout,,isargout}, @ref{XREFnthargout,,nthargout}}
@end deftypefn
@node Variable-length Return Lists
@section Variable-length Return Lists
@cindex variable-length return lists
@cindex @code{varargout}
@anchor{XREFvarargout}
It is possible to return a variable number of output arguments from a
function using a syntax that's similar to the one used with the
special @code{varargin} parameter name. To let a function return a
variable number of output arguments the special output parameter name
@code{varargout} is used. As with @code{varargin}, @code{varargout} is
a cell array that will contain the requested output arguments.
As an example the following function sets the first output argument to
1, the second to 2, and so on.
@example
@group
function varargout = one_to_n ()
for i = 1:nargout
varargout@{i@} = i;
endfor
endfunction
@end group
@end example
@noindent
When called this function returns values like this
@example
@group
[a, b, c] = one_to_n ()
@result{} a = 1
@result{} b = 2
@result{} c = 3
@end group
@end example
If @code{varargin} (@code{varargout}) does not appear as the last
element of the input (output) parameter list, then it is not special,
and is handled the same as any other parameter name.
@c deal scripts/general/deal.m
@anchor{XREFdeal}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {[@var{r1}, @var{r2}, @dots{}, @var{rn}] =} deal (@var{a})
@deftypefnx {} {[@var{r1}, @var{r2}, @dots{}, @var{rn}] =} deal (@var{a1}, @var{a2}, @dots{}, @var{an})
Copy the input parameters into the corresponding output parameters.
If only a single input parameter is supplied, its value is copied to each
of the outputs.
For example,
@example
[a, b, c] = deal (x, y, z);
@end example
@noindent
is equivalent to
@example
@group
a = x;
b = y;
c = z;
@end group
@end example
@noindent
and
@example
[a, b, c] = deal (x);
@end example
@noindent
is equivalent to
@example
a = b = c = x;
@end example
Programming Note: @code{deal} is often used with comma-separated lists
derived from cell arrays or structures. This is unnecessary as the
interpreter can perform the same action without the overhead of a function
call. For example:
@example
@group
c = @{[1 2], "Three", 4@};
[x, y, z] = c@{:@}
@result{}
x =
1 2
y = Three
z = 4
@end group
@end example
@xseealso{@ref{XREFcell2struct,,cell2struct}, @ref{XREFstruct2cell,,struct2cell}, @ref{XREFrepmat,,repmat}}
@end deftypefn
@node Variable-length Argument Lists
@section Variable-length Argument Lists
@cindex variable-length argument lists
@cindex @code{varargin}
@anchor{XREFvarargin}
Sometimes the number of input arguments is not known when the function
is defined. As an example think of a function that returns the smallest
of all its input arguments. For example:
@example
@group
a = smallest (1, 2, 3);
b = smallest (1, 2, 3, 4);
@end group
@end example
@noindent
In this example both @code{a} and @code{b} would be 1. One way to write
the @code{smallest} function is
@example
@group
function val = smallest (arg1, arg2, arg3, arg4, arg5)
@var{body}
endfunction
@end group
@end example
@noindent
and then use the value of @code{nargin} to determine which of the input
arguments should be considered. The problem with this approach is
that it can only handle a limited number of input arguments.
If the special parameter name @code{varargin} appears at the end of a
function parameter list it indicates that the function takes a variable
number of input arguments. Using @code{varargin} the function
looks like this
@example
@group
function val = smallest (varargin)
@var{body}
endfunction
@end group
@end example
@noindent
In the function body the input arguments can be accessed through the
variable @code{varargin}. This variable is a cell array containing
all the input arguments. @xref{Cell Arrays}, for details on working
with cell arrays. The @code{smallest} function can now be defined
like this
@example
@group
function val = smallest (varargin)
val = min ([varargin@{:@}]);
endfunction
@end group
@end example
@noindent
This implementation handles any number of input arguments, but it's also
a very simple solution to the problem.
A slightly more complex example of @code{varargin} is a function
@code{print_arguments} that prints all input arguments. Such a function
can be defined like this
@example
@group
function print_arguments (varargin)
for i = 1:length (varargin)
printf ("Input argument %d: ", i);
disp (varargin@{i@});
endfor
endfunction
@end group
@end example
@noindent
This function produces output like this
@example
@group
print_arguments (1, "two", 3);
@print{} Input argument 1: 1
@print{} Input argument 2: two
@print{} Input argument 3: 3
@end group
@end example
@c parseparams scripts/miscellaneous/parseparams.m
@anchor{XREFparseparams}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {[@var{reg}, @var{prop}] =} parseparams (@var{params})
@deftypefnx {} {[@var{reg}, @var{var1}, @dots{}] =} parseparams (@var{params}, @var{name1}, @var{default1}, @dots{})
Return in @var{reg} the cell elements of @var{param} up to the first
string element and in @var{prop} all remaining elements beginning with the
first string element.
For example:
@example
@group
[reg, prop] = parseparams (@{1, 2, "linewidth", 10@})
reg =
@{
[1,1] = 1
[1,2] = 2
@}
prop =
@{
[1,1] = linewidth
[1,2] = 10
@}
@end group
@end example
The parseparams function may be used to separate regular numeric arguments
from additional arguments given as property/value pairs of the
@var{varargin} cell array.
In the second form of the call, available options are specified directly
with their default values given as name-value pairs. If @var{params} do
not form name-value pairs, or if an option occurs that does not match any
of the available options, an error occurs.
When called from an m-file function, the error is prefixed with the name
of the caller function.
The matching of options is case-insensitive.
@xseealso{@ref{XREFvarargin,,varargin}, @ref{XREFinputParser,,inputParser}}
@end deftypefn
@node Ignoring Arguments
@section Ignoring Arguments
In the formal argument list, it is possible to use the dummy placeholder
@code{~} instead of a name. This indicates that the corresponding argument
value should be ignored and not stored to any variable.
@example
@group
function val = pick2nd (~, arg2)
val = arg2;
endfunction
@end group
@end example
The value of @code{nargin} is not affected by using this declaration.
Return arguments can also be ignored using the same syntax. For example, the
sort function returns both the sorted values, and an index vector for the
original input which will result in a sorted output. Ignoring the second
output is simple---don't request more than one output. But ignoring the first,
and calculating just the second output, requires the use of the @code{~}
placeholder.
@example
@group
x = [2, 3, 1];
[s, i] = sort (x)
@result{}
s =
1 2 3
i =
3 1 2
[~, i] = sort (x)
@result{}
i =
3 1 2
@end group
@end example
When using the @code{~} placeholder, commas---not whitespace---must be used
to separate output arguments. Otherwise, the interpreter will view @code{~} as
the logical not operator.
@example
@group
[~ i] = sort (x)
parse error:
invalid left hand side of assignment
@end group
@end example
Functions may take advantage of ignored outputs to reduce the number of
calculations performed. To do so, use the @code{isargout} function to query
whether the output argument is wanted. For example:
@example
@group
function [out1, out2] = long_function (x, y, z)
if (isargout (1))
## Long calculation
@dots{}
out1 = result;
endif
@dots{}
endfunction
@end group
@end example
@c isargout libinterp/octave-value/ov-usr-fcn.cc
@anchor{XREFisargout}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {@var{tf} =} isargout (@var{k})
Within a function, return a logical value indicating whether the argument
@var{k} will be assigned to a variable on output.
If the result is false, the argument has been ignored during the function
call through the use of the tilde (~) special output argument. Functions
can use @code{isargout} to avoid performing unnecessary calculations for
outputs which are unwanted.
If @var{k} is outside the range @code{1:max (nargout)}, the function returns
false. @var{k} can also be an array, in which case the function works
element-by-element and a logical array is returned. At the top level,
@code{isargout} returns an error.
@xseealso{@ref{XREFnargout,,nargout}, @ref{XREFvarargout,,varargout}, @ref{XREFnthargout,,nthargout}}
@end deftypefn
@node Default Arguments
@section Default Arguments
@cindex default arguments
Since Octave supports variable number of input arguments, it is very useful
to assign default values to some input arguments. When an input argument
is declared in the argument list it is possible to assign a default
value to the argument like this
@example
@group
function @var{name} (@var{arg1} = @var{val1}, @dots{})
@var{body}
endfunction
@end group
@end example
@noindent
If no value is assigned to @var{arg1} by the user, it will have the
value @var{val1}.
As an example, the following function implements a variant of the classic
``Hello, World'' program.
@example
@group
function hello (who = "World")
printf ("Hello, %s!\n", who);
endfunction
@end group
@end example
@noindent
When called without an input argument the function prints the following
@example
@group
hello ();
@print{} Hello, World!
@end group
@end example
@noindent
and when it's called with an input argument it prints the following
@example
@group
hello ("Beautiful World of Free Software");
@print{} Hello, Beautiful World of Free Software!
@end group
@end example
Sometimes it is useful to explicitly tell Octave to use the default value
of an input argument. This can be done writing a @samp{:} as the value
of the input argument when calling the function.
@example
@group
hello (:);
@print{} Hello, World!
@end group
@end example
@node Validating Arguments
@section Validating Arguments
@cindex validating arguments
Octave is a weakly typed programming language. Thus it is possible to
call a function with arguments, that probably cause errors or might have
undesirable side effects. For example calling a string processing function
with a huge sparse matrix.
It is good practice at the head of a function to verify that it has been
called correctly. Octave offers several functions for this purpose.
@menu
* Validating the number of Arguments::
* Validating the type of Arguments::
* Parsing Arguments::
@end menu
@node Validating the number of Arguments
@subsection Validating the number of Arguments
In Octave the following idiom is seen frequently at the beginning of a
function definition:
@example
@group
if (nargin < min_#_inputs || nargin > max_#_inputs)
print_usage ();
endif
@end group
@end example
@noindent
which stops the function execution and prints a message about the correct
way to call the function whenever the number of inputs is wrong.
Similar error checking is provided by @code{narginchk} and
@code{nargoutchk}.
@c narginchk scripts/miscellaneous/narginchk.m
@anchor{XREFnarginchk}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {} narginchk (@var{minargs}, @var{maxargs})
Check for correct number of input arguments.
Generate an error message if the number of arguments in the calling function
is outside the range @var{minargs} and @var{maxargs}. Otherwise, do
nothing.
Both @var{minargs} and @var{maxargs} must be scalar numeric values. Zero,
Inf, and negative values are all allowed, and @var{minargs} and
@var{maxargs} may be equal.
Note that this function evaluates @code{nargin} on the caller.
@xseealso{@ref{XREFnargoutchk,,nargoutchk}, @ref{XREFerror,,error}, @ref{XREFnargout,,nargout}, @ref{XREFnargin,,nargin}}
@end deftypefn
@c nargoutchk scripts/miscellaneous/nargoutchk.m
@anchor{XREFnargoutchk}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {} nargoutchk (@var{minargs}, @var{maxargs})
@deftypefnx {} {@var{msgstr} =} nargoutchk (@var{minargs}, @var{maxargs}, @var{nargs})
@deftypefnx {} {@var{msgstr} =} nargoutchk (@var{minargs}, @var{maxargs}, @var{nargs}, "string")
@deftypefnx {} {@var{msgstruct} =} nargoutchk (@var{minargs}, @var{maxargs}, @var{nargs}, "struct")
Check for correct number of output arguments.
In the first form, return an error if the number of arguments is not between
@var{minargs} and @var{maxargs}. Otherwise, do nothing. Note that this
function evaluates the value of @code{nargout} on the caller so its value
must have not been tampered with.
Both @var{minargs} and @var{maxargs} must be numeric scalars. Zero, Inf,
and negative are all valid, and they can have the same value.
For backwards compatibility, the other forms return an appropriate error
message string (or structure) if the number of outputs requested is
invalid.
This is useful for checking to that the number of output arguments supplied
to a function is within an acceptable range.
@xseealso{@ref{XREFnarginchk,,narginchk}, @ref{XREFerror,,error}, @ref{XREFnargout,,nargout}, @ref{XREFnargin,,nargin}}
@end deftypefn
@node Validating the type of Arguments
@subsection Validating the type of Arguments
Besides the number of arguments, inputs can be checked for various
properties. @code{validatestring} is used for string arguments and
@code{validateattributes} for numeric arguments.
@c validatestring scripts/strings/validatestring.m
@anchor{XREFvalidatestring}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {@var{validstr} =} validatestring (@var{str}, @var{strarray})
@deftypefnx {} {@var{validstr} =} validatestring (@var{str}, @var{strarray}, @var{funcname})
@deftypefnx {} {@var{validstr} =} validatestring (@var{str}, @var{strarray}, @var{funcname}, @var{varname})
@deftypefnx {} {@var{validstr} =} validatestring (@dots{}, @var{position})
Verify that @var{str} is an element, or substring of an element, in
@var{strarray}.
When @var{str} is a character string to be tested, and @var{strarray} is a
cell array of strings of valid values, then @var{validstr} will be the
validated form of @var{str} where validation is defined as @var{str} being
a member or substring of @var{validstr}. This is useful for both verifying
and expanding short options, such as @qcode{"r"}, to their longer forms,
such as @qcode{"red"}. If @var{str} is a substring of @var{validstr},
and there are multiple matches, the shortest match will be returned if
all matches are substrings of each other. Otherwise, an error will be
raised because the expansion of @var{str} is ambiguous. All comparisons
are case insensitive.
The additional inputs @var{funcname}, @var{varname}, and @var{position}
are optional and will make any generated validation error message more
specific.
Examples:
@c Set example in small font to prevent overfull line
@smallexample
@group
validatestring ("r", @{"red", "green", "blue"@})
@result{} "red"
validatestring ("b", @{"red", "green", "blue", "black"@})
@result{} error: validatestring: multiple unique matches were found for 'b':
blue, black
@end group
@end smallexample
@xseealso{@ref{XREFstrcmp,,strcmp}, @ref{XREFstrcmpi,,strcmpi}, @ref{XREFvalidateattributes,,validateattributes}, @ref{XREFinputParser,,inputParser}}
@end deftypefn
@c validateattributes scripts/miscellaneous/validateattributes.m
@anchor{XREFvalidateattributes}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {} validateattributes (@var{A}, @var{classes}, @var{attributes})
@deftypefnx {} {} validateattributes (@var{A}, @var{classes}, @var{attributes}, @var{arg_idx})
@deftypefnx {} {} validateattributes (@var{A}, @var{classes}, @var{attributes}, @var{func_name})
@deftypefnx {} {} validateattributes (@var{A}, @var{classes}, @var{attributes}, @var{func_name}, @var{arg_name})
@deftypefnx {} {} validateattributes (@var{A}, @var{classes}, @var{attributes}, @var{func_name}, @var{arg_name}, @var{arg_idx})
Check validity of input argument.
Confirms that the argument @var{A} is valid by belonging to one of
@var{classes}, and holding all of the @var{attributes}. If it does not,
an error is thrown, with a message formatted accordingly. The error
message can be made further complete by the function name @var{fun_name},
the argument name @var{arg_name}, and its position in the input
@var{arg_idx}.
@var{classes} must be a cell array of strings (an empty cell array is
allowed) with the name of classes (remember that a class name is case
sensitive). In addition to the class name, the following categories
names are also valid:
@table @asis
@item @qcode{"float"}
Floating point value comprising classes @qcode{"double"} and
@qcode{"single"}.
@item @qcode{"integer"}
Integer value comprising classes (u)int8, (u)int16, (u)int32, (u)int64.
@item @qcode{"numeric"}
Numeric value comprising either a floating point or integer value.
@end table
@var{attributes} must be a cell array with names of checks for @var{A}.
Some of them require an additional value to be supplied right after the
name (see details for each below).
@table @asis
@item @qcode{"<="}
All values are less than or equal to the following value in
@var{attributes}.
@item @qcode{"<"}
All values are less than the following value in @var{attributes}.
@item @qcode{">="}
All values are greater than or equal to the following value in
@var{attributes}.
@item @qcode{">"}
All values are greater than the following value in @var{attributes}.
@item @qcode{"2d"}
A 2-dimensional matrix. Note that vectors and empty matrices have
2 dimensions, one of them being of length 1, or both length 0.
@item @qcode{"3d"}
Has no more than 3 dimensions. A 2-dimensional matrix is a 3-D matrix
whose 3rd dimension is of length 1.
@item @qcode{"binary"}
All values are either 1 or 0.
@item @qcode{"column"}
Values are arranged in a single column.
@item @qcode{"decreasing"}
No value is @var{NaN}, and each is less than the preceding one.
@item @qcode{"diag"}
Value is a diagonal matrix.
@item @qcode{"even"}
All values are even numbers.
@item @qcode{"finite"}
All values are finite.
@item @qcode{"increasing"}
No value is @var{NaN}, and each is greater than the preceding one.
@item @qcode{"integer"}
All values are integer. This is different than using @code{isinteger}
which only checks its an integer type. This checks that each value in
@var{A} is an integer value, i.e., it has no decimal part.
@item @qcode{"ncols"}
Has exactly as many columns as the next value in @var{attributes}.
@item @qcode{"ndims"}
Has exactly as many dimensions as the next value in @var{attributes}.
@item @qcode{"nondecreasing"}
No value is @var{NaN}, and each is greater than or equal to the preceding
one.
@item @qcode{"nonempty"}
It is not empty.
@item @qcode{"nonincreasing"}
No value is @var{NaN}, and each is less than or equal to the preceding one.
@item @qcode{"nonnan"}
No value is a @code{NaN}.
@item @nospell{@qcode{"nonnegative"}}
All values are non negative.
@item @qcode{"nonsparse"}
It is not a sparse matrix.
@item @qcode{"nonzero"}
No value is zero.
@item @qcode{"nrows"}
Has exactly as many rows as the next value in @var{attributes}.
@item @qcode{"numel"}
Has exactly as many elements as the next value in @var{attributes}.
@item @qcode{"odd"}
All values are odd numbers.
@item @qcode{"positive"}
All values are positive.
@item @qcode{"real"}
It is a non-complex matrix.
@item @qcode{"row"}
Values are arranged in a single row.
@item @qcode{"scalar"}
It is a scalar.
@item @qcode{"size"}
Its size has length equal to the values of the next in @var{attributes}.
The next value must is an array with the length for each dimension. To
ignore the check for a certain dimension, the value of @code{NaN} can be
used.
@item @qcode{"square"}
Is a square matrix.
@item @qcode{"vector"}
Values are arranged in a single vector (column or vector).
@end table
@xseealso{@ref{XREFisa,,isa}, @ref{XREFvalidatestring,,validatestring}, @ref{XREFinputParser,,inputParser}}
@end deftypefn
As alternatives to @code{validateattributes} there are several shorter
convenience functions to check for individual properties.
@c mustBeFinite scripts/miscellaneous/mustBeFinite.m
@anchor{XREFmustBeFinite}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {} mustBeFinite (@var{x})
Require that input @var{x} is finite.
Raise an error if any element of the input @var{x} is not finite, as
determined by @code{isfinite (x)}.
@xseealso{@ref{XREFmustBeNonNan,,mustBeNonNan}, @ref{XREFisfinite,,isfinite}}
@end deftypefn
@c mustBeGreaterThan scripts/miscellaneous/mustBeGreaterThan.m
@anchor{XREFmustBeGreaterThan}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {} mustBeGreaterThan (@var{x}, @var{c})
Require that input @var{x} is greater than @var{c}.
Raise an error if any element of the input @var{x} is not greater than
@var{c}, as determined by @code{@var{x} > @var{c}}.
@xseealso{@ref{XREFmustBeGreaterThanOrEqual,,mustBeGreaterThanOrEqual}, @ref{XREFmustBeLessThan,,mustBeLessThan}, @ref{XREFgt,,gt}}
@end deftypefn
@c mustBeGreaterThanOrEqual scripts/miscellaneous/mustBeGreaterThanOrEqual.m
@anchor{XREFmustBeGreaterThanOrEqual}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {} mustBeGreaterThanOrEqual (@var{x}, @var{c})
Require that input @var{x} is greater than or equal to @var{c}.
Raise an error if any element of the input @var{x} is not greater than
or equal to @var{c}, as determined by @code{@var{x} >= @var{c}}.
@xseealso{@ref{XREFmustBeGreaterThan,,mustBeGreaterThan}, @ref{XREFmustBeLessThanOrEqual,,mustBeLessThanOrEqual}, @ref{XREFge,,ge}}
@end deftypefn
@c mustBeInteger scripts/miscellaneous/mustBeInteger.m
@anchor{XREFmustBeInteger}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {} mustBeInteger (@var{x})
Require that input @var{x} is integer-valued (but not necessarily
integer-typed).
Raise an error if any element of the input @var{x} is not a finite,
real, integer-valued numeric value, as determined by various checks.
@xseealso{@ref{XREFmustBeNumeric,,mustBeNumeric}}
@end deftypefn
@c mustBeLessThan scripts/miscellaneous/mustBeLessThan.m
@anchor{XREFmustBeLessThan}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {} mustBeLessThan (@var{x}, @var{c})
Require that input @var{x} is less than @var{c}.
Raise an error if any element of the input @var{x} is not less than
@var{c}, as determined by @code{@var{x} < @var{c}}.
@xseealso{@ref{XREFmustBeLessThanOrEqual,,mustBeLessThanOrEqual}, @ref{XREFmustBeGreaterThan,,mustBeGreaterThan}, @ref{XREFlt,,lt}}
@end deftypefn
@c mustBeLessThanOrEqual scripts/miscellaneous/mustBeLessThanOrEqual.m
@anchor{XREFmustBeLessThanOrEqual}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {} mustBeLessThanOrEqual (@var{x}, @var{c})
Require that input is less than or equal to a given value.
Raise an error if any element of the input @var{x} is not less than
or equal to @var{c}, as determined by @code{@var{x} <= @var{c}}.
@xseealso{@ref{XREFmustBeLessThan,,mustBeLessThan}, @ref{XREFmustBeGreaterThanOrEqual,,mustBeGreaterThanOrEqual}, @ref{XREFle,,le}}
@end deftypefn
@c mustBeMember scripts/miscellaneous/mustBeMember.m
@anchor{XREFmustBeMember}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {} mustBeMember (@var{x}, @var{valid})
Require that input @var{x} is a member of a set of given valid values.
Raise an error if any element of the input @var{x} is not a member
of the set @var{valid}, as determined by @code{ismember (@var{x})}.
Programming Note: char inputs may behave strangely because of the
interaction between chars and cellstrings when calling @code{ismember} on
them. But it will probably "do what you mean" if you just use it naturally.
To guarantee operation, convert all char arrays to cellstrings with
@code{cellstr}.
@xseealso{@ref{XREFmustBeNonempty,,mustBeNonempty}, @ref{XREFismember,,ismember}}
@end deftypefn
@c mustBeNegative scripts/miscellaneous/mustBeNegative.m
@anchor{XREFmustBeNegative}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {} mustBeNegative (@var{x})
Require that input @var{x} is negative.
Raise an error if any element of the input @var{x} is not negative, as
determined by @code{@var{x} < 0}.
@xseealso{@ref{XREFmustBeNonnegative,,mustBeNonnegative}}
@end deftypefn
@c mustBeNonempty scripts/miscellaneous/mustBeNonempty.m
@anchor{XREFmustBeNonempty}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {} mustBeNonempty (@var{x})
Require that input @var{x} is nonempty.
Raise an error if the input @var{x} is empty, as determined by
@code{isempty (@var{x})}.
@xseealso{@ref{XREFmustBeMember,,mustBeMember}, @ref{XREFmustBeNonzero,,mustBeNonzero}, @ref{XREFisempty,,isempty}}
@end deftypefn
@c mustBeNonNan scripts/miscellaneous/mustBeNonNan.m
@anchor{XREFmustBeNonNan}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {} mustBeNonNan (@var{x})
Require that input @var{x} is non-@code{NaN}.
Raise an error if any element of the input @var{x} is @code{NaN}, as
determined by @code{isnan (@var{x})}.
@xseealso{@ref{XREFmustBeFinite,,mustBeFinite}, @ref{XREFmustBeNonempty,,mustBeNonempty}, @ref{XREFisnan,,isnan}}
@end deftypefn
@c mustBeNonnegative scripts/miscellaneous/mustBeNonnegative.m
@anchor{XREFmustBeNonnegative}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {} mustBeNonnegative (@var{x})
Require that input @var{x} is not negative.
Raise an error if any element of the input @var{x} is negative, as
determined by @code{@var{x} >= 0}.
@xseealso{@ref{XREFmustBeNonzero,,mustBeNonzero}, @ref{XREFmustBePositive,,mustBePositive}}
@end deftypefn
@c mustBeNonpositive scripts/miscellaneous/mustBeNonpositive.m
@anchor{XREFmustBeNonpositive}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {} mustBeNonpositive (@var{x})
Require that input @var{x} is not positive.
Raise an error if any element of the input @var{x} is positive, as
determined by @code{@var{x} <= 0}.
@xseealso{@ref{XREFmustBeNegative,,mustBeNegative}, @ref{XREFmustBeNonzero,,mustBeNonzero}}
@end deftypefn
@c mustBeNonsparse scripts/miscellaneous/mustBeNonsparse.m
@anchor{XREFmustBeNonsparse}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {} mustBeNonsparse (@var{x})
Require that input @var{x} is not sparse.
Raise an error if the input @var{x} is sparse, as determined by
@code{issparse (@var{x})}.
@xseealso{@ref{XREFissparse,,issparse}}
@end deftypefn
@c mustBeNonzero scripts/miscellaneous/mustBeNonzero.m
@anchor{XREFmustBeNonzero}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {} mustBeNonzero (@var{x})
Require that input @var{x} is not zero.
Raise an error if any element of the input @var{x} is zero, as determined
by @code{@var{x} == 0}.
@xseealso{@ref{XREFmustBeNonnegative,,mustBeNonnegative}, @ref{XREFmustBePositive,,mustBePositive}}
@end deftypefn
@c mustBeNumeric scripts/miscellaneous/mustBeNumeric.m
@anchor{XREFmustBeNumeric}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {} mustBeNumeric (@var{x})
Require that input @var{x} is numeric.
Raise an error if the input @var{x} is not numeric, as determined by
@code{isnumeric (@var{x})}.
@xseealso{@ref{XREFmustBeNumericOrLogical,,mustBeNumericOrLogical}, @ref{XREFisnumeric,,isnumeric}}
@end deftypefn
@c mustBeNumericOrLogical scripts/miscellaneous/mustBeNumericOrLogical.m
@anchor{XREFmustBeNumericOrLogical}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {} mustBeNumericOrLogical (@var{x})
Require that input @var{x} is numeric or logical.
Raise an error if the input @var{x} is not numeric or logical, as
determined by @code{isnumeric (@var{x}) || islogical (@var{x})}.
@xseealso{@ref{XREFmustBeNumeric,,mustBeNumeric}, @ref{XREFisnumeric,,isnumeric}, @ref{XREFislogical,,islogical}}
@end deftypefn
@c mustBePositive scripts/miscellaneous/mustBePositive.m
@anchor{XREFmustBePositive}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {} mustBePositive (@var{x})
Require that input @var{x} is positive.
Raise an error if any element of the input @var{x} is not positive, as
determined by @code{@var{x} > 0}.
@xseealso{@ref{XREFmustBeNonnegative,,mustBeNonnegative}, @ref{XREFmustBeNonzero,,mustBeNonzero}}
@end deftypefn
@c mustBeReal scripts/miscellaneous/mustBeReal.m
@anchor{XREFmustBeReal}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {} mustBeReal (@var{x})
Require that input @var{x} is real.
Raise an error if the input @var{x} is not real, as determined by
@code{isreal (@var{x})}.
@xseealso{@ref{XREFmustBeFinite,,mustBeFinite}, @ref{XREFmustBeNonNan,,mustBeNonNan}, @ref{XREFisreal,,isreal}}
@end deftypefn
@node Parsing Arguments
@subsection Parsing Arguments
If none of the preceding validation functions is sufficient there is also
the class @code{inputParser} which can perform extremely complex input
checking for functions.
@c inputParser scripts/miscellaneous/inputParser.m
@anchor{XREFinputParser}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {@var{p} =} inputParser ()
Create object @var{p} of the inputParser class.
This class is designed to allow easy parsing of function arguments. The
class supports four types of arguments:
@enumerate
@item mandatory (see @code{addRequired});
@item optional (see @code{addOptional});
@item named (see @code{addParameter});
@item switch (see @code{addSwitch}).
@end enumerate
After defining the function API with these methods, the supplied arguments
can be parsed with the @code{parse} method and the results accessed with
the @code{Results} accessor.
@end deftypefn
@deftypefn {} {} inputParser.Parameters
Return the list of parameter names already defined. (read-only)
@end deftypefn
@deftypefn {} {} inputParser.Results
Return a structure with argument names as fieldnames and corresponding
values. (read-only)
@end deftypefn
@deftypefn {} {} inputParser.Unmatched
Return a structure similar to @code{Results}, but for unmatched
parameters. (read-only)
See the @code{KeepUnmatched} property.
@end deftypefn
@deftypefn {} {} inputParser.UsingDefaults
Return cell array with the names of arguments that are using default
values. (read-only)
@end deftypefn
@deftypefn {} {} inputParser.FunctionName = @var{name}
Set function name to be used in error messages; Defaults to empty string.
@end deftypefn
@deftypefn {} {} inputParser.CaseSensitive = @var{boolean}
Set whether matching of argument names should be case sensitive; Defaults
to false.
@end deftypefn
@deftypefn {} {} inputParser.KeepUnmatched = @var{boolean}
Set whether string arguments which do not match any Parameter are parsed
and stored in the @code{Unmatched} property; Defaults to false. If false,
an error will be emitted at the first unrecognized argument and parsing
will stop. Note that since @code{Switch} and @code{Parameter} arguments
can be mixed, it is not possible to know the type of the unmatched
argument. Octave assumes that all unmatched arguments are of the
@code{Parameter} type and therefore must be followed by a value.
@end deftypefn
@deftypefn {} {} inputParser.PartialMatching = @var{boolean}
Set whether argument names for @code{Parameter} and @code{Switch} options
may be given in shortened form as long as the name uniquely identifies
an option; Defaults to true. For example, the argument @qcode{'opt'} will
match a parameter @qcode{'opt_color'}, but will fail if there is also a
parameter @qcode{'opt_case'}.
@end deftypefn
@deftypefn {} {} inputParser.StructExpand = @var{boolean}
Set whether a structure passed to the function is expanded into
parameter/value pairs (parameter = fieldname); Defaults to true.
The following example shows how to use this class:
@example
function check (varargin)
@c The next two comments need to be indented by one for alignment
p = inputParser (); # create object
p.FunctionName = "check"; # set function name
p.addRequired ("pack", @@ischar); # mandatory argument
p.addOptional ("path", pwd(), @@ischar); # optional argument
## Create anonymous function handle for validators
valid_vec = @@(x) isvector (x) && all (x >= 0) && all (x <= 1);
p.addOptional ("vec", [0 0], valid_vec);
## Create two arguments of type "Parameter"
vld_type = @@(x) any (strcmp (x, @{"linear", "quadratic"@}));
p.addParameter ("type", "linear", vld_type);
vld_tol = @@(x) any (strcmp (x, @{"low", "medium", "high"@}));
p.addParameter ("tolerance", "low", vld_tol);
## Create a switch type of argument
p.addSwitch ("verbose");
p.parse (varargin@{:@}); # Run created parser on inputs
## The rest of the function can access inputs by using p.Results.
## For example, get the tolerance input with p.Results.tolerance
endfunction
@end example
@example
@group
check ("mech"); # valid, use defaults for other arguments
check (); # error, one argument is mandatory
check (1); # error, since ! ischar
check ("mech", "~/dev"); # valid, use defaults for other arguments
check ("mech", "~/dev", [0 1 0 0], "type", "linear"); # valid
## following is also valid. Note how the Switch argument type can
## be mixed in with or before the Parameter argument type (but it
## must still appear after any Optional arguments).
check ("mech", "~/dev", [0 1 0 0], "verbose", "tolerance", "high");
## following returns an error since an Optional argument, 'path',
## was given after the Parameter argument 'type'.
check ("mech", "type", "linear", "~/dev");
@end group
@end example
@emph{Note 1}: A function can have any mixture of the four API types but
they must appear in a specific order. @code{Required} arguments must be
first and can be followed by any @code{Optional} arguments. Only the
@code{Parameter} and @code{Switch} arguments may be mixed together and
they must appear following the first two types.
@emph{Note 2}: If both @code{Optional} and @code{Parameter} arguments
are mixed in a function API then once a string Optional argument fails to
validate it will be considered the end of the @code{Optional} arguments.
The remaining arguments will be compared against any @code{Parameter} or
@code{Switch} arguments.
@xseealso{@ref{XREFnargin,,nargin}, @ref{XREFvalidateattributes,,validateattributes}, @ref{XREFvalidatestring,,validatestring}, @ref{XREFvarargin,,varargin}}
@end deftypefn
@node Function Files
@section Function Files
@cindex function file
Except for simple one-shot programs, it is not practical to have to
define all the functions you need each time you need them. Instead, you
will normally want to save them in a file so that you can easily edit
them, and save them for use at a later time.
Octave does not require you to load function definitions from files
before using them. You simply need to put the function definitions in a
place where Octave can find them.
When Octave encounters an identifier that is undefined, it first looks
for variables or functions that are already compiled and currently
listed in its symbol table. If it fails to find a definition there, it
searches a list of directories (the @dfn{path}) for files ending in
@file{.m} that have the same base name as the undefined
identifier.@footnote{The @samp{.m} suffix was chosen for compatibility
with @sc{matlab}.} Once Octave finds a file with a name that matches,
the contents of the file are read. If it defines a @emph{single}
function, it is compiled and executed. @xref{Script Files}, for more
information about how you can define more than one function in a single
file.
When Octave defines a function from a function file, it saves the full
name of the file it read and the time stamp on the file. If the time
stamp on the file changes, Octave may reload the file. When Octave is
running interactively, time stamp checking normally happens at most once
each time Octave prints the prompt. Searching for new function
definitions also occurs if the current working directory changes.
Checking the time stamp allows you to edit the definition of a function
while Octave is running, and automatically use the new function
definition without having to restart your Octave session.
To avoid degrading performance unnecessarily by checking the time stamps
on functions that are not likely to change, Octave assumes that function
files in the directory tree
@file{@var{octave-home}/share/octave/@var{version}/m}
will not change, so it doesn't have to check their time stamps every time the
functions defined in those files are used. This is normally a very good
assumption and provides a significant improvement in performance for the
function files that are distributed with Octave.
If you know that your own function files will not change while you are
running Octave, you can improve performance by calling
@code{ignore_function_time_stamp ("all")}, so that Octave will
ignore the time stamps for all function files. Passing
@qcode{"system"} to this function resets the default behavior.
@c FIXME: note about time stamps on files in NFS environments?
@c edit scripts/miscellaneous/edit.m
@anchor{XREFedit}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {} edit @var{name}
@deftypefnx {} {} edit @var{field} @var{value}
@deftypefnx {} {@var{value} =} edit ("get", @var{field})
@deftypefnx {} {@var{value} =} edit ("get", "all")
Edit the named function, or change editor settings.
If @code{edit} is called with the name of a file or function as its
argument it will be opened in the default text editor. The default editor
for the Octave GUI is specified in the Editor tab of Preferences. The
default editor for the CLI is specified by the @code{EDITOR} function.
@itemize @bullet
@item
If the function @var{name} is available in a file on your path, then it
will be opened in the editor. If no file is found, then the m-file
variant, ending with @qcode{".m"}, will be considered. If still no file is
found, then variants with a leading @qcode{"@@"} and then with both a
leading @qcode{"@@"} and trailing @qcode{".m"} will be considered.
@item
If @var{name} is the name of a command-line function, then an m-file will
be created to contain that function along with its current definition.
@item
If @code{@var{name}.cc} is specified, then it will search for
@file{@var{name}.cc} in the path and open it in the editor. If the file is
not found, then a new @file{.cc} file will be created. If @var{name}
happens to be an m-file or command-line function, then the text of that
function will be inserted into the .cc file as a comment.
@item
If @file{@var{name}.ext} is on your path then it will be edited, otherwise
the editor will be started with @file{@var{name}.ext} in the current
directory as the filename.
@strong{Warning:} You may need to clear @var{name} before the new definition
is available. If you are editing a .cc file, you will need to execute
@code{mkoctfile @file{@var{name}.cc}} before the definition will be
available.
@end itemize
If @code{edit} is called with @var{field} and @var{value} variables, the
value of the control field @var{field} will be set to @var{value}.
If an output argument is requested and the first input argument is
@code{get} then @code{edit} will return the value of the control field
@var{field}. If the control field does not exist, edit will return a
structure containing all fields and values. Thus, @code{edit ("get",
@qcode{"all"})} returns a complete control structure.
The following control fields are used:
@table @samp
@item author
This is the name to put after the "## Author:" field of new functions. By
default it guesses from the @code{gecos} field of the password database.
@item email
This is the e-mail address to list after the name in the author field. By
default it guesses @code{<$LOGNAME@@$HOSTNAME>}, and if @code{$HOSTNAME}
is not defined it uses @code{uname -n}. You probably want to override
this. Be sure to use the format @code{@email{user@@host}}.
@item license
@table @samp
@item gpl
GNU General Public License (default).
@item bsd
BSD-style license without advertising clause.
@item pd
Public domain.
@item "text"
Your own default copyright and license.
@end table
Unless you specify @samp{pd}, edit will prepend the copyright statement
with "Copyright (C) YYYY Author".
@item mode
This value determines whether the editor should be started in async mode
(editor is started in the background and Octave continues) or sync mode
(Octave waits until the editor exits). Set it to @qcode{"sync"} to start
the editor in sync mode. The default is @qcode{"async"}
(@pxref{XREFsystem,,@code{system}}).
@item editinplace
Determines whether files should be edited in place, without regard to
whether they are modifiable or not. The default is @code{true}.
Set it to @code{false} to have read-only function files automatically
copied to @samp{home}, if it exists, when editing them.
@item home
This value indicates a directory that system m-files should be copied into
before opening them in the editor. The intent is that this directory is
also in the path, so that the edited copy of a system function file shadows
the original. This setting only has an effect when @samp{editinplace} is
set to @code{false}. The default is the empty matrix (@code{[]}), which
means it is not used. The default in previous versions of Octave was
@file{~/octave}.
@end table
@xseealso{@ref{XREFEDITOR,,EDITOR}, @ref{XREFpath,,path}}
@end deftypefn
@c mfilename libinterp/parse-tree/oct-parse.yy
@anchor{XREFmfilename}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {} mfilename ()
@deftypefnx {} {} mfilename ("fullpath")
@deftypefnx {} {} mfilename ("fullpathext")
Return the name of the currently executing file.
The base name of the currently executing script or function is returned without
any extension. If called from outside an m-file, such as the command line,
return the empty string.
Given the argument @qcode{"fullpath"}, include the directory part of the
filename, but not the extension.
Given the argument @qcode{"fullpathext"}, include the directory part of
the filename and the extension.
@xseealso{@ref{XREFinputname,,inputname}, @ref{XREFdbstack,,dbstack}}
@end deftypefn
@c ignore_function_time_stamp libinterp/corefcn/fcn-info.cc
@anchor{XREFignore_function_time_stamp}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {@var{val} =} ignore_function_time_stamp ()
@deftypefnx {} {@var{old_val} =} ignore_function_time_stamp (@var{new_val})
Query or set the internal variable that controls whether Octave checks
the time stamp on files each time it looks up functions defined in
function files.
If the internal variable is set to @qcode{"system"}, Octave will not
automatically recompile function files in subdirectories of
@file{@var{octave-home}/share/@var{version}/m} if they have changed since
they were last compiled, but will recompile other function files in the
search path if they change.
If set to @qcode{"all"}, Octave will not recompile any function files
unless their definitions are removed with @code{clear}.
If set to @qcode{"none"}, Octave will always check time stamps on files
to determine whether functions defined in function files need to
recompiled.
@end deftypefn
@menu
* Manipulating the Load Path::
* Subfunctions::
* Private Functions::
* Nested Functions::
* Overloading and Autoloading::
* Function Locking::
* Function Precedence::
@end menu
@node Manipulating the Load Path
@subsection Manipulating the Load Path
When a function is called, Octave searches a list of directories for
a file that contains the function declaration. This list of directories
is known as the load path. By default the load path contains
a list of directories distributed with Octave plus the current
working directory. To see your current load path call the @code{path}
function without any input or output arguments.
It is possible to add or remove directories to or from the load path
using @code{addpath} and @code{rmpath}. As an example, the following
code adds @samp{~/Octave} to the load path.
@example
addpath ("~/Octave")
@end example
@noindent
After this the directory @samp{~/Octave} will be searched for functions.
@c addpath libinterp/corefcn/load-path.cc
@anchor{XREFaddpath}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {} addpath (@var{dir1}, @dots{})
@deftypefnx {} {} addpath (@var{dir1}, @dots{}, @var{option})
@deftypefnx {} {@var{oldpath} =} addpath (@dots{})
Add named directories to the function search path.
If @var{option} is @qcode{"-begin"} or 0 (the default), prepend the directory
name(s) to the current path. If @var{option} is @qcode{"-end"} or 1, append
the directory name(s) to the current path. Directories added to the path must
exist.
In addition to accepting individual directory arguments, lists of
directory names separated by @code{pathsep} are also accepted. For example:
@example
addpath ("dir1:/dir2:~/dir3")
@end example
The newly added paths appear in the load path in the same order that they
appear in the arguments of @code{addpath}. When extending the load path to
the front, the last path in the list of arguments is added first. When
extending the load path to the end, the first path in the list of arguments
is added first.
For each directory that is added, and that was not already in the path,
@code{addpath} checks for the existence of a file named @file{PKG_ADD}
(note lack of .m extension) and runs it if it exists.
@xseealso{@ref{XREFpath,,path}, @ref{XREFrmpath,,rmpath}, @ref{XREFgenpath,,genpath}, @ref{XREFpathdef,,pathdef}, @ref{XREFsavepath,,savepath}, @ref{XREFpathsep,,pathsep}}
@end deftypefn
@c genpath libinterp/corefcn/load-path.cc
@anchor{XREFgenpath}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {@var{pathstr} =} genpath (@var{dir})
@deftypefnx {} {@var{pathstr} =} genpath (@var{dir}, @var{skipdir1}, @dots{})
Return a path constructed from @var{dir} and all its subdirectories.
The path does not include package directories (beginning with @samp{+}),
old-style class directories (beginning with @samp{@@}), @file{private}
directories, or any subdirectories of these types.
If additional string parameters are given, the resulting path will exclude
directories with those names.
@xseealso{@ref{XREFpath,,path}, @ref{XREFaddpath,,addpath}}
@end deftypefn
@c rmpath libinterp/corefcn/load-path.cc
@anchor{XREFrmpath}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {} rmpath (@var{dir1}, @dots{})
@deftypefnx {} {@var{oldpath} =} rmpath (@var{dir1}, @dots{})
Remove @var{dir1}, @dots{} from the current function search path.
In addition to accepting individual directory arguments, lists of
directory names separated by @code{pathsep} are also accepted. For example:
@example
rmpath ("dir1:/dir2:~/dir3")
@end example
For each directory that is removed, @code{rmpath} checks for the
existence of a file named @file{PKG_DEL} (note lack of .m extension)
and runs it if it exists.
@xseealso{@ref{XREFpath,,path}, @ref{XREFaddpath,,addpath}, @ref{XREFgenpath,,genpath}, @ref{XREFpathdef,,pathdef}, @ref{XREFsavepath,,savepath}, @ref{XREFpathsep,,pathsep}}
@end deftypefn
@c savepath scripts/path/savepath.m
@anchor{XREFsavepath}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {} savepath
@deftypefnx {} {} savepath @var{file}
@deftypefnx {} {@var{status} =} savepath (@dots{})
Save the unique portion of the current function search path to @var{file}.
The list of folders that are saved in @var{file} does @emph{not} include
the folders that are added for Octave's own functions, those that belong to
Octave packages (see @ref{XREFpkg,,pkg load}), and those added via command
line switches.
If @var{file} is omitted, Octave looks in the current directory for a
project-specific @file{.octaverc} file in which to save the path
information. If no such file is present then the user's configuration file
@file{~/.octaverc} is used.
If successful, @code{savepath} returns 0.
The @code{savepath} function makes it simple to customize a user's
configuration file to restore the working paths necessary for a particular
instance of Octave. Assuming no filename is specified, Octave will
automatically restore the saved directory paths from the appropriate
@file{.octaverc} file when starting up. If a filename has been specified
then the paths may be restored manually by calling @code{source @var{file}}.
@xseealso{@ref{XREFpath,,path}, @ref{XREFaddpath,,addpath}, @ref{XREFrmpath,,rmpath}, @ref{XREFgenpath,,genpath}, @ref{XREFpathdef,,pathdef}}
@end deftypefn
@c path libinterp/corefcn/load-path.cc
@anchor{XREFpath}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {} path ()
@deftypefnx {} {@var{str} =} path ()
@deftypefnx {} {@var{str} =} path (@var{path1}, @dots{})
Modify or display Octave's load path.
If @var{nargin} and @var{nargout} are zero, display the elements of
Octave's load path in an easy to read format.
If @var{nargin} is zero and nargout is greater than zero, return the
current load path.
If @var{nargin} is greater than zero, concatenate the arguments,
separating them with @code{pathsep}. Set the internal search path
to the result and return it.
No checks are made for duplicate elements.
@xseealso{@ref{XREFaddpath,,addpath}, @ref{XREFrmpath,,rmpath}, @ref{XREFgenpath,,genpath}, @ref{XREFpathdef,,pathdef}, @ref{XREFsavepath,,savepath}, @ref{XREFpathsep,,pathsep}}
@end deftypefn
@c pathdef scripts/path/pathdef.m
@anchor{XREFpathdef}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {@var{val} =} pathdef ()
Return the default path for Octave.
The path information is extracted from one of four sources.
The possible sources, in order of preference, are:
@enumerate
@item @file{.octaverc}
@item @file{~/.octaverc}
@item @file{<OCTAVE_HOME>/@dots{}/<version>/m/startup/octaverc}
@item Octave's path prior to changes by any octaverc file.
@end enumerate
@xseealso{@ref{XREFpath,,path}, @ref{XREFaddpath,,addpath}, @ref{XREFrmpath,,rmpath}, @ref{XREFgenpath,,genpath}, @ref{XREFsavepath,,savepath}}
@end deftypefn
@c pathsep libinterp/corefcn/dirfns.cc
@anchor{XREFpathsep}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {@var{val} =} pathsep ()
Query the character used to separate directories in a path.
@xseealso{@ref{XREFfilesep,,filesep}}
@end deftypefn
@c rehash libinterp/corefcn/load-path.cc
@anchor{XREFrehash}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {} rehash ()
Reinitialize Octave's load path directory cache.
@end deftypefn
@c file_in_loadpath libinterp/corefcn/utils.cc
@anchor{XREFfile_in_loadpath}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {@var{fname} =} file_in_loadpath (@var{file})
@deftypefnx {} {@var{fname} =} file_in_loadpath (@var{file}, "all")
Return the absolute name of @var{file} if it can be found in the list of
directories specified by @code{path}.
If no file is found, return an empty character string.
When @var{file} is already an absolute name, the name is checked against the
file system instead of Octave's loadpath. In this case, if @var{file} exists
it will be returned in @var{fname}, otherwise an empty string is returned.
If the first argument is a cell array of strings, search each directory of
the loadpath for element of the cell array and return the first that
matches.
If the second optional argument @qcode{"all"} is supplied, return a cell
array containing the list of all files that have the same name in the path.
If no files are found, return an empty cell array.
@xseealso{@ref{XREFfile_in_path,,file_in_path}, @ref{XREFdir_in_loadpath,,dir_in_loadpath}, @ref{XREFpath,,path}}
@end deftypefn
@c restoredefaultpath libinterp/corefcn/load-path.cc
@anchor{XREFrestoredefaultpath}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {@var{pathstr} =} restoredefaultpath ()
Restore Octave's path to its initial state at startup.
The re-initialized path is returned as an output.
@xseealso{@ref{XREFpath,,path}, @ref{XREFaddpath,,addpath}, @ref{XREFrmpath,,rmpath}, @ref{XREFgenpath,,genpath}, @ref{XREFpathdef,,pathdef}, @ref{XREFsavepath,,savepath}, @ref{XREFpathsep,,pathsep}}
@end deftypefn
@c command_line_path libinterp/corefcn/load-path.cc
@anchor{XREFcommand_line_path}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {@var{pathstr} =} command_line_path ()
Return the path argument given to Octave at the command line when the
interpreter was started (@w{@env{--path @var{arg}}}).
@xseealso{@ref{XREFpath,,path}, @ref{XREFaddpath,,addpath}, @ref{XREFrmpath,,rmpath}, @ref{XREFgenpath,,genpath}, @ref{XREFpathdef,,pathdef}, @ref{XREFsavepath,,savepath}, @ref{XREFpathsep,,pathsep}}
@end deftypefn
@c dir_in_loadpath libinterp/corefcn/utils.cc
@anchor{XREFdir_in_loadpath}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {@var{dirname} =} dir_in_loadpath (@var{dir})
@deftypefnx {} {@var{dirname} =} dir_in_loadpath (@var{dir}, "all")
Return the absolute name of the loadpath element matching @var{dir} if it can
be found in the list of directories specified by @code{path}.
If no match is found, return an empty character string.
The match is performed at the end of each path element. For example, if
@var{dir} is @qcode{"foo/bar"}, it matches the path element
@nospell{@qcode{"/some/dir/foo/bar"}}, but not
@nospell{@qcode{"/some/dir/foo/bar/baz"}}
@nospell{@qcode{"/some/dir/allfoo/bar"}}. When @var{dir} is an absolute name,
rather than just a path fragment, it is matched against the file system
instead of Octave's loadpath. In this case, if @var{dir} exists it will be
returned in @var{dirname}, otherwise an empty string is returned.
If the optional second argument is supplied, return a cell array containing
all name matches rather than just the first.
@xseealso{@ref{XREFfile_in_path,,file_in_path}, @ref{XREFfile_in_loadpath,,file_in_loadpath}, @ref{XREFpath,,path}}
@end deftypefn
@c mfile_encoding libinterp/corefcn/input.cc
@anchor{XREFmfile_encoding}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {@var{current_encoding} =} mfile_encoding ()
@deftypefnx {} {} mfile_encoding (@var{new_encoding})
@deftypefnx {} {@var{old_encoding} =} mfile_encoding (@var{new_encoding})
Query or set the encoding that is used for reading m-files.
The input and output are strings naming an encoding, e.g.,
@nospell{@qcode{"utf-8"}}.
This encoding is used by Octave's parser when reading m-files unless a
different encoding was set for a specific directory containing m-files using
the function @code{dir_encoding} or in a file @file{.oct-config} in that
directory.
The special value @qcode{"system"} selects the encoding that matches the system
locale.
If the m-file encoding is changed after the m-files have already been parsed,
the files have to be parsed again for that change to take effect. That can be
triggered with the command @code{clear all}.
Additionally, this encoding is used to load and save files with the built-in
editor in Octave's GUI.
@xseealso{@ref{XREFdir_encoding,,dir_encoding}}
@end deftypefn
@c dir_encoding libinterp/corefcn/input.cc
@anchor{XREFdir_encoding}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {@var{current_encoding} =} dir_encoding (@var{dir})
@deftypefnx {} {} dir_encoding (@var{dir}, @var{new_encoding})
@deftypefnx {} {} dir_encoding (@var{dir}, "delete")
@deftypefnx {} {@var{old_encoding} =} dir_encoding (@var{dir}, @var{new_encoding})
Query or set the @var{encoding} that is used for reading m-files in @var{dir}.
The per-directory encoding overrides the (globally set) m-file encoding,
@pxref{XREFmfile_encoding,,@code{mfile_encoding}}.
The string @var{DIR} must match how the directory would appear in the load
path.
The @var{new_encoding} input must be a valid encoding identifier or
@qcode{"delete"}. In the latter case, any per-directory encoding is removed
and the (globally set) m-file encoding will be used for the given @var{dir}.
The currently or previously used encoding is returned only if an output
argument is requested.
The directory encoding is automatically read from the file @file{.oct-config}
when a new path is added to the load path (for example with @code{addpath}).
To set the encoding for all files in the same folder, that file must contain
a line starting with @qcode{"encoding="} followed by the encoding identifier.
For example to set the file encoding for all files in the same folder to
ISO 8859-1 (Latin-1), create a file @file{.oct-config} with the following
content:
@example
encoding=iso8859-1
@end example
If the file encoding is changed after the files have already been parsed, the
files have to be parsed again for that change to take effect. That can be done
with the command @code{clear all}.
@xseealso{@ref{XREFaddpath,,addpath}, @ref{XREFpath,,path}, @ref{XREFmfile_encoding,,mfile_encoding}}
@end deftypefn
@node Subfunctions
@subsection Subfunctions
A function file may contain secondary functions called
@dfn{subfunctions}. These secondary functions are only visible to the
other functions in the same function file. For example, a file
@file{f.m} containing
@example
@group
function f ()
printf ("in f, calling g\n");
g ()
endfunction
function g ()
printf ("in g, calling h\n");
h ()
endfunction
function h ()
printf ("in h\n")
endfunction
@end group
@end example
@noindent
defines a main function @code{f} and two subfunctions. The
subfunctions @code{g} and @code{h} may only be called from the main
function @code{f} or from the other subfunctions, but not from outside
the file @file{f.m}.
@c localfunctions libinterp/corefcn/help.cc
@anchor{XREFlocalfunctions}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {@var{subfcn_list} =} localfunctions ()
Return a list of all local functions, i.e., subfunctions, within the current
file.
The return value is a column cell array of function handles to all local
functions accessible from the function from which @code{localfunctions} is
called. Nested functions are @emph{not} included in the list.
If the call is from the command line, an anonymous function, or a script,
the return value is an empty cell array.
@xseealso{@ref{XREFfunctions,,functions}}
@end deftypefn
@node Private Functions
@subsection Private Functions
In many cases one function needs to access one or more helper
functions. If the helper function is limited to the scope of a single
function, then subfunctions as discussed above might be used. However,
if a single helper function is used by more than one function, then
this is no longer possible. In this case the helper functions might
be placed in a subdirectory, called "private", of the directory in which
the functions needing access to this helper function are found.
As a simple example, consider a function @code{func1}, that calls a helper
function @code{func2} to do much of the work. For example:
@example
@group
function y = func1 (x)
y = func2 (x);
endfunction
@end group
@end example
@noindent
Then if the path to @code{func1} is @code{<directory>/func1.m}, and if
@code{func2} is found in the directory @code{<directory>/private/func2.m},
then @code{func2} is only available for use of the functions, like
@code{func1}, that are found in @code{<directory>}.
@node Nested Functions
@subsection Nested Functions
Nested functions are similar to subfunctions in that only the main function is
visible outside the file. However, they also allow for child functions to
access the local variables in their parent function. This shared access mimics
using a global variable to share information --- but a global variable which is
not visible to the rest of Octave. As a programming strategy, sharing data
this way can create code which is difficult to maintain. It is recommended to
use subfunctions in place of nested functions when possible.
As a simple example, consider a parent function @code{foo}, that calls a nested
child function @code{bar}, with a shared variable @var{x}.
@example
@group
function y = foo ()
x = 10;
bar ();
y = x;
function bar ()
x = 20;
endfunction
endfunction
foo ()
@result{} 20
@end group
@end example
@noindent
Notice that there is no special syntax for sharing @var{x}. This can lead to
problems with accidental variable sharing between a parent function and its
child. While normally variables are inherited, child function parameters and
return values are local to the child function.
Now consider the function @code{foobar} that uses variables @var{x} and
@var{y}. @code{foobar} calls a nested function @code{foo} which takes
@var{x} as a parameter and returns @var{y}. @code{foo} then calls @code{bat}
which does some computation.
@example
@group
function z = foobar ()
x = 0;
y = 0;
z = foo (5);
z += x + y;
function y = foo (x)
y = x + bat ();
function z = bat ()
z = x;
endfunction
endfunction
endfunction
foobar ()
@result{} 10
@end group
@end example
@noindent
It is important to note that the @var{x} and @var{y} in @code{foobar} remain
zero, as in @code{foo} they are a return value and parameter respectively. The
@var{x} in @code{bat} refers to the @var{x} in @code{foo}.
Variable inheritance leads to a problem for @code{eval} and scripts. If a
new variable is created in a parent function, it is not clear what should
happen in nested child functions. For example, consider a parent function
@code{foo} with a nested child function @code{bar}:
@example
@group
function y = foo (to_eval)
bar ();
eval (to_eval);
function bar ()
eval ("x = 100;");
eval ("y = x;");
endfunction
endfunction
foo ("x = 5;")
@result{} error: can not add variable "x" to a static workspace
foo ("y = 10;")
@result{} 10
foo ("")
@result{} 100
@end group
@end example
@noindent
The parent function @code{foo} is unable to create a new variable
@var{x}, but the child function @code{bar} was successful. Furthermore, even
in an @code{eval} statement @var{y} in @code{bar} is the same @var{y} as in its
parent function @code{foo}. The use of @code{eval} in conjunction with nested
functions is best avoided.
As with subfunctions, only the first nested function in a file may be called
from the outside. Inside a function the rules are more complicated. In
general a nested function may call:
@enumerate 0
@item
Globally visible functions
@item
Any function that the nested function's parent can call
@item
Sibling functions (functions that have the same parents)
@item
Direct children
@end enumerate
As a complex example consider a parent function @code{ex_top} with two
child functions, @code{ex_a} and @code{ex_b}. In addition, @code{ex_a} has two
more child functions, @code{ex_aa} and @code{ex_ab}. For example:
@example
function ex_top ()
## Can call: ex_top, ex_a, and ex_b
## Can NOT call: ex_aa and ex_ab
function ex_a ()
## Can call everything
function ex_aa ()
## Can call everything
endfunction
function ex_ab ()
## Can call everything
endfunction
endfunction
function ex_b ()
## Can call: ex_top, ex_a, and ex_b
## Can NOT call: ex_aa and ex_ab
endfunction
endfunction
@end example
@node Overloading and Autoloading
@subsection Overloading and Autoloading
Functions can be overloaded to work with different input arguments. For
example, the operator '+' has been overloaded in Octave to work with single,
double, uint8, int32, and many other arguments. The preferred way to overload
functions is through classes and object oriented programming
(@pxref{Function Overloading}). Occasionally, however, one needs to undo
user overloading and call the default function associated with a specific
type. The @code{builtin} function exists for this purpose.
@c builtin libinterp/parse-tree/oct-parse.yy
@anchor{XREFbuiltin}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {[@dots{}] =} builtin (@var{f}, @dots{})
Call the base function @var{f} even if @var{f} is overloaded to another
function for the given type signature.
This is normally useful when doing object-oriented programming and there is
a requirement to call one of Octave's base functions rather than the
overloaded one of a new class.
A trivial example which redefines the @code{sin} function to be the
@code{cos} function shows how @code{builtin} works.
@example
@group
sin (0)
@result{} 0
function y = sin (x), y = cos (x); endfunction
sin (0)
@result{} 1
builtin ("sin", 0)
@result{} 0
@end group
@end example
@end deftypefn
A single dynamically linked file might define several
functions. However, as Octave searches for functions based on the
functions filename, Octave needs a manner in which to find each of the
functions in the dynamically linked file. On operating systems that
support symbolic links, it is possible to create a symbolic link to the
original file for each of the functions which it contains.
However, there is at least one well known operating system that doesn't
support symbolic links. Making copies of the original file for each of
the functions is undesirable as it increases the
amount of disk space used by Octave. Instead Octave supplies the
@code{autoload} function, that permits the user to define in which
file a certain function will be found.
@c autoload libinterp/parse-tree/oct-parse.yy
@anchor{XREFautoload}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {@var{autoload_map} =} autoload ()
@deftypefnx {} {} autoload (@var{function}, @var{file})
@deftypefnx {} {} autoload (@dots{}, "remove")
Define @var{function} to autoload from @var{file}.
The second argument, @var{file}, should be an absolute filename or a file
name in the same directory as the function or script from which the autoload
command was run. @var{file} @emph{should not} depend on the Octave load
path.
Normally, calls to @code{autoload} appear in PKG_ADD script files that are
evaluated when a directory is added to Octave's load path. To avoid having
to hardcode directory names in @var{file}, if @var{file} is in the same
directory as the PKG_ADD script then
@example
autoload ("foo", "bar.oct");
@end example
@noindent
will load the function @code{foo} from the file @code{bar.oct}. The above
usage when @code{bar.oct} is not in the same directory, or usages such as
@example
autoload ("foo", file_in_loadpath ("bar.oct"))
@end example
@noindent
are strongly discouraged, as their behavior may be unpredictable.
With no arguments, return a structure containing the current autoload map.
If a third argument @qcode{"remove"} is given, the function is cleared and
not loaded anymore during the current Octave session.
@xseealso{@ref{XREFPKG_ADD,,PKG_ADD}}
@end deftypefn
@node Function Locking
@subsection Function Locking
It is sometime desirable to lock a function into memory with the @code{mlock}
function. This is typically used for dynamically linked functions in
oct-files or mex-files that contain some initialization, and it is desirable
that calling @code{clear} does not remove this initialization.
As an example,
@example
@group
function my_function ()
mlock ();
@dots{}
endfunction
@end group
@end example
@noindent
prevents @code{my_function} from being removed from memory after it is called,
even if @code{clear} is called. It is possible to determine if a function is
locked into memory with the @code{mislocked}, and to unlock a function with
@code{munlock}, which the following code illustrates.
@example
@group
my_function ();
mislocked ("my_function")
@result{} ans = 1
munlock ("my_function");
mislocked ("my_function")
@result{} ans = 0
@end group
@end example
A common use of @code{mlock} is to prevent persistent variables from being
removed from memory, as the following example shows:
@example
@group
function count_calls ()
mlock ();
persistent calls = 0;
printf ("count_calls() has been called %d times\n", ++calls);
endfunction
count_calls ();
@print{} count_calls() has been called 1 times
clear count_calls
count_calls ();
@print{} count_calls() has been called 2 times
@end group
@end example
@code{mlock} might also be used to prevent changes to an m-file, such as in an
external editor, from having any effect in the current Octave session; A
similar effect can be had with the @code{ignore_function_time_stamp} function.
@c mlock libinterp/corefcn/variables.cc
@anchor{XREFmlock}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {} mlock ()
Lock the current function into memory so that it can't be removed with
@code{clear}.
@xseealso{@ref{XREFmunlock,,munlock}, @ref{XREFmislocked,,mislocked}, @ref{XREFpersistent,,persistent}, @ref{XREFclear,,clear}}
@end deftypefn
@c munlock libinterp/corefcn/variables.cc
@anchor{XREFmunlock}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {} munlock ()
@deftypefnx {} {} munlock (@var{fcn})
Unlock the named function @var{fcn} so that it may be removed from memory with
@code{clear}.
If no function is named then unlock the current function.
@xseealso{@ref{XREFmlock,,mlock}, @ref{XREFmislocked,,mislocked}, @ref{XREFpersistent,,persistent}, @ref{XREFclear,,clear}}
@end deftypefn
@c mislocked libinterp/corefcn/variables.cc
@anchor{XREFmislocked}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {@var{tf} =} mislocked ()
@deftypefnx {} {@var{tf} =} mislocked (@var{fcn})
Return true if the named function @var{fcn} is locked in memory.
If no function is named then return true if the current function is locked.
@xseealso{@ref{XREFmlock,,mlock}, @ref{XREFmunlock,,munlock}, @ref{XREFpersistent,,persistent}, @ref{XREFclear,,clear}}
@end deftypefn
@node Function Precedence
@subsection Function Precedence
Given the numerous different ways that Octave can define a function, it
is possible and even likely that multiple versions of a function, might be
defined within a particular scope. The precedence of which function will be
used within a particular scope is given by
@enumerate 1
@item Subfunction
A subfunction with the required function name in the given scope.
@item Private function
A function defined within a private directory of the directory
which contains the current function.
@item Class constructor
A function that constructs a user class as defined in chapter
@ref{Object Oriented Programming}.
@item Class method
An overloaded function of a class as in chapter
@ref{Object Oriented Programming}.
@item Command-line Function
A function that has been defined on the command-line.
@item Autoload function
A function that is marked as autoloaded with @xref{XREFautoload,,autoload}.
@item A Function on the Path
A function that can be found on the users load-path. There can also be
Oct-file, mex-file or m-file versions of this function and the precedence
between these versions are in that order.
@item Built-in function
A function that is a part of core Octave such as @code{numel}, @code{size},
etc.
@end enumerate
@node Script Files
@section Script Files
A script file is a file containing (almost) any sequence of Octave
commands. It is read and evaluated just as if you had typed each
command at the Octave prompt, and provides a convenient way to perform a
sequence of commands that do not logically belong inside a function.
Unlike a function file, a script file must @emph{not} begin with the
keyword @code{function}. If it does, Octave will assume that it is a
function file, and that it defines a single function that should be
evaluated as soon as it is defined.
A script file also differs from a function file in that the variables
named in a script file are not local variables, but are in the same
scope as the other variables that are visible on the command line.
Even though a script file may not begin with the @code{function}
keyword, it is possible to define more than one function in a single
script file and load (but not execute) all of them at once. To do
this, the first token in the file (ignoring comments and other white
space) must be something other than @code{function}. If you have no
other statements to evaluate, you can use a statement that has no
effect, like this:
@example
@group
# Prevent Octave from thinking that this
# is a function file:
1;
# Define function one:
function one ()
@dots{}
@end group
@end example
To have Octave read and compile these functions into an internal form,
you need to make sure that the file is in Octave's load path
(accessible through the @code{path} function), then simply type the
base name of the file that contains the commands. (Octave uses the
same rules to search for script files as it does to search for
function files.)
If the first token in a file (ignoring comments) is @code{function},
Octave will compile the function and try to execute it, printing a
message warning about any non-whitespace characters that appear after
the function definition.
Note that Octave does not try to look up the definition of any identifier
until it needs to evaluate it. This means that Octave will compile the
following statements if they appear in a script file, or are typed at
the command line,
@example
@group
# not a function file:
1;
function foo ()
do_something ();
endfunction
function do_something ()
do_something_else ();
endfunction
@end group
@end example
@noindent
even though the function @code{do_something} is not defined before it is
referenced in the function @code{foo}. This is not an error because
Octave does not need to resolve all symbols that are referenced by a
function until the function is actually evaluated.
Since Octave doesn't look for definitions until they are needed, the
following code will always print @samp{bar = 3} whether it is typed
directly on the command line, read from a script file, or is part of a
function body, even if there is a function or script file called
@file{bar.m} in Octave's path.
@example
@group
eval ("bar = 3");
bar
@end group
@end example
Code like this appearing within a function body could fool Octave if
definitions were resolved as the function was being compiled. It would
be virtually impossible to make Octave clever enough to evaluate this
code in a consistent fashion. The parser would have to be able to
perform the call to @code{eval} at compile time, and that would be
impossible unless all the references in the string to be evaluated could
also be resolved, and requiring that would be too restrictive (the
string might come from user input, or depend on things that are not
known until the function is evaluated).
Although Octave normally executes commands from script files that have
the name @file{@var{file}.m}, you can use the function @code{source} to
execute commands from any file.
@c source libinterp/parse-tree/oct-parse.yy
@anchor{XREFsource}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {} source (@var{file})
@deftypefnx {} {} source (@var{file}, @var{context})
Parse and execute the contents of @var{file}.
Without specifying @var{context}, this is equivalent to executing commands
from a script file, but without requiring the file to be named
@file{@var{file}.m} or to be on the execution path.
Instead of the current context, the script may be executed in either the
context of the function that called the present function
(@qcode{"caller"}), or the top-level context (@qcode{"base"}).
@xseealso{@ref{XREFrun,,run}}
@end deftypefn
@menu
* Publish Octave Script Files::
* Publishing Markup::
* Jupyter Notebooks::
@end menu
@node Publish Octave Script Files
@subsection Publish Octave Script Files
The function @code{publish} provides a dynamic possibility to document your
script file. Unlike static documentation, @code{publish} runs the script
file, saves any figures and output while running the script, and presents them
alongside static documentation in a desired output format. The static
documentation can make use of @ref{Publishing Markup} to enhance and
customize the output.
@c publish scripts/miscellaneous/publish.m
@anchor{XREFpublish}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {} publish (@var{file})
@deftypefnx {} {} publish (@var{file}, @var{output_format})
@deftypefnx {} {} publish (@var{file}, @var{option1}, @var{value1}, @dots{})
@deftypefnx {} {} publish (@var{file}, @var{options})
@deftypefnx {} {@var{output_file} =} publish (@var{file}, @dots{})
Generate a report from the Octave script file @var{file} in one of several
output formats.
The generated reports interpret Publishing Markup in section comments, which
is explained in detail in the GNU Octave manual. Section comments are
comment blocks that start with a line with double comment character.
Assume the following example, using some Publishing Markup, to be the
contents of the script file @file{pub_example.m}:
@example
@group
## Headline title
#
# Some *bold*, _italic_, or |monospaced| Text with
# a <https://www.octave.org link to *GNU Octave*>.
##
# "Real" Octave commands to be evaluated
sombrero ()
%% @sc{matlab} comment style ('%') is supported as well
%
% * Bulleted list item 1
% * Bulleted list item 2
%
% # Numbered list item 1
% # Numbered list item 2
@end group
@end example
To publish this script file, type @code{publish ("pub_example.m")}.
When called with one input argument, a HTML report is generated in a
subdirectory @file{html} relative to the current working directory. Any
Octave commands in @file{pub_example.m} are evaluated in a separate context
and any figures created while executing the script file are included in the
report.
Using @code{publish (@var{file}, @var{output_format})} is equivalent to the
function call using a structure
@example
@group
@var{options}.format = @var{output_format};
publish (@var{file}, @var{options})
@end group
@end example
@noindent
which is described below. The same holds for using option/value pairs
@example
@group
@var{options}.@var{option1} = @var{value1};
publish (@var{file}, @var{options})
@end group
@end example
The structure @var{options} can have the following field names. If a field
name is not specified, the default value is used:
@itemize @bullet
@item
@samp{format} --- Output format of the published script file, one of
@samp{html} (default), @samp{doc}, @samp{latex}, @samp{ppt},
@samp{pdf}, or @samp{xml}.
The output formats @samp{doc}, @samp{ppt}, and @samp{xml} are not currently
supported. To generate a @samp{doc} report, open a generated @samp{html}
report with your office suite.
In Octave custom formats are supported by implementing all callback
subfunctions in a function file named
@samp{__publish_<custom format>_output__.m}. To obtain a template for the
HTML format type:
@example
@group
edit (fullfile (fileparts (which ("publish")), ...
"private", "__publish_html_output__.m"))
@end group
@end example
@item
@samp{outputDir} --- Full path of the directory where the generated report
will be located. If no directory is given, the report is generated in a
subdirectory @file{html} relative to the current working directory.
@item
@samp{stylesheet} --- Not supported, only for @sc{matlab} compatibility.
@item
@samp{createThumbnail} --- Not supported, only for @sc{matlab}
compatibility.
@item
@samp{figureSnapMethod} --- Not supported, only for @sc{matlab}
compatibility.
@item
@samp{imageFormat} --- Desired format for any images produced while
evaluating the code. The allowed image formats depend on the output format:
@itemize @bullet
@item @samp{html}, @samp{xml} --- @samp{png} (default), any image format
supported by Octave
@item @samp{latex} --- @samp{epsc2} (default), any image format supported by
Octave
@item @samp{pdf} --- @samp{jpg} (default) or @samp{bmp}, note @sc{matlab}
uses @samp{bmp} as default
@item @samp{doc} or @samp{ppt} --- @samp{png} (default), @samp{jpg},
@samp{bmp}, or @samp{tiff}
@end itemize
@item
@samp{maxWidth} and @samp{maxHeight} --- Maximum width (height) of the
produced images in pixels. An empty value means no restriction. Both
values must be set in order for the option to work properly.
@samp{[]} (default), integer value @geq{} 0
@item
@samp{useNewFigure} --- Use a new figure window for figures created by the
evaluated code. This avoids side effects with already opened figure
windows.
@samp{true} (default) or @samp{false}
@item
@samp{evalCode} --- Evaluate code of the Octave source file
@samp{true} (default) or @samp{false}
@item
@samp{catchError} --- Catch errors while evaluating code and continue
@samp{true} (default) or @samp{false}
@item
@samp{codeToEvaluate} --- Octave commands that should be evaluated prior to
publishing the script file. These Octave commands do not appear in the
generated report.
@item
@samp{maxOutputLines} --- Maximum number of output lines from code
evaluation which are included in output.
@samp{Inf} (default) or integer value > 0
@item
@samp{showCode} --- Show the evaluated Octave commands in the generated
report
@samp{true} (default) or @samp{false}
@end itemize
The option output @var{output_file} is a string with path and file name
of the generated report.
@xseealso{@ref{XREFgrabcode,,grabcode}}
@end deftypefn
The counterpart to @code{publish} is @code{grabcode}:
@c grabcode scripts/miscellaneous/grabcode.m
@anchor{XREFgrabcode}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {} grabcode @var{filename}
@deftypefnx {} {} grabcode @var{url}
@deftypefnx {} {@var{code_str} =} grabcode (@dots{})
Grab the code from a report created by the @code{publish} function.
The grabbed code inside the published report must be enclosed by the
strings @samp{##### SOURCE BEGIN #####} and @samp{##### SOURCE END #####}.
The @code{publish} function creates this format automatically.
If no return value is requested the code is saved to a temporary file and
opened in the default editor. NOTE: The temporary file must be saved to a
new filename or the code will be lost.
If an output is requested the grabbed code will be returned as string
@var{code_str}.
Example:
@example
@group
publish ("my_script.m");
grabcode ("html/my_script.html");
@end group
@end example
The example above publishes @file{my_script.m} to the default location
@file{html/my_script.html}. Next, the published Octave script is grabbed to
edit its content in a new temporary file.
@xseealso{@ref{XREFpublish,,publish}}
@end deftypefn
@node Publishing Markup
@subsection Publishing Markup
@menu
* Using Publishing Markup in Script Files::
* Text Formatting::
* Sections::
* Preformatted Code::
* Preformatted Text::
* Bulleted Lists::
* Numbered Lists::
* Including File Content::
* Including Graphics::
* Including URLs::
* Mathematical Equations::
* HTML Markup::
* LaTeX Markup::
@end menu
@node Using Publishing Markup in Script Files
@subsubsection Using Publishing Markup in Script Files
To use Publishing Markup, start by typing @samp{##} or @samp{%%} at the
beginning of a new line. For @sc{matlab} compatibility @samp{%%%} is treated
the same way as @samp{%%}.
The lines following @samp{##} or @samp{%%} start with one of either
@samp{#} or @samp{%} followed by at least one space. These lines are
interpreted as section. A section ends at the first line not starting
with @samp{#} or @samp{%}, or when the end of the document is reached.
A section starting in the first line of the document, followed by another
start of a section that might be empty, is interpreted as a document
title and introduction text.
See the example below for clarity:
@example
@group
%% Headline title
%
% Some *bold*, _italic_, or |monospaced| Text with
% a <https://www.octave.org link to GNU Octave>.
%%
# "Real" Octave commands to be evaluated
sombrero ()
## Octave comment style supported as well
#
# * Bulleted list item 1
# * Bulleted list item 2
#
# # Numbered list item 1
# # Numbered list item 2
@end group
@end example
@node Text Formatting
@subsubsection Text Formatting
Basic text formatting is supported inside sections, see the example
given below:
@example
@group
##
# @b{*bold*}, @i{_italic_}, or |monospaced| Text
@end group
@end example
Additionally two trademark symbols are supported, just embrace the letters
@samp{TM} or @samp{R}.
@example
@group
##
# (TM) or (R)
@end group
@end example
@node Sections
@subsubsection Sections
A section is started by typing @samp{##} or @samp{%%} at the beginning of
a new line. A section title can be provided by writing it, separated by a
space, in the first line after @samp{##} or @samp{%%}. Without a section
title, the section is interpreted as a continuation of the previous section.
For @sc{matlab} compatibility @samp{%%%} is treated the same way as @samp{%%}.
@example
@group
some_code ();
## Section 1
#
## Section 2
some_code ();
##
# Still in section 2
some_code ();
%%% Section 3
%
%
@end group
@end example
@node Preformatted Code
@subsubsection Preformatted Code
To write preformatted code inside a section, indent the code by three
spaces after @samp{#} at the beginning of each line and leave the lines
above and below the code blank, except for @samp{#} at the beginning of
those lines.
@example
@group
##
# This is a syntax highlighted for-loop:
#
# for i = 1:5
# disp (i);
# endfor
#
# And more usual text.
@end group
@end example
@node Preformatted Text
@subsubsection Preformatted Text
To write preformatted text inside a section, indent the code by two spaces
after @samp{#} at the beginning of each line and leave the lines above and
below the preformatted text blank, except for @samp{#} at the beginning of
those lines.
@example
@group
##
# This following text is preformatted:
#
# "To be, or not to be: that is the question:
# Whether 'tis nobler in the mind to suffer
# The slings and arrows of outrageous fortune,
# Or to take arms against a sea of troubles,
# And by opposing end them? To die: to sleep;"
#
# --"Hamlet" by W. Shakespeare
@end group
@end example
@node Bulleted Lists
@subsubsection Bulleted Lists
To create a bulleted list, type
@example
@group
##
#
# * Bulleted list item 1
# * Bulleted list item 2
#
@end group
@end example
@noindent
to get output like
@itemize @bullet
@item Bulleted list item 1
@item Bulleted list item 2
@end itemize
Notice the blank lines, except for the @samp{#} or @samp{%} before and
after the bulleted list!
@node Numbered Lists
@subsubsection Numbered Lists
To create a numbered list, type
@example
@group
##
#
# # Numbered list item 1
# # Numbered list item 2
#
@end group
@end example
@noindent
to get output like
@enumerate
@item Numbered list item 1
@item Numbered list item 2
@end enumerate
Notice the blank lines, except for the @samp{#} or @samp{%} before and
after the numbered list!
@node Including File Content
@subsubsection Including File Content
To include the content of an external file, e.g., a file called
@samp{my_function.m} at the same location as the published Octave script,
use the following syntax to include it with Octave syntax highlighting.
Alternatively, you can write the full or relative path to the file.
@example
@group
##
#
# <include>my_function.m</include>
#
# <include>/full/path/to/my_function.m</include>
#
# <include>../relative/path/to/my_function.m</include>
#
@end group
@end example
@node Including Graphics
@subsubsection Including Graphics
To include external graphics, e.g., a graphic called @samp{my_graphic.png}
at the same location as the published Octave script, use the following syntax.
Alternatively, you can write the full path to the graphic.
@example
@group
##
#
# <<my_graphic.png>>
#
# <</full/path/to/my_graphic.png>>
#
# <<../relative/path/to/my_graphic.png>>
#
@end group
@end example
@node Including URLs
@subsubsection Including URLs
Basically, a URL is written between an opening @samp{<} and a closing @samp{>}
angle.
@example
@group
##
# <https://www.octave.org>
@end group
@end example
Text that is within these angles and separated by at least one space from the
URL is a displayed text for the link.
@example
@group
##
# <https://www.octave.org GNU Octave>
@end group
@end example
A link starting with @samp{<octave:} followed by the name of a GNU Octave
function, optionally with a displayed text, results in a link to the online
GNU Octave documentations function index.
@example
@group
##
# <octave:DISP The display function>
@end group
@end example
@node Mathematical Equations
@subsubsection Mathematical Equations
One can insert @LaTeX{} inline math, surrounded by single @samp{$} signs, or
displayed math, surrounded by double @samp{$$} signs, directly inside
sections.
@example
@group
##
# Some shorter inline equation $e^@{ix@} = \cos x + i\sin x$.
#
# Or more complicated formulas as displayed math:
# $$e^x = \lim_@{n\rightarrow\infty@}\left(1+\dfrac@{x@}@{n@}\right)^@{n@}.$$
@end group
@end example
@node HTML Markup
@subsubsection HTML Markup
If the published output is a HTML report, you can insert HTML markup,
that is only visible in this kind of output.
@example
@group
##
# <html>
# <table style="border:1px solid black;">
# <tr><td>1</td><td>2</td></tr>
# <tr><td>3</td><td>3</td></tr>
# </html>
@end group
@end example
@node LaTeX Markup
@subsubsection LaTeX Markup
If the published output is a @LaTeX{} or PDF report, you can insert @LaTeX{}
markup, that is only visible in this kind of output.
@example
@group
##
# <latex>
# Some output only visible in @nospell{LaTeX} or PDF reports.
# \begin@{equation@}
# e^x = \lim\limits_@{n\rightarrow\infty@}\left(1+\dfrac@{x@}@{n@}\right)^@{n@}
# \end@{equation@}
# </latex>
@end group
@end example
@node Jupyter Notebooks
@subsection Jupyter Notebooks
@cindex Jupyter Notebooks
Jupyter notebooks are one popular technique for displaying code, text, and
graphical output together in a comprehensive manner. Octave can publish
results to a Jupyter notebook with the function @code{jupyter_notebook}.
@c jupyter_notebook scripts/miscellaneous/jupyter_notebook.m
@anchor{XREFjupyter_notebook}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {@var{notebook} =} jupyter_notebook (@var{notebook_filename})
@deftypefnx {} {@var{notebook} =} jupyter_notebook (@var{notebook_filename}, @var{options})
Run and fill the Jupyter Notebook in file @var{notebook_filename} from
within GNU Octave.
Both text and graphical Octave outputs are supported.
This class has a public property @code{notebook} which is a structure
representing the JSON-decoded Jupyter Notebook. This property is
intentionally public to enable advanced notebook manipulations.
Note: Jupyter Notebook versions (@code{nbformat}) lower than 4.0 are not
supported.
The optional second argument @var{options} is a struct with fields:
@itemize @bullet
@item
@code{tmpdir} to set the temporary working directory.
@end itemize
@code{%plot} magic is supported with the following settings:
@itemize @bullet
@item
"@code{%plot -f <format>}" or "@code{%plot --format <format>}": specifies
the image storage format. Supported formats are:
@itemize @minus
@item
PNG (default)
@item SVG
(Note: If SVG images do not appear in the notebook, it is most likely
related to Jupyter Notebook security mechanisms and explicitly "trusting"
them will be necessary).
@item
JPG
@end itemize
@item
"@code{%plot -r <number>}" or "@code{%plot --resolution <number>}":
specifies the image resolution.
@item
"@code{%plot -w <number>}" or "@code{%plot --width <number>}":
specifies the image width.
@item
"@code{%plot -h <number>}" or "@code{%plot --height <number>}":
specifies the image height.
@end itemize
Examples:
@example
@group
## Run all cells and generate the filled notebook
## Instantiate an object from a notebook file
notebook = jupyter_notebook ("myNotebook.ipynb");
## Run the code and embed the results in the @code{notebook} property
notebook.run_all ();
## Generate a new notebook by overwriting the original notebook
notebook.generate_notebook ("myNotebook.ipynb");
@end group
@group
## Run just the second cell and generate the filled notebook
## Instantiate an object from a notebook file
notebook = jupyter_notebook ("myNotebook.ipynb");
## Run the code and embed the results in the @code{notebook} property
notebook.run (2)
## Generate a new notebook in a new file
notebook.generate_notebook ("myNewNotebook.ipynb");
@end group
@group
## Generate an Octave script from a notebook
## Instantiate an object from a notebook file
notebook = jupyter_notebook ("myNotebook.ipynb");
## Generate the Octave script
notebook.generate_octave_script ("jup_script.m");
@end group
@end example
@xseealso{@ref{XREFjsondecode,,jsondecode}, @ref{XREFjsonencode,,jsonencode}}
@end deftypefn
@node Function Handles and Anonymous Functions
@section Function Handles and Anonymous Functions
@cindex handle, function handles
@cindex anonymous functions
It can be very convenient store a function in a variable so that it
can be passed to a different function. For example, a function that
performs numerical minimization needs access to the function that
should be minimized.
@menu
* Function Handles::
* Anonymous Functions::
@end menu
@node Function Handles
@subsection Function Handles
A function handle is a pointer to another function and is defined with
the syntax
@example
@@@var{function-name}
@end example
@noindent
For example,
@example
f = @@sin;
@end example
@noindent
creates a function handle called @code{f} that refers to the
function @code{sin}.
Function handles are used to call other functions indirectly, or to pass
a function as an argument to another function like @code{quad} or
@code{fsolve}. For example:
@example
@group
f = @@sin;
quad (f, 0, pi)
@result{} 2
@end group
@end example
You may use @code{feval} to call a function using function handle, or
simply write the name of the function handle followed by an argument
list. If there are no arguments, you must use an empty argument list
@samp{()}. For example:
@example
@group
f = @@sin;
feval (f, pi/4)
@result{} 0.70711
f (pi/4)
@result{} 0.70711
@end group
@end example
@c is_function_handle libinterp/octave-value/ov-fcn-handle.cc
@anchor{XREFis_function_handle}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {@var{tf} =} is_function_handle (@var{x})
Return true if @var{x} is a function handle.
@xseealso{@ref{XREFisa,,isa}, @ref{XREFtypeinfo,,typeinfo}, @ref{XREFclass,,class}, @ref{XREFfunctions,,functions}}
@end deftypefn
@c functions libinterp/octave-value/ov-fcn-handle.cc
@anchor{XREFfunctions}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {@var{s} =} functions (@var{fcn_handle})
Return a structure containing information about the function handle
@var{fcn_handle}.
The structure @var{s} always contains these three fields:
@table @asis
@item function
The function name. For an anonymous function (no name) this will be the
actual function definition.
@item type
Type of the function.
@table @asis
@item anonymous
The function is anonymous.
@item private
The function is private.
@item overloaded
The function overloads an existing function.
@item simple
The function is a built-in or m-file function.
@item subfunction
The function is a subfunction within an m-file.
@end table
@item nested
The function is nested.
@item file
The m-file that will be called to perform the function. This field is empty
for anonymous and built-in functions.
@end table
In addition, some function types may return more information in additional
fields.
@strong{Warning:} @code{functions} is provided for debugging purposes only.
Its behavior may change in the future and programs should not depend on any
particular output format.
@xseealso{@ref{XREFfunc2str,,func2str}, @ref{XREFstr2func,,str2func}}
@end deftypefn
@c func2str libinterp/octave-value/ov-fcn-handle.cc
@anchor{XREFfunc2str}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {@var{str} =} func2str (@var{fcn_handle})
Return a string containing the name of the function referenced by the function
handle @var{fcn_handle}.
@xseealso{@ref{XREFstr2func,,str2func}, @ref{XREFfunctions,,functions}}
@end deftypefn
@c str2func libinterp/octave-value/ov-fcn-handle.cc
@anchor{XREFstr2func}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {@var{hfcn} =} str2func (@var{str})
Return a function handle constructed from the string @var{str}.
The input may be the name of a function such as @qcode{"sin"} or a string
defining a function such as @qcode{"@@(x) sin (x + pi)"}.
Programming Note: In most cases it will be better to use anonymous function
syntax and let the Octave parser create the function handle rather than use
@code{str2func}. For example:
@example
@group
hfcn = @@sin ;
hfcn = @@(x) sin (x + pi) ;
@end group
@end example
@xseealso{@ref{XREFfunc2str,,func2str}, @ref{XREFfunctions,,functions}}
@end deftypefn
@c symvar scripts/miscellaneous/symvar.m
@anchor{XREFsymvar}
@html
<span style="display:block; margin-top:-4.5ex;"> </span>
@end html
@deftypefn {} {@var{vars} =} symvar (@var{str})
Identify the symbolic variable names in the string @var{str}.
Common constant names such as @code{i}, @code{j}, @code{pi}, @code{Inf} and
Octave functions such as @code{sin} or @code{plot} are ignored.
Any names identified are returned in a cell array of strings. The array is
empty if no variables were found.
Example:
@example
@group
symvar ("x^2 + y^2 == 4")
@result{} @{
[1,1] = x
[2,1] = y
@}
@end group
@end example
@end deftypefn
@node Anonymous Functions
@subsection Anonymous Functions
Anonymous functions are defined using the syntax
@example
@@(@var{argument-list}) @var{expression}
@end example
@noindent
Any variables that are not found in the argument list are inherited from
the enclosing scope. Anonymous functions are useful for creating simple
unnamed functions from expressions or for wrapping calls to other
functions to adapt them for use by functions like @code{quad}. For
example,
@example
@group
f = @@(x) x.^2;
quad (f, 0, 10)
@result{} 333.33
@end group
@end example
@noindent
creates a simple unnamed function from the expression @code{x.^2} and
passes it to @code{quad},
@example
@group
quad (@@(x) sin (x), 0, pi)
@result{} 2
@end group
@end example
@noindent
wraps another function, and
@example
@group
a = 1;
b = 2;
quad (@@(x) betainc (x, a, b), 0, 0.4)
@result{} 0.13867
@end group
@end example
@noindent
adapts a function with several parameters to the form required by
@code{quad}. In this example, the values of @var{a} and @var{b} that
are passed to @code{betainc} are inherited from the current
environment.
Note that for performance reasons it is better to use handles to existing
Octave functions, rather than to define anonymous functions which wrap an
existing function. The integration of @code{sin (x)} is 5X faster if the code
is written as
@example
quad (@@sin, 0, pi)
@end example
@noindent
rather than using the anonymous function @code{@@(x) sin (x)}. There are many
operators which have functional equivalents that may be better choices than an
anonymous function. Instead of writing
@example
f = @@(x, y) x + y
@end example
@noindent
this should be coded as
@example
f = @@plus
@end example
@xref{Operator Overloading}, for a list of operators which also have a
functional form.
@node Command Syntax and Function Syntax
@section Command Syntax and Function Syntax
@cindex commands functions
In addition to the function syntax described above (i.e., calling a function
like @code{fun (arg1, arg2, @dots{})}), a function can be called using command
syntax (for example, calling a function like @code{fun arg1 arg2 @dots{}}). In
that case, all arguments are passed to the function as strings. For example,
@example
my_command hello world
@end example
@noindent
is equivalent to
@example
my_command ("hello", "world")
@end example
@noindent
The general form of a command call is
@example
cmdname arg1 arg2 @dots{}
@end example
@noindent
which translates directly to
@example
cmdname ("arg1", "arg2", @dots{})
@end example
If an argument including spaces should be passed to a function in command
syntax, (double-)quotes can be used. For example,
@example
my_command "first argument" "second argument"
@end example
@noindent
is equivalent to
@example
my_command ("first argument", "second argument")
@end example
Any function can be used as a command if it accepts string input arguments.
For example:
@example
@group
upper lower_case_arg
@result{} ans = LOWER_CASE_ARG
@end group
@end example
Since the arguments are passed as strings to the corresponding function, it is
not possible to pass input arguments that are stored in variables. In that
case, a command must be called using the function syntax. For example:
@example
@group
strvar = "hello world";
upper strvar
@result{} ans = STRVAR
upper (strvar)
@result{} ans = HELLO WORLD
@end group
@end example
Additionally, the return values of functions cannot be assigned to variables
using the command syntax. Only the first return argument is assigned to the
built-in variable @code{ans}. If the output argument of a command should be
assigned to a variable, or multiple output arguments of a function should be
returned, the function syntax must be used.
It should be noted that mixing command syntax and binary operators can
create apparent ambiguities with mathematical and logical expressions that
use function syntax. For example, all three of the statements
@example
@group
arg1 - arg2
arg1 -arg2
arg1-arg2
@end group
@end example
@noindent
could be intended by a user to be subtraction operations between
@code{arg1} and @code{arg2}. The first two, however, could also have been
meant as a command syntax call to function @code{arg1}, in the first case
with options @code{-} and @code{arg2}, and in the second case with option
@option{-arg2}.
Octave uses whitespace to interpret such expressions according to the
following rules:
@itemize @bullet
@item
Statements consisting of plain symbols without any operators that are
separated only by whitespace are always treated as command syntax:
@example
arg1 arg2 arg3 ... argn
@end example
@item
Statements without any whitespace are always treated as function syntax:
@example
@group
arg1+arg2
arg1&&arg2||arg3
arg1+=arg2*arg3
@end group
@end example
@item
If the first symbol is a constant (or special-valued named constant pi, i,
I, j, J, e, NaN, or Inf) followed by a binary operator, the statement is
treated as function syntax regardless of any whitespace or what follows the
second symbol:
@example
@group
7 -arg2
pi+ arg2
j * arg2 -arg3
@end group
@end example
@item
If the first symbol is a function or variable and there is no whitespace
separating the operator and the second symbol, the statement is treated
as command syntax:
@example
@group
arg1 -arg2
arg1 &&arg2 ||arg3
arg1 +=arg2*arg3
@end group
@end example
@item
Any other whitespace combination will result in the statement being treated
as function syntax.
@end itemize
Note 1: If a special-valued named constant has been redefined as a
variable, the interpreter will still process the statement with function
syntax.
Note 2: Attempting to use a variable as @code{arg1} in a command being
processed as command syntax will result in an error.
@node Organization of Functions
@section Organization of Functions Distributed with Octave
Many of Octave's standard functions are distributed as function files.
They are loosely organized by topic, in subdirectories of
@file{@var{octave-home}/share/octave/@var{version}/m}, to make it easier
to find them.
The following is a list of all the function file subdirectories, and the
types of functions you will find there.
@table @file
@item @@ftp
Class functions for the FTP object.
@item +containers
Package for the containers classes.
@item audio
Functions for playing and recording sounds.
@item deprecated
Out-of-date functions which will eventually be removed from Octave.
@item elfun
Elementary functions, principally trigonometric.
@item general
Miscellaneous matrix manipulations, like @code{flipud}, @code{rot90},
and @code{triu}, as well as other basic functions, like
@code{ismatrix}, @code{narginchk}, etc.
@item geometry
Functions related to Delaunay triangulation.
@item gui
Functions for GUI elements like dialog, message box, etc.
@item help
Functions for Octave's built-in help system.
@item image
Image processing tools. These functions require the X Window System.
@item io
Input-output functions.
@item java
Functions related to the Java integration.
@item linear-algebra
Functions for linear algebra.
@item miscellaneous
Functions that don't really belong anywhere else.
@item ode
Functions to solve ordinary differential equations (ODEs).
@item optimization
Functions related to minimization, optimization, and root finding.
@item path
Functions to manage the directory path Octave uses to find functions.
@item pkg
Package manager for installing external packages of functions in Octave.
@item plot
Functions for displaying and printing two- and three-dimensional graphs.
@item polynomial
Functions for manipulating polynomials.
@item prefs
Functions implementing user-defined preferences.
@item set
Functions for creating and manipulating sets of unique values.
@item signal
Functions for signal processing applications.
@item sparse
Functions for handling sparse matrices.
@item specfun
Special functions such as @code{bessel} or @code{factor}.
@item special-matrix
Functions that create special matrix forms such as Hilbert or
@nospell{Vandermonde} matrices.
@item startup
Octave's system-wide startup file.
@item statistics
Statistical functions.
@item strings
Miscellaneous string-handling functions.
@item testfun
Functions for performing unit tests on other functions.
@item time
Functions related to time and date processing.
@end table
|