INTRODUCTION TO MATLAB
Victoria Lapuerta
Ana Laverón
Index Introducción Basic elements of Matlab’s
desktop MATLAB editor Numbers and operations Vectors and matrices Operations with vectors and
matrices Functio
ns for vectors and matrices Data Input and output Data structures and cell mat
rices Polynomials
2D and 3D graphics (I) 2D and 3D graphics (II) 2D and 3D graphics (III) Creating movies Matlab files Functions for functions Programming Numerical analysis Exercices
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.
CommandWindows
Current directory
CommandHistory
Basic elements of Matlab’s desktop
Basic elements of Matlab’s desktopSome comments about the command window
Commands can be retrieved with arrow up / arrow down keys ↓↑
Moving around the command line is possible with left / right arrow keys → ←. Go to the beginning of the line with Inicio (Home) and to the end with Fin (End). Esc deletes the whole line.
A program can be stopped with Ctrl+c
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 editorDebugger
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
Numbers and operationsNumerical Data:
Variables are defined with the assignment operator “=“. MATLAB is dynamically typed, meaning that variables can be assigned without declaring their type, and that their type can change. There is no need to define variables as integers, reals, etc, as in other languages
Integers: a=2 Reals: x=-35.2
Maximum 19 significant figures 2.23e-3=2.23*10-3
Precision and formats: By defect, it uses a short format defect, but other formats can be used: >> format long (14 significant figures) >> format short (5 significant figures) >> format short e (exponential notation) >> format long e (exponential notation) >> format rat (rational approximation)
See in File menu: Preferences → Command Windows
Numbers and operationsPreferences (in File menu)
Numbers and operationsNumerical data: They’re case sensitive: x=5, X=7
Information about the variables used and their dimensions (if they’re matrices): Workspace. Also typing
>> who >> whos (gives more information)
To delete a variable (or several), run:>> clear variable1 variable2
To delete all the variables, run: >> clear
Characteristic constants: pi=, NaN (not a number, 0/0), Inf=.
Complex numbers: i=sqrt(-1) (only i or j can be used), z=2+i*4, z=2+4i Careful not to use ‘i’ or “j” afterwards as a counter for a loop when
working with complex numbers.
Numbers and operations
Basic Arithmetic Operations:
Addition: +, Substraction -
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 operationsMatlab 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 matricesDefining 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 matricesDefining 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
Vectors and matricesDefining 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 matricesOperating vectors and matrices with scalars:
v: vector, k: scalar:
v+k addition 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 matricesOperating vectors and matrices
+ addition – 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 eigenvalues, 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
load –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
Data structures and cell matrices Matlab allows store variables with a tree structure:
>> structure1.data1= value of data 1>> structure1.data2=value of data 2>> structure1.data3.subdata31=value of subdata 31>> structure1.data3.subdata32=value of subdata 32
Example: main_data_structure.m
estructura1
dato1 dato2 dato3
subdato31 subdato32
Matlab allows store different variables in cell matrices: >> cell_matrix1= {data1 data2; data3 data4}
data1 data2
data3 data4
Polynomials Polynomials are written in Matlab as a row vector whose dimension
is n+1, n being the degree of the polynomial. Example: x3+2x-7 is written:
>> pol1=
Obtaining the roots: roots (returns a column vector, even though pol1 is a row vector)
>>roots_data=roots(pol1)
A polynomial can be reconstructed from its roots, using the command poly
>> p=poly(roots_data) (returns a row vector)
If the input for poly is a matrix, the output is the characteristic polynomian of the matrix
1 0 2 -7
Example: main_polynomials.m
Polynomials
Matlab functions for polynomials
Calculate the value of a polynomial p in a given point x: polyval
>>y=polyval(p,x)
Multiplying and dividing polynomials: conv(p,q) y deconv(p,q)
Calculate the derivative polynomial: polyder(p)
2D and 3D Graphics (I)Basic 2D and 3D Graphic Functions
2D: plot() creates a graphic from vectors, with linear scales on both axes,
>> plot(X,Y,’option’) (option: allows chosing color and stroke of the curve)
hold on: allows to draw more graphics on the same figure (deactivate with hold off)
grid activates a grid on the drawing. Writing grid again deactivates it.
2D: loglog() logarithmic scale on both axes, semilogx(): logarithmic scale on the abcises axis, and linear on the ordinates axis, semilogy(): linear scale on abscises and logarithmic on ordinates.
Example: main_graphics.m, and see in Demos: Graphics
2D and 3D Graphics (I)
Basic 2D and 3D graphic functions
2D: subplot(n,m,k) divides a drawing window in n horizontal parts and m vertical parts, where k is the activated partition.
2D: polar(angle,r) to draw in polars
2D: fill(x,y,’option’) draws a closed curve and fills it with the color indicated in ‘option’
3D: plot3 is similar to the 2D plot.» plot3(X,Y,Z, ’option’)
2D and 3D Graphics(I)
2D: ezplot(f) simplified graphic functions. By default [–2π ≤ x ≤ 2π]
ezplot(f,[a,b]) plots f in a different interval
f can be an implicit function f(x,y)=0. >> ezplot(f); % plots f(x,y)=0 in -2*pi<x<2*pi and -2*pi<y<2*pi>> ezplot(f, [a,b]); % plots f(x,y)=0 in a<x<b and a<y<b>> ezplot(f, [xmin,xmax,ymin,ymax]);
ezplot can plot parametric functions x(t), y(t):>> ezplot('sin(t)','cos(t)'); % plots with 0<t<2*pi>> ezplot('sin(t)','cos(t)', [t1,t2]); % plots with t1<t<t2
2D: ezpolar(f) to plot in polar coordinates 3D: ezplot3 the same idea as ezplot but 3D
Example: main_graphics.m
Basic 2D and 3D graphic functions
2D and 3D Graphics (I)Selecting the axes scale
axis([x0 x1 y0 y1]) (2D), axis([x0 x1 y0 y1 z0 z1]) (3D)
axis auto: returns to the default scale
axis off: deactivates the axes labels. Axes, labels and grid disappear, axis on: activates it again.
axis equal: same scale factor for both axes
axis square: encloses the area delimited by the axes in a square.
To chose the labels on the axes:
set(gca, ‘XTick’,-pi:pi/2,pi) %gca:get current axis set(gca, ‘XTicklabel’,({‘-pi’,’-pi/2’,0,’pi/2’,’pi’})
2D and 3D Graphics (I)Functions to add titles to the graphic
title('title') adds a title to the drawing. To include in the text the value of a numerical variable, it has to be transformed with:
int2str(n) converts the value of the integer n to a character num2str(x) converts the value of a real or complex variable x to
a character. Example: title(num2str(x))
xlabel(‘text’) adds a label to the abscises axis. With xlabel off it disapppears. Same with ylabel(‘text’) or zlabel(‘text’)
text(x,y,'text') places 'text‘ on the specific coordinates x and y. If x and y are vectors, the text is placed on each pair of elements.
gtext('text') places text with help of the mouse.
2D and 3D Graphics (I)Matlab functions for 2D and 3D graphics
Printing graphics: Print (File button on the graphic window)
Saving graphics: Save (File button on the graphic window): A .fig file is created, it can be re-edited and saved again.
Exporting graphics: Export (File button on the graphic window)
figure(n): calls to a new figure or to a figure already done.
close all deletes all figures, close(figure(n)) deletes one figure in particular.
2D and 3D Graphics (II)Drawing surfaces
Creating a grid from two vectors [X, Y]=meshgrid(x,y) Drawing of the grid builton a surface Z(X,Y):
mesh(X,Y,Z), meshc(X,Y,Z) (also draws the level lines on the z=0 surface)
Graphic of the surface Z(X,Y): surf(X,Y,Z), surfc(X,Y,Z)
pcolor(Z) draws the projection with colored shadows on the flat surface (the color range is related to the variations of Z)
contour(X,Y,Z,v) and contour3(X,Y,Z,v) generate contour lines of a surface for the values given in v. To label the lines, first cs=contour(Z) (to know the contour values) and then clabel(cs) or directly clabel(cs,v)
contourf(X,Y,Z,v): to fill with colours the space between contour lines ezsurf (f). Plots a 3D graphic of f(x,y). By default:–2 < x, y < 2.
Example: main_surface_graphics.m and see in Demos: Graphics
Example: main_surface_graphics.m and see in Demos: Graphics
2D and 3D Graphics (II)Drawing surfaces Different ways of drawing colored polygons:
shading flat: shadows with flat color for each polygon. shading interp: shadows with interpolated colors between
corners of each polygon. shading faceted: flat shadowing with superposed black lines
(default option)
hidden off (deactivates the option of hidden lines), hidden on (activates it)
Manipulating graphics: view(azimut, elev), view([xd,yd,zd]) rotate(h,d,a) or rotate(h,d,a,o), ‘h’ is the object, ‘d’ is a vector
that gives the direction, ‘a’ an angle and ‘o’ the rotation origin In graphic window: View (camera toolbar)
2D and 3D Graphics (III)Coordinate System Transformation
[ang,rad]=cart2pol(x,y), from cartesians to polars [ang,rad,z]=cart2pol(x,y,z), from cartesians to cylindric
[x,y]=pol2cart(ang,rad), from polars to cartesians [x,y,z]=pol2cart(ang,rad,z), from cylindric to cartesians
[angx,angz,rad]=cart2sph(x,y,z), from cartesians to spheric [x,y,z]=aph2cart(angx,angz,rad), from espheric to cartesians
Creating movies
A movie is made out of several images or frames
getframe is used to save all those images. It returns a column vector with the required information for reproducing the image that has been represented, for example with the plot function. These vectors are stored in a matrix, M.
movie(M,n,fps) represents n times the movie stored in M at a fps frames per second speed
X=0:0.01:2*pi;for j=1:10
plot(x,sin(j*x)/2)M(j)=getframe;
endmovie(M,4,6)
Example: main_movie.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
Matlab Files MATLAB allows the definition of functions directly from mathematic
expressions using function inline
By default 'x‘, ‘y’, … are the inputs, althought it is possible to define them explicitly when we call the function inline.
>> function_1 = inline('cos(x)+2*sin(2*x)');
>> function_2 = inline('cos(x)+2*sin(2*y)‘,’x’,’y’);
Input and Output commands:
input: allows entering data: a=input(‘Type the value of a’); disp: shows a text on screen: disp(‘The algorythm did not
converge’)
Functions for functionsFunction references
They asign a function to a variable. The operator @ is used.
>> @reference_name=function_name
To evaluate a reference the function feval is used as follows
[r1, r2, r3, ...] = feval(reference_name, arg1, arg2, arg3, ...)
Function references are very useful to give a function to other functions. Functions that execute other functions are called functions for functions.
Function references are variables of MATLAB, so they can be stored in matrices, for example.
Example: main_functions_for_functions.m
Function for functions
fzero(@name_function,x0): Calculates the zero of a function closest to the value of the variable x0
fminsearch(@name_function,x0): calculates the relative minimun of a function closest to x0
fminbnd(@name_function,a,b): calculates a minimun of the function in the interval [a,b]
Example: main_functions_for_functions.m
ProgrammingLoops
for k=n1:incre:n2
end
for k=vector_column
end
while
end
Example: main_loops
ProgrammingConditional control structures
Logical operators: >, <, >=,<=,== (equal) | (or), &(and) ~ (no), ~= (not equal)
Example: main_conditional
if
end
if
else
end
if
elseif
else
end
ProgrammingStructures of control condicionated: switch
switch is similar to a sequence of if...elseif
Example: main_conditional
switch_expresion=case_expr3 %example
switch switch_expresion
case case_expr1,actions1
case {case_expr2, case_expr3,case_expr4,...}actions2
otherwise, % option by defaultactions3
end
ProgrammingInterpolation
1D: A polynomial is defined (example, n=2, ax^2+bx+c),to
interpolate: p=polyfit(x,y,n). To obtain the interpolation on certain values ’xi’: yi=polyval(p,xi).
yi = interp1(x,y,xi,method). Methods: ‘linear’ (linear interpolation), ’cubic’ (cubic), ’spline (cubic spline )
2D: matrix_Z=interp2(X,Y,Z,matrix_X,matriz_Y,method). Methods:
’bilinear’ (linear interpolation), ’bicubic’ (cubic)
Numerical AnalysisIntegration
1D: quad, quadl: integrate a function in an interval [a,b]
quad(@name_function,a,b)
2D: dblquad: integrate a function in an interval [xmin,xmax]x[ymin,ymax]
dblquad(@sin,xmin,xmax,ymin,ymax)
Numerical AnalysisSolving differential ecuations
Solving initial value problems for ordinate differential ecuations (ODEs)
[T,Y]=solver(@F,tspan,Y0)
solver: algorythm to solve ODEs, ode45, ode23, ode113, ode15s,ode23s.
F: function that has the differentical ecuations in matrix form Tspan: times vector [t0 tfinal] for the integration. Y0: column vector with the initial conditions in t0
Exercise IRepresent the functions:
y1= sin(3 π x)/ex
y2=cos(3π x)/ex
with x between 0 and 3 π,obtaining only one figure like:
Exercise II
a) Solve the equation system:
3x+2y-z=1
5x+y+3z=-2
3y-4z=3
b) Be A the coefficients matrix of the previous system. Obtain the maximum eigenvalue of A and its associated eigenvector as the program output.