Title: INTRODUCTION TO MATLAB
1INTRODUCTION TO MATLAB
- Victoria Lapuerta
- Ana Laverón
2Index
- 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
- Introducción
- Basic elements of Matlabs desktop
- MATLAB editor
- Numbers and operations
- Vectors and matrices
- Operations with vectors and matrices
- Functions for vectors and matrices
- Data Input and output
- Data structures and cell matrices
- Polynomials
3Introduction
- 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.
4Basic elements of Matlabs 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.
5Basic elements of Matlabs desktop
Current directory
Command Windows
Command History
6Basic elements of Matlabs desktop
- Some 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 Ctrlc
7Matlab 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 dont 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
8Matlab 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
9Numbers and operations
- Numerical 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 a2
- Reals x-35.2
- Maximum 19 significant figures
- 2.23e-32.2310-3
- Precision and formats By defect, it uses a short
format defect, but other formats can be used - gtgt format long (14 significant figures)
- gtgt format short (5 significant figures)
- gtgt format short e (exponential notation)
- gtgt format long e (exponential notation)
- gtgt format rat (rational approximation)
- See in File menu Preferences ? Command Windows
10Numbers and operationsPreferences (in File menu)
11Numbers and operations
- Numerical data
- Theyre case sensitive x5, X7
- Information about the variables used and their
dimensions (if theyre matrices) Workspace. Also
typing - gtgt who
- gtgt whos (gives more information)
- To delete a variable (or several), run
- gtgt clear variable1 variable2
- To delete all the variables, run gtgt clear
- Characteristic constants pi?, NaN (not a
number, 0/0), Inf?. - Complex numbers isqrt(-1) (only i or j can be
used), z2i4, z24i - Careful not to use i or j afterwards as a
counter for a loop when working with complex
numbers.
12Numbers 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
13Numbers 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
14Vectors and matrices
- Defining vectors
- Row vectors elements separated by spaces or
comas - gtgt v 2 3 4
- Column vectors elements separated by semicolon
() - gtgt w 234798
- Length of a vector w length(w)
- Generating row vectors
- Specifying the increment h between the elements
vahb - Specifying the dimension n linspace(a,b,n) (by
default n100) - Elements logarithmically spaced logspace(a,b,n)
(n points logarithmically spaced between 10a y
10b. By default n50) - Example main_matrix_operations.m
15Vectors and matrices
- Defining matrices
- Its 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 (). - M3 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
16Vectors 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
17Operations with vectors and matrices
- Operating vectors and matrices with scalars
- v vector, k scalar
- vk addition
- v-k sustraction
- vk 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
18Operations with vectors and matrices
- Operating 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 BA (in complex numbers, it
returns the conjugated transposed, to get only
the trasposed BA.) - Example main_matrix_operations.m
19Functions 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,kmax(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.
20Functions for vectors and matrices
- n,msize(M) gives the number of rows and
columns - Inverted matrix Binv(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, landaeig(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
21Data 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
22Data structures and cell matrices
- Matlab allows store variables with a tree
structure - gtgt structure1.data1 value of data 1
- gtgt structure1.data2value of data 2
- gtgt structure1.data3.subdata31value of subdata 31
- gtgt structure1.data3.subdata32value of subdata 32
- Matlab allows store different variables in
cell matrices - gtgt cell_matrix1 data1 data2 data3 data4
Example main_data_structure.m
23Polynomials
- Polynomials are written in Matlab as a row vector
whose dimension is n1, n being the degree of the
polynomial. - Example x32x-7 is written
- gtgt pol1
- Obtaining the roots roots (returns a column
vector, even though pol1 is a row vector) - gtgtroots_dataroots(pol1)
- A polynomial can be reconstructed from its roots,
using the command poly - gtgt ppoly(roots_data) (returns a row vector)
- If the input for poly is a matrix, the output is
the characteristic polynomian of the matrix
Example main_polynomials.m
24Polynomials
- Matlab functions for polynomials
- Calculate the value of a polynomial p in a given
point x polyval - gtgtypolyval(p,x)
- Multiplying and dividing polynomials conv(p,q) y
deconv(p,q) - Calculate the derivative polynomial polyder(p)
252D and 3D Graphics (I)
- Basic 2D and 3D Graphic Functions
- 2D plot() creates a graphic from vectors, with
linear scales on both axes, - gtgt 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
262D 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)
272D and 3D Graphics(I)
Basic 2D and 3D graphic functions
- 2D ezplot(f) simplified graphic functions. By
default 2p x 2p - ezplot(f,a,b) plots f in a different interval
- f can be an implicit function f(x,y)0.
- gtgt ezplot(f) plots f(x,y)0 in -2piltxlt2pi
and -2piltylt2pi - gtgt ezplot(f, a,b) plots f(x,y)0 in altxltb
and altyltb - gtgt ezplot(f, xmin,xmax,ymin,ymax)
- ezplot can plot parametric functions x(t), y(t)
- gtgt ezplot('sin(t)','cos(t)') plots with
0lttlt2pi - gtgt ezplot('sin(t)','cos(t)', t1,t2) plots
with t1lttltt2 - 2D ezpolar(f) to plot in polar coordinates
- 3D ezplot3 the same idea as ezplot but 3D
Example main_graphics.m
282D 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,-pipi/2,pi) gcaget current
axis - set(gca, XTicklabel,(-pi,-pi/2,0,pi/2,pi
)
292D 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.
302D 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.
312D and 3D Graphics (II)
- Drawing surfaces
- Creating a grid from two vectors X,
Ymeshgrid(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
z0 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 cscontour(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
default2p lt x, y lt 2p. - Example main_surface_graphics.m and see in
Demos Graphics
Example main_surface_graphics.m and see in
Demos Graphics
322D 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)
332D and 3D Graphics (III)
- Coordinate System Transformation
- ang,radcart2pol(x,y), from cartesians to
polars - ang,rad,zcart2pol(x,y,z), from cartesians to
cylindric - x,ypol2cart(ang,rad), from polars to
cartesians - x,y,zpol2cart(ang,rad,z), from cylindric to
cartesians - angx,angz,radcart2sph(x,y,z), from cartesians
to spheric - x,y,zaph2cart(angx,angz,rad), from espheric to
cartesians
34Creating 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 - X00.012pi
- for j110
- plot(x,sin(jx)/2)
- M(j)getframe
- end
- movie(M,4,6)
- Example main_movie.m
35Matlab 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_arg2function_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
36Matlab 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. - gtgt function_1 inline('cos(x)2sin(2x)')
- gtgt function_2 inline('cos(x)2sin(2y),x,y
) - Input and Output commands
- input allows entering data ainput(Type the
value of a) - disp shows a text on screen disp(The algorythm
did not converge)
37Functions for functions
- Function references
- They asign a function to a variable. The operator
_at_ is used. - gtgt _at_reference_namefunction_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
38Function for functions
- fzero(_at_name_function,x0) Calculates the zero of
a function closest to the value of the variable
x0 - fminsearch(_at_name_function,x0) calculates the
relative minimun of a function closest to x0 - fminbnd(_at_name_function,a,b) calculates a
minimun of the function in the interval a,b
Example main_functions_for_functions.m
39Programming
- Loops
- for kn1incren2
-
- end
- for kvector_column
- end
- while
- end
- Example main_loops
40Programming
- Conditional control structures
- Logical operators
- gt, lt, gt,lt, (equal)
- (or), (and)
- (no), (not equal)
- Example main_conditional
if elseif else end
if else end
if end
41Programming
- Structures of control condicionated switch
- switch is similar to a sequence of if...elseif
switch_expresioncase_expr3 example switch
switch_expresion case case_expr1, actions1 ca
se case_expr2, case_expr3,case_expr4,... actio
ns2 otherwise, option by default actions3 end
Example main_conditional
42Programming
- Interpolation
- 1D
- A polynomial is defined (example, n2,
ax2bxc),to interpolate ppolyfit(x,y,n). To
obtain the interpolation on certain values xi
yipolyval(p,xi). - yi interp1(x,y,xi,method). Methods linear
(linear interpolation), cubic (cubic), spline
(cubic spline ) - 2D
- matrix_Zinterp2(X,Y,Z,matrix_X,matriz_Y,method).
Methods bilinear (linear interpolation),
bicubic (cubic)
43Numerical Analysis
- Integration
- 1D quad, quadl integrate a function in an
interval a,b - quad(_at_name_function,a,b)
- 2D dblquad integrate a function in an interval
xmin,xmaxxymin,ymax - dblquad(_at_sin,xmin,xmax,ymin,ymax)
44Numerical Analysis
- Solving differential ecuations
- Solving initial value problems for ordinate
differential ecuations (ODEs) - T,Ysolver(_at_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
45Exercise I
- Represent the functions
- y1 sin(3 p x)/ex
- y2cos(3p x)/ex
- with x between 0 and 3 p,obtaining only one
figure like
46Exercise II
- Solve the equation system
- 3x2y-z1
- 5xy3z-2
- 3y-4z3
- Be A the coefficients matrix of the previous
system. Obtain the maximum eigenvalue of A and
its associated eigenvector as the program output.