Scilab Bag Of Tricks: The Scilab-2.5 IAQ (Infrequently Asked Questions) | ||
---|---|---|

Prev | Chapter 2. Common Pitfalls | Next |

The square bracket operator `[]` is a convenient
tool 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 ... expr = ... row = [row expr] end mat = [mat; row] end

Rows are separated by semi-colons, 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 three 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. - 1. + 2.i ! ! - 1. + i 1. - i !m2 = [1 +%i - 1 + %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, orPutting every compound expression in parentheses, like

`-->`ans = ! 1. + i - 1. + i ! ! - 1. + i 1. - i !**[(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 the section called *Line Breaking* in Chapter 3.