Vectors and Matrices
Last revision: January 11, 2017In this section we are going to cover some linear algebra
stuff. Octave is especially well designed for those purposes.
Vectors are the most basic objects in Octave. You already
know how to define some: V=1:5 yields V=(1,2,3,4,5). You can also
say:
> V=[1 2 3 4 5]But that’s a row vector. What if you want a column vector? There are two ways:
> W=V'which means transpose (i.e.: convert rows into columns), or either you can do:
> W=[1;2;3;4;5]Either way it will work. You can cut vectors easily:
> V=[5 1 4 3 2];
> V(2)
ans = 1
> V([1:3])
ans = [5 1 4]Matrices are not difficult to define either:
> A=[ 1 2; 3 4]
A =
1 2
3 4 Of course, you can multiply a matrix with a column vector:
> A=[ 1 2; 3 4];
> V=[0;1];
> A*V
ans =
2
4 Solving a linear system is very easy. If your system is $A\vec x=\vec
b$, with $A$ a matrix and $\vec b$ a vector, then you can formally
write x = A \ b, and that will solve the system by gaussian
reduction. An example, let’s solve the system:
So we write the matrix $A$ and the right hand side vector $\vec b$:
> A = [ 1 3; 2 -5]
> b = [ 5; -1 ]
> x = A \ b
x = [ 2; 1 ]We can check easily that the solution is right:
> A * x
ans = [ 5; -1]as it should.
The special matrices are easy to find. For example, the identity, $I$, is called “eye” (yes, it’s someone’s idea of a joke):
> I=eye(2)
> A*I
ans =
1 3
2 -5Or the zero matrix:
> Z=zeros(2)
> A*Z
ans =
0 0
0 0Exercises
- Solve the following linear system of equations:
Check the solution!
- Find the 10-th power of the following matrix
1 0 1
0 1 0
1 1 1