INTRODUCTION TO MATLAB Victoria Lapuerta Ana Lavern Index

INTRODUCTION TO MATLAB Victoria Lapuerta Ana Laverón

Index q q q q q Introducción Basic elements of Matlab’s 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 q q q q q 2 D and 3 D graphics (I) 2 D and 3 D graphics (III) Creating movies Matlab files Functions for functions Programming Numerical analysis Exercices

Introduction n What is Matlab? MATrix LABoratory. n 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. n MATLAB makes mathematical operations with vectors y matrices. As a particular case, it can also work with scalar numbers, both reals and complexes. n It has packages with specialized functions.

Basic elements of Matlab’s desktop n Command Windows: Where all commands and programs are run. Write the command or program name and hit Enter. n Command History: Shows the last commands run on the Command Windows. A command can be recovered clicking twice n Current directory: Shows the directory where work will be done. n Workspace: To see the variables in use and their dimensions (if working with matrices) n Help (can also be called from within the comand windows) n Matlab Editor: All Matlab files must end in the. m extension.

Basic elements of Matlab’s desktop Current directory Command Windows Command History

Basic elements of Matlab’s desktop Some comments about the command window q q q 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 n There can not be empty spaces in the name of the Matlab files n Use “main_” for the name of the main programs, for example: main_curvature n 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 n Write “%” at the beginning of a line to write a comment in the program n 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

Numbers and operations Numerical Data: n 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 q q n Integers: a=2 Reals: x=-35. 2 n Maximum 19 significant figures n 2. 23 e-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 operations Preferences (in File menu)

Numbers and operations Numerical data: n They’re case sensitive: x=5, X=7 n Information about the variables used and their dimensions (if they’re matrices): Workspace. Also typing >> whos (gives more information) n To delete a variable (or several), run: >> clear variable 1 variable 2 n To delete all the variables, run: n Characteristic constants: pi= , Na. N (not a number, 0/0), Inf=. n >> clear Complex numbers: i=sqrt(-1) (only i or j can be used), z=2+i*4, z=2+4 i q 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: n Addition: +, Substraction - n Multiplication: *, Division: / n Power: ^ n Priority Order: Power, division and multiplication, and lastly addition and substraction. Use () to change the priority. n Example: main_number_operations. m. Try the Debugger

Numbers and operations Matlab Functions: n exp(x), log(x) (base e), log 2(x) (base 2), log 10(x) (base 10), sqrt(x) n Trigonometric functions: sin(x), cos(x), tan(x), asin(x), acos(x), atan 2(x) (entre –pi y pi) n Hyperbolic functions: sinh(x), cosh(x), tanh(x), asinh(x), acosh(x), atanh(x) n Other functions: abs(x) (absolute value), int(x) (integer part ), round(x) (rounds to the closest integer), sign(x) (sign function) n 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: n Row vectors; elements separated by spaces or comas >> v =[2 3 4] n Column vectors: elements separated by semicolon (; ) >> w =[2; 3; 4; 7; 9; 8] n Length of a vector w: length(w) n Generating row vectors: q Specifying the increment h between the elements v=a: h: b q Specifying the dimension n: linspace(a, b, n) (by default n=100) q Elements logarithmically spaced logspace(a, b, n) (n points logarithmically spaced between 10 a y 10 b. By default n=50) Example: main_matrix_operations. m

Vectors and matrices Defining matrices: n It’s not needed to define their size before hand (a size can be defined and changed afterwards). n 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] n Empty matrix: M=[ ]; n Information about an element: M(1, 3), a row M(2, : ), a column M(: , 3). n Changing the value of an element: M(2, 3)=1; n Deleting a column: M(: , 1)=[ ], a row: M(2, : )=[ ]; n Example: main_matrix_operations. m

