Section 4.9 Octave/MATLAB recap
Matrices. In the code below we show several ways to define a matrix. In the example we use a \(2\times2\) matrix but the same syntax can be used for any \(n\text{.}\)
Operations with matrices. Matrices can be added, subtracted, multiplied and inverted. Moreover, matrices can be transposed, namely their rows become columns and viceversa. The code below shows examples of such operations. There are two important things to remark:
- The multiplication operator for matrix multiplication is
*
. The operator .*
would rather do a componentswise multiplication (see the code example below)
- Using the inversion to solve a system is not optimal, better using the LU decomposition or other methods.
Vectors and covectors. Arrays are by default row vectors. Technically, these are called covectors. A row vector v
can be made into a column vector by transposition. Note that matrices act (by multiplication) on column vectors only from the right and on row vectors, i.e. covectors, only from the left, as the code below illustrates:
Implicit loops. Sometimes loops can be executed implicitly using the fact that arrays can be used in place of indices for matrices, as the example below shows: The last two lines in the code above correspond to the following loop:
for k=1:length(x)
x(k)=x(k)+k.^2
end
While loops. We have already went over the for
instruction in Section 2.4. Here we meet a second way to do loops, the instruction while
. The major difference is that, while in a for
loop we provide a given number of times to repeat the instructions in the loop code, with a while
the exit condition can be any conditional statement. Notice that this in principle is dangerous because the condition might never be met and so the loop might stall. As an example, the code below calculates all Fibonacci numbers up to the first larger than 1000: Using while
rather than \(for\) is often merely matter of taste since most loops can actually be written with any of the two. The code above can be written with a for
as follows: