# Matrices

## Matrices on MatLab

An array is a collection of numbers or strings (text) and matrices are simply 2-dimentional arrays. Matlab 'understands' every parametre as a matrix. Even single numbers (e.g. x = 1) and vectors (e.g. v = [1 3 2]) are taken as 1-by-1 and (in this example) 1-by-3 matrices.

## Creating Matrices

Entering matrices on Matlab is fairly easy. They are input by entering a list of numbers separated by commas (,) for elements on a same row and semi-colons (;) for elements on the next row.
As such, inputting:

A = [1, 2, 3; 4, 5, 6; 7, 8, 9];
B = [10, 11, 12; 13, 14, 15; 16, 17, 18];

Gives:

A =
1    2    3
4    5    6
7    8    9

B =
10   11   12
13   14   15
16   17   18

It is possible to concatenate matrices (link smaller matrices to make a bigger one) as such:

C = [A ; B];

Which gives:

C =
1    2    3
4    5    6
7    8    9
10   11   12
13   14   15
16   17   18

It is also possible to create matrices using the incremental notation seen earlier in order to save time by not having to write out each individual value:

D = [100: -11: 50; 45: -11: 0];

This gives a 2-by-5 matrix between 100 and 0 of increments -11:

D =
100    89    78    67    56
45    34    23    12     1

When creating matrices, further shortcuts include

The identity matrix

The zeroes matrix

The ones matrix

E = eye(3)

E =
1    0    0
0    1    0
0    0    1

F = zeroes(3)

F =
0    0    0
0    0    0
0    0    0

G = ones(3)

G =
1    1    1
1    1    1
1    1    1

## Indexing

Consider the matrix:

A = [1, 2, 3; 4, 5, 6; 7, 8, 9];

Written as:

A =
1    2    3
4    5    6
7    8    9

1. Selecting the element in row 2 and column 3:

A(2,3)

Which returns:

ans =
6

2. Selecting the element in rows 1 to 2 and column 2 to 3:

A(1:2,2:3)

Which returns:

ans =
2    3
5    6

3. Selecting the first row:

A(1,:)

Which returns:

ans =
1    2    3

4. Selecting the third column:

A(:,3)

Which returns:

ans =
3
6
9

5. Selecting the element of index '4':

A(4)

Which returns:

ans =
2

N.B. MatLab indexes from 1 (not 0, unlike many other languages) and down each column. As such, in matrix A, the numbers 1, 4, 7 and 2 respectively have indices of 1, 2, 3 and 4. It is also possible of selecting multiple elements based on their indices using  A(index_1, index_2, ..., index_n).