```INTRODUCTION TO
MATLAB
Introduction

What is Matlab? MATrix LABoratory.

MATLAB is a numerical computing environment and programming
language (initially written in C). MATLAB allows easy matrix
manipulation, plotting of functions and data, implementation of
algorithms, creation of user interfaces, and interfacing with programs
in other languages.

MATLAB makes mathematical operations with vectors y matrices.
As a particular case, it can also work with scalar numbers, both reals
and complexes.

It has packages with specialized functions.
Basic elements of Matlab’s desktop

Command Windows: Where all commands and programs are run.
Write the command or program name and hit Enter.

Command History: Shows the last commands run on the
Command Windows. A command can be recovered clicking twice

Current directory: Shows the directory where work will be done.

Workspace: To see the variables in use and their dimensions (if
working with matrices)

Help (can also be called from within the comand windows)

Matlab Editor: All Matlab files must end in the .m extension.
Basic elements of Matlab’s desktop
Current
directory
Command
Windows
Command
History
Matlab editor





There can not be empty spaces in the name of the Matlab files
Use “main_” for the name of the main programs, for example:
main_curvature
Write “;” at the end of a line If you don’t want that the intermediate
calculus is written in the window while the program is running
Write “%” at the beginning of a line to write a comment in the
program
Write “…” at the end of a line if you are writing a very long statement
and you want to continue in the next line
Matlab editor
Debugger
Set/Clear breakingpoint: Sets or clears a break point in the
line the cursor is placed.
Clear all breakingpoints: Deletes all breaking points.
Step: Executes the current line of the program.
Step in: Executes the current line of the program, if the line
calls to a function, steps into the function.
Step out: Returns from a function you stepped in to its calling
function without executing the remaining lines individually.
Continue: Continues executing code until the next breaking
point
Quit debugging: Stops the debugger
Variable Basics
>> 16 + 24
ans =
40
no declarations needed
>> product = 16 * 23.24
product =
371.84
>> product = 16 *555.24;
>> product
product =
8883.8
Intro MATLAB
mixed data
types
semi-colon suppresses output
of the calculation’s result
Variable Basics
>> clear
clear removes all variables;
>> product = 2 * 3^3;
clear x y removes only x and
>> comp_sum = (2 + 3i) + (2 - 3i);
y
>> show_i = i^2;
complex numbers (i or j) require
>> save three_things
no special handling
>> clear
>> who
retain/restore workspace
comp_sum product
show_i
variables
>> product
product =
54
use home to clear screen and put
>> show_i
cursor at the top of the screen
show_i =
-1
Intro MATLAB
Numbers and operations
Basic Arithmetic Operations:


Multiplication: *, Division: /

Power: ^

Priority Order: Power, division and multiplication, and lastly addition
and substraction. Use () to change the priority.

Example: main_number_operations.m. Try the Debugger
Numbers and operations
Matlab Functions:

exp(x), log(x) (base e), log2(x) (base 2), log10(x) (base 10),
sqrt(x)

Trigonometric functions: sin(x), cos(x), tan(x), asin(x), acos(x),
atan(x), atan2(x) (entre –pi y pi)

Hyperbolic functions: sinh(x), cosh(x), tanh(x), asinh(x), acosh(x),
atanh(x)

Other functions: abs(x) (absolute value), int(x) (integer part ),
round(x) (rounds to the closest integer), sign(x) (sign function)

Functions for complex numbers: real(z) (real part), imag(z)
(imaginary part), abs(z) (modulus), angle(z) (angle), conj(z)
(conjugated)
Example: main_number_operations.m
Vectors and matrices
Defining vectors:

Row vectors; elements separated by spaces or comas
>> v =[2 3 4]

Column vectors: elements separated by semicolon (;)
>> w =[2;3;4;7;9;8]

Length of a vector w: length(w)

Generating row vectors:
 Specifying the increment h between the elements v=a:h:b
 Specifying the dimension n: linspace(a,b,n) (by default n=100)
 Elements logarithmically spaced logspace(a,b,n) (n points
logarithmically spaced between 10a y 10b. By default n=50)
Example: main_matrix_operations.m
Vectors and matrices
Defining matrices:

It’s not needed to define their size before hand (a size can be
defined and changed afterwards).

Matrices are defined by rows; the elements of one row are
separated by spaces or comas. Rows are separated by semicolon
(;).
» M=[3 4 5; 6 7 8; 1 -1 0]

Empty matrix: M=[ ];

Information about an element: M(1,3), a row M(2,:), a column M(:,3).

Changing the value of an element: M(2,3)=1;

Deleting a column: M(:,1)=[ ], a row: M(2,:)=[ ];

Example: main_matrix_operations.m
Durer’s Matrix: Creation
» durer1N2row = [16 3 2 13; 5 10 11
8];
» durer3row = [9 6 7 12];
» durer4row = [4 15 14 1];
» durerBy4 =
[durer1N2row;durer3row;durer4row];
» durerBy4
durerBy4 =
16
5
9
4
Intro MATLAB
3
10
6
15
2
11
7
14
13
8
12
1
Easier Way...
durerBy4 =
16
3
5
10
9
6
4
15
2
11
7
14
13
8
12
1
» durerBy4r2 = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1]
durerBy4r2 =
16
5
9
4
3
10
6
15
2
11
7
14
13
8
12
1
Intro MATLAB
Set Functions
Arrays are ordered sets:
>> a = [1 2 3 4 5]
a =
1
2
3
>> b = [3 4 5 6 7]
b =
3
4
5
>> isequal(a,b)
ans =
0
>> ismember(a,b)
ans =
0
0
1
4
5
6
7
returns true (1) if arrays are the same
size and have the same values
returns 1 where a is in b
and 0 otherwise
1
1
Intro MATLAB
Matrix Operations
>> durer = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1]
durer =
16
5
9
4
3
10
6
15
2
11
7
14
MATLAB also has
magic(N) (N >
2)
function
13
8
12
1
>> % durer's matrix is "magic" in that all rows, columns,
>> % and main diagonals sum to the same number
>> column_sum = sum(durer) % MATLAB operates column-wise
column_sum =
34
34
34
34
Intro MATLAB
Dot Operator Example
>> A = [1 5 6; 11 9 8; 2 34 78]
A =
1
5
6
11
9
8
2
34
78
>> B = [16 4 23; 8 123 86; 67 259 5]
B =
16
4
23
8
123
86
67
259
5
Intro MATLAB
Vectors and matrices
Defining matrices:

Generating de matrices:





Generating a matrix full of zeros, zeros(n,m)
Generating a matrix full of ones, ones(n,m)
Initializing an identity matrix eye(n,m)
Generating a matrix with random elements rand(n,m)
Adding matrices: [X Y] columns, [X; Y] rows
Example: main_matrix_operations.m
Operations with vectors and matrices
Operating vectors and matrices with scalars:
v: vector, k: scalar:







v-k sustraction
v*k product
v/k divides each element of v by k
k./v divides k by each element of v
v.^k powers each element of v to the k-power
k.^v powers k to each element of v
Example: main_matrix_operations.m
Operations with vectors and matrices
Operating vectors and matrices










– subtraction
* matrix product
.* product element by element
^ power
.^ power element by element
\ left-division
/ right-division
./ y .\ right and left division element by element
Transposed matrix: B=A’ (in complex numbers, it returns the
conjugated transposed, to get only the trasposed: B=A.’)
Example: main_matrix_operations.m
Functions for vectors and matrices

sum(v) adds the elements of a vector

prod(v) product of the elements of a vector

dot(v,w) vectors dot product

cross(v,w) cross product

mean(v) (gives the average)

diff(v) (vector whose elements are the differenceof the elements of v)

[y,k]=max(v) maximum value of the elements of a vector (k gives the
position), min(v) (minimum value). The maximum value of a matrix M is
obtained with max(max(M)) and the minimum with min(min(v))

Some of these operations applied to matrices, give the result by
columns.
Functions for vectors and matrices

[n,m]=size(M) gives the number of rows and columns

Inverted matrix: B=inv(M), rank: rank(M)

diag(M): gives the diagonal of a matrix. sum(diag(M)) sums the
elements of the diagonal of M. diag(M,k) gives the k-th diagonal.

norm(M) norm of a matrix (maximum value of the absolute values of
the elements of M)

flipud(M) reorders the matrix, making it symmetrical over an
horizontal axis. fliplr(M) ) reorders the matrix, making it symmetrical
over a vertical axis.

[V, landa]=eig(M) gives a diagonal matrix landa with the eigen
values, and another V whose columns are the eigenvectors of M
Example: main_matrix_operations.m
Data input and output

Saving to files and recovering data:

save –mat file_name matrix1_name, matrix2_name



save file_name matrix1_name –ascii (saves 8 figures after the
decimal point)
save file_name matrix1_name –ascii –double (saves 16 figures
after the decimal point)
Example: main_matrix_operations.m
Matlab Files

Program files: Scripts
They are built with a series of commands. The main file will be named
main_name.m

Function files
To create your own functions. They are called from within the scripts.

The first line is executable and starts with the word function as showed:
function [output_arg1, output_arg2]=function_name(input_arg1,
input_arg2, …, parameters)


The file must be saved as function_name.m
Example: main_plot_sine.m. Use “Step in” in Debugger to enter this
function
Vectorization Example*
>> type slow.m
tic;
x=0.1;
for k=1:199901
y(k)=besselj(3,x) +
log(x);
x=x+0.001;
end
toc;
>> slow
Elapsed time is 17.092999
seconds.
*times measured on this laptop
Intro MATLAB
>> type fast.m
tic;
x=0.1:0.001:200;
y=besselj(3,x) + log(x);
toc;
>> fast
Elapsed time is 0.551970
seconds.
Roughly 31 times faster
without use of for loop
Easy 2-D Graphics
>> x = [0: pi/100: pi]; % [start: increment: end]
>> y = sin(x);
>> plot(x,y), title('Simple Plot')
Intro MATLAB
>> z = cos(x);
>> plot(x,y,'g.',x,z,'b-.'),title('More complicated')
Line color, style, marker type,
all within single quotes; type
>> doc LineSpec
for all available line properties
Intro MATLAB
m-file Editor Window
You can save and run the
file/function/script in one
step by clicking here
Tip: semi-colons suppress printing, commas (and
semi-colons) allow multiple commands on one line,
and 3 dots (…) allow continuation of lines without
execution
Intro MATLAB
Functions – First Example
function [a b c] = myfun(x, y)
b = x * y; a = 100; c = x.^2;
Write these two lines to a file
myfun.m and save it on MATLAB’s
path
>> myfun(2,3)
% called with zero
outputs
ans =
100
>> u = myfun(2,3)
% called with one output
u =
100
>> [u v w] = myfun(2,3) % called with all outputs
u =
100
Any return value which is not stored
v =
in an output variable is simply
6
w =
4
Intro MATLAB
Programming
Loops
for k=n1:incre:n2
end
for k=vector_column
end
while
end
Example: main_loops
for Loop
>> for i = 2:5
for j = 3:6
a(i,j) = (i + j)^2
end
end
>> a
a =
0
0
0
0
0
0
0
25
36
49
0
0
36
49
64
0
0
49
64
81
0
0
64
81
100
Intro MATLAB
0
64
81
100
121
while Loop
>> b = 4; a = 2.1; count = 0;
>> while b - a > 0.01
a = a + 0.001;
count = count + 1;
end
>> count
count =
1891
Intro MATLAB
Programming
Conditional control structures

Logical operators:
 >, <, >=,<=,== (equal)
 | (or), &(and)
 ~ (no), ~= (not equal)
if
end
if
else
end
Example: main_conditional
if
elseif
else
end
if/elseif/else Statement
>> A = 2; B = 3;
>> if A > B
'A is bigger'
elseif A < B
'B is bigger'
elseif A == B
'A equals B'
else
error('Something odd is happening')
end
ans =
B is bigger
Intro MATLAB
Programming
Structures of control condicionated: switch

switch is similar to a sequence of if...elseif
switch_expresion=case_expr3 %example
switch switch_expresion
case case_expr1,
actions1
case {case_expr2, case_expr3,case_expr4,...}
actions2
otherwise, % option by default
actions3
end
Example: main_conditional
switch Statement
>> n = 8
n =
8
>> switch(rem(n,3))
case 0
m = 'no remainder'
case 1
m = ‘the remainder is one'
case 2
m = ‘the remainder is two'
otherwise
error('not possible')
end
m =
the remainder is two
Intro MATLAB
```