Vectors and matrices Defining matrices: n Generating de matrices: q q n 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 Operating vectors and matrices with scalars: matrices v: vector, k: scalar: n n n n 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 Operating vectors and matrices n n n n n + addition – subtraction * matrix product. * product element by element ^ 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 sum(v) adds the elements of a vector matrices n n prod(v) product of the elements of a vector n dot(v, w) vectors dot product n cross(v, w) cross product n mean(v) (gives the average) n diff(v) (vector whose elements are the differenceof the elements of v) n [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(M)) and the minimum with min(v)) n Some of these operations applied to matrices, give the result by columns.
![Functions for vectors and [n, m]=size(M) gives the number of rows and columns matrices Functions for vectors and [n, m]=size(M) gives the number of rows and columns matrices](http://slidetodoc.com/presentation_image_h/3172f90ce9ba830102176b7db019576f/image-20.jpg)
Functions for vectors and [n, m]=size(M) gives the number of rows and columns matrices n n Inverted matrix: B=inv(M), rank: rank(M) n 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. n norm(M) norm of a matrix (maximum value of the absolute values of the elements of M) n flipud(M) reorders the matrix, making it symmetrical over an horizontal axis. fliplr(M) ) reorders the matrix, making it symmetrical over a vertical axis. n [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 n Saving to files and recovering data: q save –mat file_name matrix 1_name, matrix 2_name q load –mat file_name matrix 1_name, matrix 2_name q q save file_name matrix 1_name –ascii (saves 8 figures after the decimal point) save file_name matrix 1_name –ascii –double (saves 16 figures after the decimal point) Example: main_matrix_operations. m

Data structures and cell matrices n Matlab allows store variables with a tree structure: >> structure 1. data 1= value of data 1 >> structure 1. data 2=value of data 2 >> structure 1. data 3. subdata 31=value of subdata 31 >> structure 1. data 3. subdata 32=value of subdata 32 estructura 1 dato 2 dato 3 subdato 31 § subdato 32 Matlab allows store different variables in cell matrices: >> cell_matrix 1= {data 1 data 2; data 3 data 4} Example: main_data_structure. m data 1 data 2 data 3 data 4

Polynomials n Polynomials are written in Matlab as a row vector whose dimension is n+1, n being the degree of the polynomial. Example: x 3+2 x-7 is written: >> pol 1= n Obtaining the roots: roots (returns a column vector, even though pol 1 is a row vector) >>roots_data=roots(pol 1) n A polynomial can be reconstructed from its roots, using the command poly >> p=poly(roots_data) (returns a row vector) n If the input for poly is a matrix, the output is the characteristic polynomian of the matrix Example: main_polynomials. m

Polynomials Matlab functions for polynomials n Calculate the value of a polynomial p in a given point x: polyval >>y=polyval(p, x) n Multiplying and dividing polynomials: conv(p, q) y deconv(p, q) n Calculate the derivative polynomial: polyder(p)

2 D and 3 D Graphics (I) Basic 2 D and 3 D Graphic Functions n 2 D: 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) q q n 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. 2 D: 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

2 D and 3 D Graphics (I) Basic 2 D and 3 D graphic functions n 2 D: subplot(n, m, k) divides a drawing window in n horizontal parts and m vertical parts, where k is the activated partition. n 2 D: polar(angle, r) to draw in polars n 2 D: fill(x, y, ’option’) draws a closed curve and fills it with the color indicated in ‘option’ n 3 D: plot 3 is similar to the 2 D plot. » plot 3(X, Y, Z, ’option’)

2 D and 3 D Graphics(I) Basic 2 D and 3 D graphic functions n 2 D: ezplot(f) simplified graphic functions. By default [– 2π ≤ x ≤ 2π] q q q n n 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)', [t 1, t 2]); % plots with t 1<t<t 2 2 D: ezpolar(f) to plot in polar coordinates 3 D: ezplot 3 the same idea as ezplot but 3 D Example: main_graphics. m

