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
|
@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 Expressions
@chapter Expressions
@cindex expressions
Expressions are the basic building block of statements in Octave. An
expression evaluates to a value, which you can print, test, store in a
variable, pass to a function, or assign a new value to a variable with
an assignment operator.
An expression can serve as a statement on its own. Most other kinds of
statements contain one or more expressions which specify data to be
operated on. As in other languages, expressions in Octave include
variables, array references, constants, and function calls, as well as
combinations of these with various operators.
@menu
* Index Expressions::
* Calling Functions::
* Arithmetic Ops::
* Comparison Ops::
* Boolean Expressions::
* Assignment Ops::
* Increment Ops::
* Operator Precedence::
@end menu
@node Index Expressions
@section Index Expressions
@opindex (
@opindex )
@opindex :
An @dfn{index expression} allows you to reference or extract selected
elements of a vector, a matrix (2-D), or a higher-dimensional array. Arrays
may be indexed in one of three ways:
@ref{XREFComponentIndexing,,Component Indexing},
@ref{XREFLinearIndexing,,Linear Indexing}, and
@ref{XREFLogicalIndexing,,Logical Indexing}.
@anchor{XREFComponentIndexing}
@subheading Component Indexing
@cindex Component Indexing
Component indices may be scalars, vectors, ranges, or the special operator
@samp{:}, which selects entire rows, columns, or higher-dimensional slices.
Component index expression consists of a set of parentheses enclosing @math{M}
expressions separated by commas. Each individual index value, or component,
is used for the respective dimension of the object that it is applied to. In
other words, the first index component is used for the first dimension (rows)
of the object, the second index component is used for the second dimension
(columns) of the object, and so on. The number of index components @math{M}
defines the dimensionality of the index expression. An index with two
components would be referred to as a 2-D index because it has two dimensions.
In the simplest case, 1) all components are scalars, and 2) the dimensionality
of the index expression @math{M} is equal to the dimensionality of the object
it is applied to. For example:
@example
@group
A = reshape (1:8, 2, 2, 2) # Create 3-D array
A =
ans(:,:,1) =
1 3
2 4
ans(:,:,2) =
5 7
6 8
A(2, 1, 2) # second row, first column of second slice
# in third dimension: ans = 6
@end group
@end example
The size of the returned object in a specific dimension is equal to the number
of elements in the corresponding component of the index expression. When all
components are scalars, the result is a single output value. However, if any
component is a vector or range then the returned values are the Cartesian
product of the indices in the respective dimensions. For example:
@example
@group
A([1, 2], 1, 2) @equiv{} [A(1,1,2); A(2,1,2)]
@result{}
ans =
5
6
@end group
@end example
The total number of returned values is the product of the number of elements
returned for each index component. In the example above, the total is 2*1*1 =
2 elements.
Notice that the size of the returned object in a given dimension is equal to
the number of elements in the index expression for that dimension. In the code
above, the first index component (@code{[1, 2]}) was specified as a row vector,
but its shape is unimportant. The important fact is that the component
specified two values, and hence the result must have a size of two in the first
dimension; and because the first dimension corresponds to rows, the overall
result is a column vector.
@example
@group
A(1, [2, 1, 1], 1) # result is a row vector: ans = [3, 1, 1]
A(ones (2, 2), 1, 1) # result is a column vector: ans = [1; 1; 1; 1]
@end group
@end example
The first line demonstrates again that the size of the output in a given
dimension is equal to the number of elements in the respective indexing
component. In this case, the output has three elements in the second dimension
(which corresponds to columns), so the result is a row vector. The example
also shows how repeating entries in the index expression can be used to
replicate elements in the output. The last example further proves that the
shape of the indexing component is irrelevant, it is only the number of
elements (2x2 = 4) which is important.
The above rules apply whenever the dimensionality of the index expression
is greater than one (@math{M > 1}). However, for one-dimensional index
expressions special rules apply and the shape of the output @strong{is}
determined by the shape of the indexing component. For example:
@example
@group
A([1, 2]) # result is a row vector: ans = [1, 2]
A([1; 2]) # result is a column vector: ans = [1; 2]
@end group
@end example
The shape rules for @var{A}(@var{P}) are:
@itemize @bullet
@item When at least one of @var{A} or @var{P} has two or more dimensions, then
@var{A}(@var{P}) takes the shape of @var{P}. This happens when at least one
of the variables is a 2-D matrix or an N-D array.
@item When both @var{A} and @var{P} are 1-D vectors, then @var{A}(@var{P}) takes
the shape of @var{A} itself. In particular, when @var{A} is a row vector, then
@var{A}(@var{P}) is also a row vector irrespective of @var{P}'s shape. The
case when @var{A} is a column vector is analogous.
@end itemize
@opindex :, indexing expressions
A colon (@samp{:}) may be used as an index component to select all of the
elements in a specified dimension. Given the matrix,
@example
A = [1, 2; 3, 4]
@end example
@noindent
all of the following expressions are equivalent and select the first row of the
matrix.
@example
@group
A(1, [1, 2]) # row 1, columns 1 and 2
A(1, 1:2) # row 1, columns in range 1-2
A(1, :) # row 1, all columns
@end group
@end example
When a colon is used in the special case of 1-D indexing the result is always a
column vector. Creating column vectors with a colon index is a very frequently
encountered code idiom and is faster and generally clearer than calling
@code{reshape} for this case.
@example
@group
A(:) # result is column vector: ans = [1; 2; 3; 4]
A(:)' # result is row vector: ans = [1, 2, 3, 4]
@end group
@end example
@cindex @code{end}, indexing
@cindex @sortas{end:} @code{end:} and @code{:end}
In index expressions the keyword @code{end} automatically refers to the last
entry for a particular dimension. This magic index can also be used in ranges
and typically eliminates the needs to call @code{size} or @code{length} to
gather array bounds before indexing. For example:
@example
@group
A(1:end/2) # first half of A => [1, 2]
A(end + 1) = 5; # append element
A(end) = []; # delete element
A(1:2:end) # odd elements of A => [1, 3]
A(2:2:end) # even elements of A => [2, 4]
A(end:-1:1) # reversal of A => [4, 3, 2, 1]
@end group
@end example
For more information see the @ref{XREFend, , @qcode{"end" keyword}}.
@anchor{XREFLinearIndexing}
@subheading Linear Indexing
@cindex Linear Indexing
It is permissible to use a 1-D index with a multi-dimensional object. This is
also called @dfn{linear indexing}. In this case, the elements of the
multi-dimensional array are taken in column-first order like in Fortran. That
is, the columns of the array are imagined to be stacked on top of each other
to form a column vector and then the single linear index is applied to this
vector.
@example
@group
A = [1, 2, 3; 4, 5, 6; 7, 8, 9];
A(4) # linear index of 4th element in 2-D array: ans = 2
A(3:5) # result has shape of index component: ans = [7, 2, 5]
A([1, 2, 2, 1]) # result includes repeated elements: ans = [1, 4, 4, 1]
@end group
@end example
@anchor{XREFLogicalIndexing}
@subheading Logical Indexing
@cindex Logical Indexing
Logical values can also be used to index matrices and cell arrays.
When indexing with a logical array the result will be a vector containing
the values corresponding to @code{true} parts of the logical array. The
following examples illustrates this.
@example
@group
data = [ 1, 2; 3, 4 ];
idx = [true, false; false true];
data(idx)
@result{} ans = [ 1; 4 ]
idx = (data <= 2);
data(idx)
@result{} ans = [ 1; 2 ]
@end group
@end example
@noindent
Instead of creating the @code{idx} array it is possible to replace
@code{data(idx)} with @w{@code{data( data <= 2 )}}@ in the above code.
While the size of the logical index expressions is usually the same as that
of the array being indexed, this is not a necessary condition. If the logical
index is a different size than the array, then elements from the array are
matched against elements from the logical index based on their linear order,
just as with linear indexing.
@example
@group
data = [ 1, 2, 3; 4, 5, 6 ];
idx = [ true, false, false, true ];
data(idx)
@result{} ans = [ 1 5 ] # idx selected the 1st and 4th position elements
@end group
@end example
If the logical index is larger than then array an out of bounds error will
occur if any true values attempt to select a linear position larger than the
number of elements in the array.
@example
@group
idx = [ true, true, false; false, true, false; true; false; false ];
data(idx)
@result{} ans = [ 1; 2; 5; 3 ] # returns positions 1, 3, 4, 5 in a column
idx = [ true, true, false; false, true, false; true; false; true ];
data(idx)
@result{} error: a(9): out of bound 6 (dimensions are 2x3)
@end group
@end example
False elements of a logical index outside the array size are ignored, but when
the ninth element of the logical index is true it triggers an error as it tries
to select a nonexistent 9th element of the array.
@menu
* Advanced Indexing::
@end menu
@node Advanced Indexing
@subsection Advanced Indexing
@subsubheading Chained indexing
@cindex Chained indexing
Octave permits the use of repeated (chained) index expressions to extract
subsets of an array in a single command without the need to use intermediate
variables. This can make it easier to write code with either complicated
indexing operations or using multiple indexing methods. The following example
shows two equivalent index extraction operations:
@example
@group
A = reshape (1:16, 4, 4);
B = A(2:4, 2:3);
C = B(3:5);
D = C( [ true, false, true ] )
@result{} D = [ 8, 11 ]
D = A(2:4, 2:3)(3:5)([ true, false, true ])
@result{} D = [ 8, 11 ]
@end group
@end example
Chained indexing will necessarily be slower than a single index expression
producing the same results, but is usually more computationally efficient
than performing multiple discrete indexing operations with intermediate
variable assignments.
Note that chained indexing is only compatible with right-hand expressions and
can not be used on the left-hand side of assignment operations.
@subsubheading Component to linear index conversion
When it is necessary to extract subsets of entries out of an array whose
indices cannot be written as a Cartesian product of components, linear
indexing together with the function @code{sub2ind} can be used. For example:
@example
@group
A = reshape (1:8, 2, 2, 2) # Create 3-D array
A =
ans(:,:,1) =
1 3
2 4
ans(:,:,2) =
5 7
6 8
A(sub2ind (size (A), [1, 2, 1], [1, 1, 2], [1, 2, 1]))
@result{} ans = [A(1, 1, 1), A(2, 1, 2), A(1, 2, 1)]
@end group
@end example
@DOCSTRING(sub2ind)
@DOCSTRING(ind2sub)
@DOCSTRING(isindex)
@subsubheading Component count not equal to dimensionality
An array with @samp{nd} dimensions can be indexed by an index expression which
has from 1 to @samp{nd} components. For the ordinary and most common case, the
number of components @samp{M} matches the number of dimensions @samp{nd}. In
this case the ordinary indexing rules apply and each component corresponds to
the respective dimension of the array.
However, if the number of indexing components exceeds the number of dimensions
(@w{@code{M > nd}}) then the excess components must all be singletons
(@code{1}). Moreover, if @w{@code{M < nd}}, the behavior is equivalent to
reshaping the input object so as to merge the trailing
@w{@code{nd - M}}@ dimensions into the last index dimension @code{M}. Thus,
the result will have the dimensionality of the index expression, and not the
original object. This is the case whenever dimensionality of the index is
greater than one (@w{@code{M > 1}}), so that the special rules for linear
indexing are not applied. This is easiest to understand with an example:
@smallexample
A = reshape (1:8, 2, 2, 2) # Create 3-D array
A =
ans(:,:,1) =
1 3
2 4
ans(:,:,2) =
5 7
6 8
## 2-D indexing causes third dimension to be merged into second dimension.
## Equivalent array for indexing, Atmp, is now 2x4.
Atmp = reshape (A, 2, 4)
Atmp =
1 3 5 7
2 4 6 8
A(2,1) # Reshape to 2x4 matrix, second entry of first column: ans = 2
A(2,4) # Reshape to 2x4 matrix, second entry of fourth column: ans = 8
A(:,:) # Reshape to 2x4 matrix, select all rows & columns, ans = Atmp
@end smallexample
@noindent
Note here the elegant use of the double colon to replace the call to the
@code{reshape} function.
@subsubheading Array replication
Another advanced use of linear indexing is to create arrays filled with a
single value. This can be done by using an index of ones on a scalar value.
The result is an object with the dimensions of the index expression and every
element equal to the original scalar. For example, the following statements
@example
@group
a = 13;
a(ones (1, 4))
@end group
@end example
@noindent
produce a row vector whose four elements are all equal to 13.
Similarly, by indexing a scalar with two vectors of ones it is possible to
create a matrix. The following statements
@example
@group
a = 13;
a(ones (1, 2), ones (1, 3))
@end group
@end example
@noindent
create a 2x3 matrix with all elements equal to 13. This could also have been
written as
@example
13(ones (2, 3))
@end example
It is more efficient to use indexing rather than the code construction
@code{scalar * ones (M, N, @dots{})} because it avoids the unnecessary
multiplication operation. Moreover, multiplication may not be defined for the
object to be replicated whereas indexing an array is always defined. The
following code shows how to create a 2x3 cell array from a base unit which is
not itself a scalar.
@example
@group
@{"Hello"@}(ones (2, 3))
@end group
@end example
It should be noted that @code{ones (1, n)} (a row vector of ones) results in a
range object (with zero increment). A range is stored internally as a starting
value, increment, end value, and total number of values; hence, it is more
efficient for storage than a vector or matrix of ones whenever the number of
elements is greater than 4. In particular, when @samp{r} is a row vector, the
expressions
@example
r(ones (1, n), :)
@end example
@example
r(ones (n, 1), :)
@end example
@noindent
will produce identical results, but the first one will be significantly faster,
at least for @samp{r} and @samp{n} large enough. In the first case the index
is held in compressed form as a range which allows Octave to choose a more
efficient algorithm to handle the expression.
A general recommendation for users unfamiliar with these techniques is to use
the function @code{repmat} for replicating smaller arrays into bigger ones,
which uses such tricks.
@subsubheading Indexing for performance enhancement
A second use of indexing is to speed up code. Indexing is a fast operation
and judicious use of it can reduce the requirement for looping over individual
array elements, which is a slow operation.
Consider the following example which creates a 10-element row vector
@math{a} containing the values
@tex
$a_i = \sqrt{i}$.
@end tex
@ifnottex
a(i) = sqrt (i).
@end ifnottex
@example
@group
for i = 1:10
a(i) = sqrt (i);
endfor
@end group
@end example
@noindent
It is quite inefficient to create a vector using a loop like this. In this
case, it would have been much more efficient to use the expression
@example
a = sqrt (1:10);
@end example
@noindent
which avoids the loop entirely.
In cases where a loop cannot be avoided, or a number of values must be combined
to form a larger matrix, it is generally faster to set the size of the matrix
first (pre-allocate storage), and then insert elements using indexing commands.
For example, given a matrix @code{a},
@example
@group
[nr, nc] = size (a);
x = zeros (nr, n * nc);
for i = 1:n
x(:,(i-1)*nc+1:i*nc) = a;
endfor
@end group
@end example
@noindent
is considerably faster than
@example
@group
x = a;
for i = 1:n-1
x = [x, a];
endfor
@end group
@end example
@noindent
because Octave does not have to repeatedly resize the intermediate result.
For more performance improvement suggestions see
@ref{Vectorization and Faster Code Execution,,}.
@node Calling Functions
@section Calling Functions
A @dfn{function} is a name for a particular calculation. Because it has
a name, you can ask for it by name at any point in the program. For
example, the function @code{sqrt} computes the square root of a number.
A fixed set of functions are @dfn{built-in}, which means they are
available in every Octave program. The @code{sqrt} function is one of
these. In addition, you can define your own functions.
@xref{Functions and Scripts}, for information about how to do this.
@cindex arguments in function call
The way to use a function is with a @dfn{function call} expression,
which consists of the function name followed by a list of
@dfn{arguments} in parentheses. The arguments are expressions which give
the raw materials for the calculation that the function will do. When
there is more than one argument, they are separated by commas. If there
are no arguments, you can omit the parentheses, but it is a good idea to
include them anyway, to clearly indicate that a function call was
intended. Here are some examples:
@example
@group
sqrt (x^2 + y^2) # @r{One argument}
ones (n, m) # @r{Two arguments}
rand () # @r{No arguments}
@end group
@end example
Each function expects a particular number of arguments. For example, the
@code{sqrt} function must be called with a single argument, the number
to take the square root of:
@example
sqrt (@var{argument})
@end example
Some of the built-in functions take a variable number of arguments,
depending on the particular usage, and their behavior is different
depending on the number of arguments supplied.
Like every other expression, the function call has a value, which is
computed by the function based on the arguments you give it. In this
example, the value of @code{sqrt (@var{argument})} is the square root of
the argument. A function can also have side effects, such as assigning
the values of certain variables or doing input or output operations.
Unlike most languages, functions in Octave may return multiple values.
For example, the following statement
@example
[u, s, v] = svd (a)
@end example
@noindent
computes the singular value decomposition of the matrix @code{a} and
assigns the three result matrices to @code{u}, @code{s}, and @code{v}.
The left side of a multiple assignment expression is itself a list of
expressions, that is, a list of variable names potentially qualified by
index expressions. See also @ref{Index Expressions}, and @ref{Assignment Ops}.
@menu
* Call by Value::
* Recursion::
* Access via Handle::
@end menu
@node Call by Value
@subsection Call by Value
In Octave, unlike Fortran, function arguments are passed by value, which
means that each argument in a function call is evaluated and assigned to
a temporary location in memory before being passed to the function.
There is currently no way to specify that a function parameter should be
passed by reference instead of by value. This means that it is
impossible to directly alter the value of a function parameter in the
calling function. It can only change the local copy within the function
body. For example, the function
@example
@group
function f (x, n)
while (n-- > 0)
disp (x);
endwhile
endfunction
@end group
@end example
@noindent
displays the value of the first argument @var{n} times. In this
function, the variable @var{n} is used as a temporary variable without
having to worry that its value might also change in the calling
function. Call by value is also useful because it is always possible to
pass constants for any function parameter without first having to
determine that the function will not attempt to modify the parameter.
The caller may use a variable as the expression for the argument, but
the called function does not know this: it only knows what value the
argument had. For example, given a function called as
@example
@group
foo = "bar";
fcn (foo)
@end group
@end example
@noindent
you should not think of the argument as being ``the variable
@code{foo}.'' Instead, think of the argument as the string value,
@qcode{"bar"}.
Even though Octave uses pass-by-value semantics for function arguments,
values are not copied unnecessarily. For example,
@example
@group
x = rand (1000);
f (x);
@end group
@end example
@noindent
does not actually force two 1000 by 1000 element matrices to exist
@emph{unless} the function @code{f} modifies the value of its
argument. Then Octave must create a copy to avoid changing the
value outside the scope of the function @code{f}, or attempting (and
probably failing!) to modify the value of a constant or the value of a
temporary result.
@node Recursion
@subsection Recursion
@cindex factorial function
With some restrictions@footnote{Some of Octave's functions are
implemented in terms of functions that cannot be called recursively.
For example, the ODE solver @code{lsode} is ultimately implemented in a
Fortran subroutine that cannot be called recursively, so @code{lsode}
should not be called either directly or indirectly from within the
user-supplied function that @code{lsode} requires. Doing so will result
in an error.}, recursive function calls are allowed. A
@dfn{recursive function} is one which calls itself, either directly or
indirectly. For example, here is an inefficient@footnote{It would be
much better to use @code{prod (1:n)}, or @code{gamma (n+1)} instead,
after first checking to ensure that the value @code{n} is actually a
positive integer.} way to compute the factorial of a given integer:
@example
@group
function retval = fact (n)
if (n > 0)
retval = n * fact (n-1);
else
retval = 1;
endif
endfunction
@end group
@end example
@noindent
This function is recursive because it calls itself directly. It
eventually terminates because each time it calls itself, it uses an
argument that is one less than was used for the previous call. Once the
argument is no longer greater than zero, it does not call itself, and
the recursion ends.
The function @code{max_recursion_depth} may be used to specify a limit
to the recursion depth and prevents Octave from recursing infinitely.
Similarly, the function @code{max_stack_depth} may be used to specify
limit to the depth of function calls, whether recursive or not. These
limits help prevent stack overflow on the computer Octave is running on,
so that instead of exiting with a signal, the interpreter will throw an
error and return to the command prompt.
@DOCSTRING(max_recursion_depth)
@DOCSTRING(max_stack_depth)
@node Access via Handle
@subsection Access via Handle
@cindex function handle
@cindex indirect function call
@opindex @@ function handle
A function may be abstracted and referenced via a function handle acquired
using the special operator @samp{@@}. For example,
@example
@group
f = @@plus;
f (2, 2)
@result{} 4
@end group
@end example
@noindent
is equivalent to calling @code{plus (2, 2)} directly. Beyond abstraction for
general programming, function handles find use in callback methods for figures
and graphics by adding listeners to properties or assigning pre-existing
actions, such as in the following example:
@cindex figure deletefcn
@example
@group
function mydeletefcn (h, ~, msg)
printf (msg);
endfunction
sombrero;
set (gcf, "deletefcn", @{@@mydeletefcn, "Bye!\n"@});
close;
@end group
@end example
@noindent
The above will print @qcode{"Bye!"} to the terminal upon the closing
(deleting) of the figure. There are many graphics property actions for which
a callback function may be assigned, including, @code{buttondownfcn},
@code{windowscrollwheelfcn}, @code{createfcn}, @code{deletefcn},
@code{keypressfcn}, etc.
Note that the @samp{@@} character also plays a role in defining class
functions, i.e., methods, but not as a syntactical element. Rather it begins a
directory name containing methods for a class that shares the directory name
sans the @samp{@@} character. See @ref{Object Oriented Programming}.
@node Arithmetic Ops
@section Arithmetic Operators
@cindex arithmetic operators
@cindex operators, arithmetic
@cindex addition
@cindex subtraction
@cindex multiplication
@cindex matrix multiplication
@cindex division
@cindex quotient
@cindex negation
@cindex unary minus
@cindex exponentiation
@cindex transpose
@cindex Hermitian operator
@cindex transpose, complex-conjugate
@cindex complex-conjugate transpose
The following arithmetic operators are available, and work on scalars
and matrices. The element-by-element operators and functions broadcast
(@pxref{Broadcasting}).
@table @asis
@item @var{x} + @var{y}
@opindex +
Addition (always works element by element). If both operands are
matrices, the number of rows and columns must both agree, or they must
be broadcastable to the same shape.
@item @var{x} - @var{y}
@opindex -
Subtraction (always works element by element). If both operands are
matrices, the number of rows and columns of both must agree, or they
must be broadcastable to the same shape.
@item @var{x} * @var{y}
@opindex *
Matrix multiplication. The number of columns of @var{x} must agree with
the number of rows of @var{y}.
@item @var{x} .* @var{y}
@opindex .*
Element-by-element multiplication. If both operands are matrices, the
number of rows and columns must both agree, or they must be
broadcastable to the same shape.
@item @var{x} / @var{y}
@opindex /
Right division. This is conceptually equivalent to the expression
@example
(inv (y') * x')'
@end example
@noindent
but it is computed without forming the inverse of @var{y'}.
If the system is not square, or if the coefficient matrix is singular,
a minimum norm solution is computed.
@item @var{x} ./ @var{y}
@opindex ./
Element-by-element right division.
@item @var{x} \ @var{y}
@opindex \
Left division. This is conceptually equivalent to the expression
@example
inv (x) * y
@end example
@noindent
but it is computed without forming the inverse of @var{x}.
If the system is not square, or if the coefficient matrix is singular,
a minimum norm solution is computed.
@item @var{x} .\ @var{y}
@opindex .\
Element-by-element left division. Each element of @var{y} is divided
by each corresponding element of @var{x}.
@item @var{x} ^ @var{y}
@opindex ^
Power operator. If @var{x} and @var{y} are both scalars, this operator
returns @var{x} raised to the power @var{y}. If @var{x} is a scalar and
@var{y} is a square matrix, the result is computed using an eigenvalue
expansion. If @var{x} is a square matrix, the result is computed by
repeated multiplication if @var{y} is an integer, and by an eigenvalue
expansion if @var{y} is not an integer. An error results if both
@var{x} and @var{y} are matrices.
The implementation of this operator needs to be improved.
@item @var{x} .^ @var{y}
@opindex .^
Element-by-element power operator. If both operands are matrices, the
number of rows and columns must both agree, or they must be
broadcastable to the same shape. If several complex results are
possible, the one with smallest non-negative argument (angle) is taken.
This rule may return a complex root even when a real root is also possible.
Use @code{realpow}, @code{realsqrt}, @code{cbrt}, or @code{nthroot} if a
real result is preferred.
@item -@var{x}
@opindex -
Negation.
@item +@var{x}
@opindex +
Unary plus. This operator has no effect on the operand.
@item @var{x}'
@opindex @code{'}
Complex conjugate transpose. For real arguments, this operator is the
same as the transpose operator. For complex arguments, this operator is
equivalent to the expression
@example
conj (x.')
@end example
@item @var{x}.'
@opindex @code{.'}
Transpose.
@end table
Note that because Octave's element-by-element operators begin with a
@samp{.}, there is a possible ambiguity for statements like
@example
1./m
@end example
@noindent
because the period could be interpreted either as part of the constant
or as part of the operator. To resolve this conflict, Octave treats the
expression as if you had typed
@example
(1) ./ m
@end example
@noindent
and not
@example
(1.) / m
@end example
@noindent
Although this is inconsistent with the normal behavior of Octave's
lexer, which usually prefers to break the input into tokens by
preferring the longest possible match at any given point, it is more
useful in this case.
Note also that some combinations of binary operators and whitespace can
create apparent ambiguities with the Command Syntax form of calling
functions. See @ref{Command Syntax and Function Syntax} for a description
of how Octave treats that syntax.
@opindex @code{'}
@DOCSTRING(ctranspose)
@DOCSTRING(pagectranspose)
@opindex .\
@DOCSTRING(ldivide)
@opindex -
@DOCSTRING(minus)
@opindex \
@DOCSTRING(mldivide)
@opindex ^
@DOCSTRING(mpower)
@opindex /
@DOCSTRING(mrdivide)
@opindex *
@DOCSTRING(mtimes)
@opindex +
@DOCSTRING(plus)
@opindex .^
@DOCSTRING(power)
@opindex ./
@DOCSTRING(rdivide)
@opindex .*
@DOCSTRING(times)
@opindex @code{.'}
@DOCSTRING(transpose)
@DOCSTRING(pagetranspose)
@opindex -
@DOCSTRING(uminus)
@opindex +
@DOCSTRING(uplus)
@node Comparison Ops
@section Comparison Operators
@cindex comparison expressions
@cindex expressions, comparison
@cindex relational operators
@cindex operators, relational
@cindex less than operator
@cindex greater than operator
@cindex equality operator
@cindex tests for equality
@cindex equality, tests for
@dfn{Comparison operators} compare numeric values for relationships
such as equality. They are written using
@emph{relational operators}.
All of Octave's comparison operators return a value of 1 if the
comparison is true, or 0 if it is false. For matrix values, they all
work on an element-by-element basis. Broadcasting rules apply.
@xref{Broadcasting}. For example:
@example
@group
[1, 2; 3, 4] == [1, 3; 2, 4]
@result{} 1 0
0 1
@end group
@end example
According to broadcasting rules, if one operand is a scalar and the
other is a matrix, the scalar is compared to each element of the matrix
in turn, and the result is the same size as the matrix.
@table @code
@item @var{x} < @var{y}
@opindex <
True if @var{x} is less than @var{y}.
@item @var{x} <= @var{y}
@opindex <=
True if @var{x} is less than or equal to @var{y}.
@item @var{x} == @var{y}
@opindex ==
True if @var{x} is equal to @var{y}.
@item @var{x} >= @var{y}
@opindex >=
True if @var{x} is greater than or equal to @var{y}.
@item @var{x} > @var{y}
@opindex >
True if @var{x} is greater than @var{y}.
@item @var{x} != @var{y}
@itemx @var{x} ~= @var{y}
@opindex !=
@opindex ~=
True if @var{x} is not equal to @var{y}.
@end table
For complex numbers, the following ordering is defined:
@var{z1} < @var{z2}
if and only if
@example
@group
abs (@var{z1}) < abs (@var{z2})
|| (abs (@var{z1}) == abs (@var{z2}) && arg (@var{z1}) < arg (@var{z2}))
@end group
@end example
This is consistent with the ordering used by @dfn{max}, @dfn{min} and
@dfn{sort}, but is not consistent with @sc{matlab}, which only compares the real
parts.
String comparisons may also be performed with the @code{strcmp}
function, not with the comparison operators listed above.
@xref{Strings}.
@opindex ==
@DOCSTRING(eq)
@opindex >=
@DOCSTRING(ge)
@opindex >
@DOCSTRING(gt)
@DOCSTRING(isequal)
@DOCSTRING(isequaln)
@opindex <=
@DOCSTRING(le)
@opindex <
@DOCSTRING(lt)
@opindex !=
@opindex ~=
@DOCSTRING(ne)
@node Boolean Expressions
@section Boolean Expressions
@cindex expressions, boolean
@cindex boolean expressions
@cindex expressions, logical
@cindex logical expressions
@cindex operators, boolean
@cindex boolean operators
@cindex logical operators
@cindex operators, logical
@cindex and operator
@cindex or operator
@cindex not operator
@menu
* Element-by-element Boolean Operators::
* Short-circuit Boolean Operators::
@end menu
@node Element-by-element Boolean Operators
@subsection Element-by-element Boolean Operators
@cindex element-by-element evaluation
An @dfn{element-by-element boolean expression} is a combination of
comparison expressions using the boolean
operators ``or'' (@samp{|}), ``and'' (@samp{&}), and ``not'' (@samp{!}),
along with parentheses to control nesting. The truth of the boolean
expression is computed by combining the truth values of the
corresponding elements of the component expressions. A value is
considered to be false if it is zero, and true otherwise.
Element-by-element boolean expressions can be used wherever comparison
expressions can be used. They can be used in @code{if} and @code{while}
statements. However, a matrix value used as the condition in an
@code{if} or @code{while} statement is only true if @emph{all} of its
elements are nonzero.
Like comparison operations, each element of an element-by-element
boolean expression also has a numeric value (1 if true, 0 if false) that
comes into play if the result of the boolean expression is stored in a
variable, or used in arithmetic.
Here are descriptions of the three element-by-element boolean operators.
@table @code
@item @var{boolean1} & @var{boolean2}
@opindex &
Elements of the result are true if both corresponding elements of
@var{boolean1} and @var{boolean2} are true.
@item @var{boolean1} | @var{boolean2}
@opindex |
Elements of the result are true if either of the corresponding elements
of @var{boolean1} or @var{boolean2} is true.
@item ! @var{boolean}
@itemx ~ @var{boolean}
@opindex ~
@opindex !
Each element of the result is true if the corresponding element of
@var{boolean} is false.
@end table
These operators work on an element-by-element basis. For example, the
expression
@example
[1, 0; 0, 1] & [1, 0; 2, 3]
@end example
@noindent
returns a two by two identity matrix.
For the binary operators, broadcasting rules apply. @xref{Broadcasting}.
In particular, if one of the operands is a scalar and the other a
matrix, the operator is applied to the scalar and each element of the
matrix.
For the binary element-by-element boolean operators, both subexpressions
@var{boolean1} and @var{boolean2} are evaluated before computing the
result. This can make a difference when the expressions have side
effects. For example, in the expression
@example
a & b++
@end example
@noindent
the value of the variable @var{b} is incremented even if the variable
@var{a} is zero.
This behavior is necessary for the boolean operators to work as
described for matrix-valued operands.
@opindex &
@DOCSTRING(and)
@opindex ~
@opindex !
@DOCSTRING(not)
@opindex |
@DOCSTRING(or)
@node Short-circuit Boolean Operators
@subsection Short-circuit Boolean Operators
@cindex short-circuit evaluation
Combined with the implicit conversion to scalar values in @code{if} and
@code{while} conditions, Octave's element-by-element boolean operators
are often sufficient for performing most logical operations. However,
it is sometimes desirable to stop evaluating a boolean expression as
soon as the overall truth value can be determined. Octave's
@dfn{short-circuit} boolean operators work this way.
@table @code
@item @var{boolean1} && @var{boolean2}
@opindex &&
The expression @var{boolean1} is evaluated and converted to a scalar using
the equivalent of the operation @code{all (@var{boolean1}(:))}. If
@var{boolean1} is not a logical value, it is considered true if its value
is nonzero, and false if its value is zero. If @var{boolean1} is an array,
it is considered true only if it is non-empty and all elements are
nonzero. If @var{boolean1} evaluates to false, the result of the overall
expression is false. If it is true, the expression @var{boolean2} is
evaluated in the same way as @var{boolean1}. If it is true, the result of
the overall expression is true. Otherwise the result of the overall
expression is false.
@strong{Warning:} the one exception to the equivalence with evaluating
@code{all (@var{boolean1}(:))} is when @code{boolean1} an the empty array.
For @sc{matlab} compatibility, the truth value of an empty array is always
@code{false} so @code{[] && true} evaluates to @code{false} even though
@code{all ([])} is @code{true}.
@item @var{boolean1} || @var{boolean2}
@opindex ||
The expression @var{boolean1} is evaluated and converted to a scalar using
the equivalent of the operation @code{all (@var{boolean1}(:))}. If
@var{boolean1} is not a logical value, it is considered true if its value
is nonzero, and false if its value is zero. If @var{boolean1} is an array,
it is considered true only if it is non-empty and all elements are
nonzero. If @var{boolean1} evaluates to true, the result of the overall
expression is true. If it is false, the expression @var{boolean2} is
evaluated in the same way as @var{boolean1}. If it is true, the result of
the overall expression is true. Otherwise the result of the overall
expression is false.
@strong{Warning:} the truth value of an empty matrix is always
@code{false}, see the previous list item for details.
@end table
The fact that both operands may not be evaluated before determining the
overall truth value of the expression can be important. For example, in
the expression
@example
a && b++
@end example
@noindent
the value of the variable @var{b} is only incremented if the variable
@var{a} is nonzero.
This can be used to write somewhat more concise code. For example, it
is possible write
@example
@group
function f (a, b, c)
if (nargin > 2 && ischar (c))
@dots{}
@end group
@end example
@noindent
instead of having to use two @code{if} statements to avoid attempting to
evaluate an argument that doesn't exist. For example, without the
short-circuit feature, it would be necessary to write
@example
@group
function f (a, b, c)
if (nargin > 2)
if (ischar (c))
@dots{}
@end group
@end example
@noindent
Writing
@example
@group
function f (a, b, c)
if (nargin > 2 & ischar (c))
@dots{}
@end group
@end example
@noindent
would result in an error if @code{f} were called with one or two
arguments because Octave would be forced to try to evaluate both of the
operands for the operator @samp{&}.
@sc{matlab} has special behavior that allows the operators @samp{&} and
@samp{|} to short-circuit when used in the truth expression for @code{if}
and @code{while} statements. Octave behaves the same way for
compatibility, however, the use of the @samp{&} and @samp{|} operators in
this way is strongly discouraged and a warning will be issued. Instead,
you should use the @samp{&&} and @samp{||} operators that always have
short-circuit behavior.
Finally, the ternary operator (?:) is not supported in Octave. If
short-circuiting is not important, it can be replaced by the @code{ifelse}
function.
@DOCSTRING(merge)
@node Assignment Ops
@section Assignment Expressions
@cindex assignment expressions
@cindex assignment operators
@cindex operators, assignment
@cindex expressions, assignment
@opindex =
An @dfn{assignment} is an expression that stores a new value into a
variable. For example, the following expression assigns the value 1 to
the variable @code{z}:
@example
z = 1
@end example
@noindent
After this expression is executed, the variable @code{z} has the value 1.
Whatever old value @code{z} had before the assignment is forgotten.
The @samp{=} sign is called an @dfn{assignment operator}.
Assignments can store string values also. For example, the following
expression would store the value @qcode{"this food is good"} in the
variable @code{message}:
@example
@group
thing = "food"
predicate = "good"
message = [ "this " , thing , " is " , predicate ]
@result{} "this food is good"
@end group
@end example
@noindent
(This also illustrates concatenation of strings.)
@cindex side effect
Most operators (addition, concatenation, and so on) have no effect
except to compute a value. If you ignore the value, you might as well
not use the operator. An assignment operator is different. It does
produce a value, but even if you ignore the value, the assignment still
makes itself felt through the alteration of the variable. We call this
a @dfn{side effect}.
@cindex lvalue
The left-hand operand of an assignment need not be a variable
(@pxref{Variables}). It can also be an element of a matrix
(@pxref{Index Expressions}) or a list of return values
(@pxref{Calling Functions}). These are all called @dfn{lvalues}, which
means they can appear on the left-hand side of an assignment operator.
The right-hand operand may be any expression. It produces the new value
which the assignment stores in the specified variable, matrix element,
or list of return values.
It is important to note that variables do @emph{not} have permanent types.
The type of a variable is simply the type of whatever value it happens
to hold at the moment. In the following program fragment, the variable
@code{foo} has a numeric value at first, and a string value later on:
@example
@group
>> foo = 1
foo = 1
>> foo = "bar"
foo = bar
@end group
@end example
@noindent
When the second assignment gives @code{foo} a string value, the fact that
it previously had a numeric value is forgotten.
Assignment of a scalar to an indexed matrix sets all of the elements
that are referenced by the indices to the scalar value. For example, if
@code{a} is a matrix with at least two columns,
@example
a(:, 2) = 5
@end example
@noindent
sets all the elements in the second column of @code{a} to 5.
When an assignment sets the value of a vector, matrix, or array element at a
position or dimension outside of that variable's current size, the array size
will be increased to accommodate the new values:
@example
@group
>> a = [1, 2, 3]
a = 1 2 3
>> a(4) = 4
a = 1 2 3 4
>> a(2, :) = [5, 6, 7, 8]
a =
1 2 3 4
5 6 7 8
@end group
@end example
Attempting to increase the size of an array such that the desired output size
is ambiguous will result in an error:
@example
@group
>> a(9) = 10
@print{} error: Invalid resizing operation or ambiguous assignment to an
out-of-bounds array element
@end group
@end example
This is because adding the 9th element creates an ambiguity in the desired
array position for the value 10, each possibility requiring a different array
size expansion to accommodate the assignment.
Assignments may be made with fewer specified elements than would be required to
fill the newly expanded array as long as the assignment is unambiguous. In
these cases the array will be automatically padded with @emph{null} values:
@example
@group
>> a = [1, 2]
a = 1 2
>> a(4) = 5
a = 1 2 0 5
>> a(3, :) = [6, 7, 8, 9]
a =
1 2 0 5
0 0 0 0
6 7 8 9
>> a(4, 5) = 10
a =
1 2 0 5 0
0 0 0 0 0
6 7 8 9 0
0 0 0 0 10
@end group
@end example
For all built-in types, the @emph{null} value will be appropriate to that object
type.
Numeric arrays:
@example
@group
>> a = int32 ([1, 2])
a = 1, 2
>> a(4) = 5
a = 1 2 0 5
@end group
@end example
Logical arrays:
@example
@group
>> a = [true, false, true]
a = 1 0 1
>> d(5) = true
d = 1 0 1 0 1
@end group
@end example
Character arrays:
@example
@group
>> a = "abc"
a = abc
>> a(5) = "d"
a = abcd
>> double (a)
ans = 97 98 99 0 100
@end group
@end example
Cell arrays:
@example
@group
>> e = @{1, "foo", [3, 4]@};
>> e(5) = "bar"
e =
@{
[1,1] = 1
[1,2] = foo
[1,3] =
3 4
[1,4] = [](0x0)
[1,5] = bar
@}
@end group
@end example
Struct arrays:
@example
@group
>> a = struct("foo",1,"bar",2);
>> a(3) = struct("foo",3,"bar",9)
a =
1x3 struct array containing the fields:
foo
bar
>> a.foo
ans = 1
ans = [](0x0)
ans = 3
>> a.bar
ans = 2
ans = [](0x0)
ans = 9
@end group
@end example
Note that Octave currently is unable to concatenate arbitrary object types
into arrays. Such behavior must be explicitly defined within the object class
or attempts at concatenation will result in an error.
@xref{Object Oriented Programming}.
Assigning an empty matrix @samp{[]} works in most cases to allow you to
delete rows or columns of matrices and vectors. @xref{Empty Matrices}.
For example, given a 4 by 5 matrix @var{A}, the assignment
@example
A (3, :) = []
@end example
@noindent
deletes the third row of @var{A}, and the assignment
@example
A (:, 1:2:5) = []
@end example
@noindent
deletes the first, third, and fifth columns.
Deleting part of an array object will necessarily resize the object. When the
deletion allows for consistent size reduction across a dimension, e.g., one
element of a vector, or one row or column of a matrix, the size along that
dimension will be reduced while preserving dimensionality. If, however,
dimensionality cannot be maintained, the object will be reshaped into a vector
following column-wise element ordering:
@example
@group
>> a = [1, 2, 3, 4; 5, 6, 7, 8]
a =
1 2 3 4
5 6 7 8
>> a(:, 3) = []
a =
1 2 4
5 6 8
>> a(4) = []
a = 1 5 2 4 8
@end group
@end example
An assignment is an expression, so it has a value. Thus, @code{z = 1}
as an expression has the value 1. One consequence of this is that you
can write multiple assignments together:
@example
x = y = z = 0
@end example
@noindent
stores the value 0 in all three variables. It does this because the
value of @code{z = 0}, which is 0, is stored into @code{y}, and then
the value of @code{y = z = 0}, which is 0, is stored into @code{x}.
This is also true of assignments to lists of values, so the following is
a valid expression
@example
[a, b, c] = [u, s, v] = svd (a)
@end example
@noindent
that is exactly equivalent to
@example
@group
[u, s, v] = svd (a)
a = u
b = s
c = v
@end group
@end example
In expressions like this, the number of values in each part of the
expression need not match. For example, the expression
@example
[a, b] = [u, s, v] = svd (a)
@end example
@noindent
is equivalent to
@example
@group
[u, s, v] = svd (a)
a = u
b = s
@end group
@end example
@noindent
The number of values on the left side of the expression can, however,
not exceed the number of values on the right side. For example, the
following will produce an error.
@example
@group
[a, b, c, d] = [u, s, v] = svd (a);
@print{} error: element number 4 undefined in return list
@end group
@end example
The symbol @code{~} may be used as a placeholder in the list of lvalues,
indicating that the corresponding return value should be ignored and not stored
anywhere:
@example
@group
[~, s, v] = svd (a);
@end group
@end example
This is cleaner and more memory efficient than using a dummy variable.
The @code{nargout} value for the right-hand side expression is not affected.
If the assignment is used as an expression, the return value is a
comma-separated list with the ignored values dropped.
@opindex +=
A very common programming pattern is to increment an existing variable
with a given value, like this
@example
a = a + 2;
@end example
@noindent
This can be written in a clearer and more condensed form using the
@code{+=} operator
@example
a += 2;
@end example
@noindent
@opindex -=
@opindex *=
@opindex /=
Similar operators also exist for subtraction (@code{-=}),
multiplication (@code{*=}), and division (@code{/=}). An expression
of the form
@example
@var{expr1} @var{op}= @var{expr2}
@end example
@noindent
is evaluated as
@example
@var{expr1} = (@var{expr1}) @var{op} (@var{expr2})
@end example
@noindent
where @var{op} can be either @code{+}, @code{-}, @code{*}, or @code{/},
as long as @var{expr2} is a simple expression with no side effects. If
@var{expr2} also contains an assignment operator, then this expression
is evaluated as
@example
@group
@var{temp} = @var{expr2}
@var{expr1} = (@var{expr1}) @var{op} @var{temp}
@end group
@end example
@noindent
where @var{temp} is a placeholder temporary value storing the computed
result of evaluating @var{expr2}. So, the expression
@example
a *= b+1
@end example
@noindent
is evaluated as
@example
a = a * (b+1)
@end example
@noindent
and @emph{not}
@example
a = a * b + 1
@end example
You can use an assignment anywhere an expression is called for. For
example, it is valid to write @code{x != (y = 1)} to set @code{y} to 1
and then test whether @code{x} equals 1. But this style tends to make
programs hard to read. Except in a one-shot program, you should rewrite
it to get rid of such nesting of assignments. This is never very hard.
@cindex increment operator
@cindex decrement operator
@cindex operators, increment
@cindex operators, decrement
@node Increment Ops
@section Increment Operators
@emph{Increment operators} increase or decrease the value of a variable
by 1. The operator to increment a variable is written as @samp{++}. It
may be used to increment a variable either before or after taking its
value.
For example, to pre-increment the variable @var{x}, you would write
@code{++@var{x}}. This would add one to @var{x} and then return the new
value of @var{x} as the result of the expression. It is exactly the
same as the expression @code{@var{x} = @var{x} + 1}.
To post-increment a variable @var{x}, you would write @code{@var{x}++}.
This adds one to the variable @var{x}, but returns the value that
@var{x} had prior to incrementing it. For example, if @var{x} is equal
to 2, the result of the expression @code{@var{x}++} is 2, and the new
value of @var{x} is 3.
For matrix and vector arguments, the increment and decrement operators
work on each element of the operand.
The increment and decrement operators must "hug" their corresponding
variable. That means, no white spaces are allowed between these
operators and the variable they affect.
Here is a list of all the increment and decrement expressions.
@table @code
@item ++@var{x}
@opindex ++
This expression increments the variable @var{x}. The value of the
expression is the @emph{new} value of @var{x}. It is equivalent to the
expression @code{@var{x} = @var{x} + 1}.
@item --@var{x}
@opindex @code{--}
This expression decrements the variable @var{x}. The value of the
expression is the @emph{new} value of @var{x}. It is equivalent to the
expression @code{@var{x} = @var{x} - 1}.
@item @var{x}++
@opindex ++
This expression causes the variable @var{x} to be incremented. The
value of the expression is the @emph{old} value of @var{x}.
@item @var{x}--
@opindex @code{--}
This expression causes the variable @var{x} to be decremented. The
value of the expression is the @emph{old} value of @var{x}.
@end table
@node Operator Precedence
@section Operator Precedence
@cindex operator precedence
@dfn{Operator precedence} determines how operators are grouped, when
different operators appear close by in one expression. For example,
@samp{*} has higher precedence than @samp{+}. Thus, the expression
@code{a + b * c} means to multiply @code{b} and @code{c}, and then add
@code{a} to the product (i.e., @code{a + (b * c)}).
You can overrule the precedence of the operators by using parentheses.
You can think of the precedence rules as saying where the parentheses
are assumed if you do not write parentheses yourself. In fact, it is
wise to use parentheses whenever you have an unusual combination of
operators, because other people who read the program may not remember
what the precedence is in this case. You might forget as well, and then
you too could make a mistake. Explicit parentheses will help prevent
any such mistake.
When operators of equal precedence are used together, the leftmost
operator groups first, except for the assignment operators, which group
in the opposite order. Thus, the expression @code{a - b + c} groups as
@code{(a - b) + c}, but the expression @code{a = b = c} groups as
@code{a = (b = c)}.
The precedence of prefix unary operators is important when another
operator follows the operand. For example, @code{-x^2} means
@code{-(x^2)}, because @samp{-} has lower precedence than @samp{^}.
Here is a table of the operators in Octave, in order of decreasing
precedence. Unless noted, all operators group left to right.
@table @code
@item function call and array indexing, cell array indexing, and structure element indexing
@samp{()} @samp{@{@}} @samp{.}
@item postfix increment, and postfix decrement
@samp{++} @samp{--}
These operators group right to left.
@item transpose and exponentiation
@samp{'} @samp{.'} @samp{^} @samp{.^}
@item unary plus, unary minus, prefix increment, prefix decrement, and logical "not"
@samp{+} @samp{-} @samp{++} @samp{--} @samp{~} @samp{!}
@item multiply and divide
@samp{*} @samp{/} @samp{\} @samp{.\} @samp{.*} @samp{./}
@item add, subtract
@samp{+} @samp{-}
@item colon
@samp{:}
@item relational
@samp{<} @samp{<=} @samp{==} @samp{>=} @samp{>} @samp{!=} @samp{~=}
@item element-wise "and"
@samp{&}
@item element-wise "or"
@samp{|}
@item logical "and"
@samp{&&}
@item logical "or"
@samp{||}
@item assignment
@samp{=} @samp{+=} @samp{-=} @samp{*=} @samp{/=} @samp{\=}
@samp{^=} @samp{.*=} @samp{./=} @samp{.\=} @samp{.^=} @samp{|=}
@samp{&=}
These operators group right to left.
@end table
|