Scilab Bag Of Tricks: The Scilab-2.5.x IAQ (Infrequently Asked Questions) | ||
---|---|---|
Prev | Chapter 2. Common Pitfalls | Next |
The square bracket operator [ ] is a convenient means to construct vectors. There even exists an idiom to build a matrix with brackets, which is shown in Example 2-1.
Example 2-1. Building a matrix column-by-column and row-by-row
mat = [] for i = 1:n row = [] for j = 1:m ... -- compute matrix entry expr = ... row = [row expr] end mat = [mat; row] end
Rows are separated by semi-colons or newlines, which actually is straight forward. Columns are separated by commas, or spaces—and here comes trouble. First, comma and space serve the same purpose, and are interchangeable. Thus, the following expressions have the same result.
[1 2 3 4] [1,2,3,4] [1 2 3,4] [ 1, 2 3 , 4 ]
Second, a space is sometimes considered a column-separating space, sometimes a intra-expression space. This can lead to some confusion as the following three matrix definitions demonstrate. Who gets all of them right without peeking at the answers?
-->m1 = [1+%i -1+%i; -1+%i 1-%i] m1 = ! 1. + i - 1. + i ! ! - 1. + i 1. - i ! -->m2 = [1 +%i - 1 + %i; - 1 + %i 1 - %i] m2 = ! 1. - 1. + 2.i ! ! - 1. + i 1. - i ! -->m3 = [1 +%i -1 + %i; - 1 + %i 1 -%i] m3 = ! 1. i - 1. + i ! ! - 1. + i 1. - i !
Confusion makes the programmer susceptible to writing code she did not intend. To make the matrix expression clear to you and to Scilab there are at least two possibilities.
Using no spaces in the construction of the elements of a matrix. This is e.g. demonstrated in m1 above, or
Putting every compound expression in parentheses, like
-->[(1 +%i) (-1 + %i); (- 1 + %i) (1 -%i)] ans = ! 1. + i - 1. + i ! ! - 1. + i 1. - i !
Both ways avoid the ambiguity.
Actually, matrices as simple as the ones shown in the examples can be arranged in a neat way. It is discussed in Section 3.1.2. See also Section 3.1.1 on how to improve the legibility of Scilab code by the judicious use of whitespace.