2 D and 3 D Graphics (I) Selecting the axes scale n axis([x 0 x 1 y 0 y 1]) (2 D), axis([x 0 x 1 y 0 y 1 z 0 z 1]) (3 D) n axis auto: returns to the default scale n axis off: deactivates the axes labels. Axes, labels and grid disappear, axis on: activates it again. n axis equal: same scale factor for both axes n axis square: encloses the area delimited by the axes in a square. n To chose the labels on the axes: q q set(gca, ‘XTick’, -pi: pi/2, pi) %gca: get current axis set(gca, ‘XTicklabel’, ({‘-pi’, ’-pi/2’, 0, ’pi/2’, ’pi’})

2 D and 3 D Graphics (I) Functions to add titles to the graphic n 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: q q int 2 str(n) converts the value of the integer n to a character num 2 str(x) converts the value of a real or complex variable x to a character. Example: title(num 2 str(x)) n xlabel(‘text’) adds a label to the abscises axis. With xlabel off it disapppears. Same with ylabel(‘text’) or zlabel(‘text’) n 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. n gtext('text') places text with help of the mouse.

2 D and 3 D Graphics (I) Matlab functions for 2 D and 3 D graphics n Printing graphics: Print (File button on the graphic window) n Saving graphics: Save (File button on the graphic window): A. fig file is created, it can be re-edited and saved again. n Exporting graphics: Export (File button on the graphic window) n figure(n): calls to a new figure or to a figure already done. n close all deletes all figures, close(figure(n)) deletes one figure in particular.

2 D and 3 D Graphics (II) Drawing surfaces n n Creating a grid from two vectors [X, Y]=meshgrid(x, y) Drawing of the grid builton a surface Z(X, Y): q q n Graphic of the surface Z(X, Y): q q n n mesh(X, Y, Z), meshc(X, Y, Z) (also draws the level lines on the z=0 surface) 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 contour 3(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 3 D graphic of f(x, y). By default: – 2 p < x, y < 2 p. Example: main_surface_graphics. m and see in Demos: Graphics

2 D and 3 D Graphics (II) Drawing surfaces n Different ways of drawing colored polygons: q shading flat: shadows with flat color for each polygon. q shading interp: shadows with interpolated colors between corners of each polygon. q shading faceted: flat shadowing with superposed black lines (default option) n hidden off (deactivates the option of hidden lines), hidden on (activates it) n Manipulating graphics: q view(azimut, elev), view([xd, yd, zd]) q 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 q In graphic window: View (camera toolbar)

2 D and 3 D Graphics (III) Coordinate System Transformation n n n [ang, rad]=cart 2 pol(x, y), from cartesians to polars [ang, rad, z]=cart 2 pol(x, y, z), from cartesians to cylindric [x, y]=pol 2 cart(ang, rad), from polars to cartesians [x, y, z]=pol 2 cart(ang, rad, z), from cylindric to cartesians [angx, angz, rad]=cart 2 sph(x, y, z), from cartesians to spheric [x, y, z]=aph 2 cart(angx, angz, rad), from espheric to cartesians

Creating movies n A movie is made out of several images or frames n 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. n 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; end movie(M, 4, 6) n Example: main_movie. m

Matlab Files n Program files: Scripts They are built with a series of commands. The main file will be named main_name. m n Function files To create your own functions. They are called from within the scripts. q The first line is executable and starts with the word function as showed: function [output_arg 1, output_arg 2]=function_name(input_arg 1, input_arg 2, …, parameters) q n 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 n MATLAB allows the definition of functions directly from mathematic expressions using function inline n 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’); n Input and Output commands: n n 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 functions Function references n They asign a function to a variable. The operator @ is used. >> @reference_name=function_name n To evaluate a reference the function feval is used as follows [r 1, r 2, r 3, . . . ] = feval(reference_name, arg 1, arg 2, arg 3, . . . ) n Function references are very useful to give a function to other functions. Functions that execute other functions are called functions for functions. n Function references are variables of MATLAB, so they can be stored in matrices, for example. Example: main_functions_for_functions. m

Function for functions n fzero(@name_function, x 0): Calculates the zero of a function closest to the value of the variable x 0 n fminsearch(@name_function, x 0): calculates the relative minimun of a function closest to x 0 n fminbnd(@name_function, a, b): calculates a minimun of the function in the interval [a, b] Example: main_functions_for_functions. m

Programming Loops for k=n 1: incre: n 2 end for k=vector_column end while end Example: main_loops

Programming Conditional control structures n Logical operators: q >, <, >=, <=, == (equal) q | (or), &(and) q ~ (no), ~= (not equal) if end if else end Example: main_conditional if else end

Programming Structures of control condicionated: switch n switch is similar to a sequence of if. . . elseif switch_expresion=case_expr 3 %example switch_expresion case_expr 1, actions 1 case {case_expr 2, case_expr 3, case_expr 4, . . . } actions 2 otherwise, % option by default actions 3 end Example: main_conditional

Programming Interpolation n 1 D: q 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). q yi = interp 1(x, y, xi, method). Methods: ‘linear’ (linear interpolation), ’cubic’ (cubic), ’spline (cubic spline ) n 2 D: q matrix_Z=interp 2(X, Y, Z, matrix_X, matriz_Y, method). Methods: ’bilinear’ (linear interpolation), ’bicubic’ (cubic)

Numerical Analysis Integration n 1 D: quad, quadl: integrate a function in an interval [a, b] quad(@name_function, a, b) n 2 D: dblquad: integrate a function in an interval [xmin, xmax]x[ymin, ymax] dblquad(@sin, xmax, ymin, ymax)

Numerical Analysis Solving differential ecuations n Solving initial value problems for ordinate differential ecuations (ODEs) n [T, Y]=solver(@F, tspan, Y 0) q q solver: algorythm to solve ODEs, ode 45, ode 23, ode 113, ode 15 s, ode 23 s. F: function that has the differentical ecuations in matrix form Tspan: times vector [t 0 tfinal] for the integration. Y 0: column vector with the initial conditions in t 0

Exercise I Represent the functions: y 1= sin(3 π x)/ex y 2=cos(3π x)/ex with x between 0 and 3 π, obtaining only one figure like:

Exercise II a) Solve the equation system: 3 x+2 y-z=1 5 x+y+3 z=-2 3 y-4 z=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.
- Slides: 46