You are on page 1of 9

# VECTORS AND MATRICES

## Which of the following is a vector and which one is a matrix

Definitions
Vectors and matrices: set of elements (array).

## %Example - Write the following:

%%Row vector
row=[5 88 3 11] %Mind the spaces in between the values.

## If you want to refer to the element with the index No. 2

row(2)

Creating a subvector
sub1=row(2:4) %Sequential indexes

sub1(2)=16

sub1(4)=22

## vec_bigstep=1:3:5 %it will stop before the upper limit.

Decreasing vector

vec_dec=10:-2:1

## %What happens if you write the following:

vec_dec=1:-2:10 %Empty vector, the lower limit is first.

## Creating a column vector from a row vector: transpose

rowtrans = row'
Creating matrices and basic commands to deal with them

## Can you have different rows with different number of elements?

mat=[1 2 3
4 5 6] %The rows can be divided in lines.

mat=[1:3;4:6]

## Remember: Matlab counts from up to bottom and from left to right.

mat(1) %it will refer to the element of the first row, first column

mat(5) %it will refer to the element in the first row, column tree.

## Expanding the matrix

mat(4,:)=[20 30 40] % Adds the row No. 4 and fills the 3rd with zeros.
mat =
1 20 3
20 30 40
0 0 0
20 30 40

mat(:,5)= [20 30 40 50]' %Adds the row No. 4 and fills the 3rd with zeros.

mat =
1 20 3 0 20
20 30 40 0 30
0 0 0 0 40
20 30 40 0 50

mat =
1 20 3 0
20 30 40 0
0 0 0 0
20 30 40 0

mat =
1 20 3 0
20 30 40 0

## %Create the following matrices

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

A =
1 2 3
4 5 6
7 8 9

B=A'

B =
1 4 7
2 5 8
3 6 9
Multiplication

B*A

ans =
66 78 90
78 93 108
90 108 126

## Multiplication with vector

a=[4 9 1]

a =
4 9 1

a*B

ans =
25 67 109

B =
1 4 7
2 5 8
3 6 9

A.*B

ans =
1 8 21
8 25 48
21 48 81

A+B
A-B

Division

A./B
B./A %The order matters

A.\B %Elementwise but dividing the elements from B by the one from A

Potencies

Z =
0 0
0 0
0 0

z =
0
0
0

Ones =
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1

ans =
1 0 0 0
0 1 0 0

r=[1 2; 3 4]

r =
1 2
3 4

ans =
1 2 1 2 1 2
3 4 3 4 3 4
1 2 1 2 1 2
3 4 3 4 3 4
1 2 1 2 1 2
3 4 3 4 3 4
1 2 1 2 1 2
3 4 3 4 3 4

ans =
0.8147 0.9134
0.9058 0.6324
0.1270 0.0975

ans =
-2 -4 3 3 4
1 5 -4 5 5
5 5 -1 2 2
5 0 5 -5 3

## linspace function: linspace(x,y,n) - vector of n elements within the range [x,y].

% Example
ls=linspace(3,15,5)

ls =
3 6 9 12 15

Hypermatrices:
One matrix of i x j dimensions and k "layers".

## e.g. Grid Example master thesis.

% Example
AA(:,:,1)=[1 2 3; 4 5 6]
AA(:,:,2)=[2 3 4; 5 6 7]

%Example
AA(:,:,2)