Tuesday, September 15, 2015

Matlab Tutorial Part 2 - Matrices and Vectors

After I gave in the previous post a little introduction into the programming language Matlab, I want to continue with this post in that topic.
Here I want to write about the usage of matrices and vectors, for which the language is optimized and which can be used very conveniently.
A matrix is defined in square brackets, entries of one row are separated by comma, rows by semicolon, so for example: A = [1, 2; 3, 4]
Vectors of course are only special cases of matrices, namely one-dimensional ones. Thus they can be defined via V1 = [1, 2] (row vector) or V2 = [3;4] (column vector) - in the following I will only use the term matrix.
There are different predefined Matlab function for creating certain matrices: Here I want to mention ones(), zeros() and rand().
ones(a, b) creates a a x b matrix (a rows, b columns) with all entries a 1. This can also be done for higher dimensions, if only one parameter is passed over a 2-dimensional square matrix is created.
zeros() and rand() do the same, zeros() fills the resulting matrix with zeros, rand() with random entries between 0 and 1.
With matrices we can calculate as we are used to. Via +, -, * we can do matrix addition, subtraction and multiplication. * is overloaded and can also be used for a scalar multiplication between a scalar (a number) and a matrix.
In the Matlab documentation all possible functions regarding matrices are listed, like for example determining the rank (rank()) and and and.
Another intesting function when using matrices is the extraction of submatrices.
We can define a submatrix of the matrix A consisting of the rows a to b and columns c to d as follows: A(a:b, c:d)
When emitting the colon the dimension is taken completely: A(:, c:d)
Via the function sum() we thus can for example conveniently sum over the rows / colums of a matrix, for row i the command for this is: sum(A(1,:))
In the next post I will show another interesting application, there we describe the solving of equation systems.


  1. This blog awesome and i learn a lot about programming from here.The best thing about this blog is that you doing from beginning to experts level.

    Love from

    1. Thanks for your kind words, always very nice to hear!