You are on page 1of 42

Introduction to

Matlab

MATLAB (MATrix LABoratory) is one of the most popular packages for


scientic com- puting. It oers extensive libraries of numerical methods and
a variety of tools for visualization.

The MATLAB desktop

Building matrices
Command Meaning

>> A = [2, 4; 6, 8]
A=
2 4
6 8
The commas can be replaced by spaces.
>> A = [2 4; 6 8]
A=
2 4
6 8

>> A = [2 4; 6 8], B = [1 3; 5 7]; C = [1 2 1 3; 1 4 1 5]


A=
2 4
6 8
B=
1 3
5 7
C=
1 2 1 3
1 4 1 5
Matrices can be combined by using the comma or the semicolon in conjunc- tion with the matrix
constructor [].
>> C = [A , B], D = [A ; B]
C=
2 4 1 3 6 8 5 7
D=
2 4 6 8 13 5 7
If the matrices we are trying to combine are not of the correct shapes, i.e. the rows or columns that we
are trying to combine do not match, then the following error will be produced.

>> C, D
C=
2 4 1 3 6 8 5 7
D=
24681357
>> 1:1:5
ans =
1 23 45
In this example we have created a sequence of numbers starting from 1 and
ending at 5 with a step size of 1.

>> F = [1:1:5;11:2:20]
F=
1 2 3 4 5 11 13 15 17 19

Addressing and assigning elements


The rst action we have to take in order to assign a value to a variable is to address the element of
the variable we want. To address an element of a matrix the round brackets (a,b) are used. a and b
are positive integers, i.e. a,b N. The rst element inside the brackets denotes the row and the
second denotes the column.
>> F
F=
1 2 3 4 5 11 13 15 17 19
>> F(2,3)
ans =
15
Vectors can also be used to address elements in a matrix.
>> F([1 ; 2] , 3)
ans =
315
>> F([1 2] , 3)
ans =
3 15
The colon : can be used to address all the elements of a row or column.

Building special matrices


It is convenient to be able to build special matrices without the necessity of
long procedures. The following table summarizes the functions to build
special matrices.

>> randn(3,3)

You might also like