% -------------------------------------------------------------------------------- % M A T L A B T U T O R I A L % -------------------------------------------------------------------------------- % % Originally, this tutorial was started as an HTML document, the idea was % to create a comprehensive document which will introduce Matlab basics % to the newcomers. Also, it supposed to be as compact as possible, so the % reader would not be overwhelmed with unnecessary information. I really % didn't want to make just another one tutorial, which everyone can find % through the WEB. So, after I cut everything from my original document I % ended up with just some Matlab statements and some comments. Finally, I % decided to put this document into a different format, which, in my % opinion is more suitable - .m file. Now, it is a Matlab script you can % run and learn. % % Dmitry Yershov % % First what we will learn is comments. Every line, that starts with % % character is a comment, and Matlab simply ignores it. So, you can see, % that all my blah-blah by now is just a comments, and Matlab does not % care about it, but I still hope that someone else do. % % Second and not the least important thing, is getting help from Matlab % command line. Type help, and you will get a list of function % categories, with a short description for all of them. help % Then, suppose you are interested in general purpose commands in Matlab, % type help with a category name followed after white space, and you'll % get a list of functions in this category, again, with a short % description of what each function does. help general % Now, you finally are interested in "clear" command, and you want to % know more of what it does, and how it works. help clear % The line above will give you detailed description of "clear" command % -------------------------------------------------------------------------------- % Matrices and arrays in Matlab % -------------------------------------------------------------------------------- clear % Create a row vector of length 5 v = [1 0 -1 3 -2] % or v = [1, 0, -1, 3, -2] % Note: in my experience, there is no difference whether you use comas to % separate row values or whether you just use white spaces. % Create a column array of length 3 w = [-1; 1; 2] % Note: semicolons are important here. You have to use semicolon to % indicate a new row. % Create a 2x3 matrix A = [1 3 2; 3 2 1] % Creating sequences with ":" t = 0:10 % Note: t is a row vector that holds integers from 0 to 10 in the % increasing order. % Defining a step s = 0:0.1:10; % Note: s = [0 0.1 0.2 0.3 ... 10] or in other words operator works like % this first_element:step:last_element % % Note: semicolon in the end of the line prevents output % You also can use different functions to create vectors or matrices of % different sizes. Note, that row vector is a 1xN matrix and column % vector is Mx1 matrix. % let N = 5 M = 4 % define a zero NxM matrix B = zeros(N, M) % try Z = zeros(N) and see what the difference % random NxM matrix C = rand([N M]) % another equal way to define a matrix size % or NxM matrix with ones on the diagonal I = eye(N, M) % Vectors and matrices are stored as one- and two-dimensional array % correspondingly. To access array elements we use () with corresponding % index and indices s(51) I(3,3) % Matlab can operate on more then one- or two-dimensional arrays. For % example, we now create a 3D array. E = zeros(3, 3, 4) % and put 5 into (2,3,1) element E(2,3,1) = 5 % Getting dimensions and sizes ndims(E) % returns 3 size(B) % returns [N M], e.g. [5 4] length(s) % for vectors only % Extract diagonal vector diag(C) % Extract lower triangular part tril(C) % Extract upper triangular part triu(C) % diag is also can be used to generate diagonal matrix from the vector diag(w) % or even more interesting diag(diag(C)) % OK, now it's time to do some arithmetics % matrix addition B = I + C % matrix multiplication %D = B * C % Note: the error will occur in the line above, because "*" is considered % as a matrix multiplication by rules of linear algebra, so the number of % columns of the first matrix must agree with the number of rows of the % second one. To get element-wise multiplication we need to use ".*". For % example: D = B .* C % Note that ".+" and ".-" are the same as "+" and "-" for matrices. % Computing the action of a matrix on a vector is just a matrix-vector % product u = A * w % for right action x = v * D % for left action % Another important operation is getting transpose, which can be done by % using unary operation "dot-prime" or ".'". For example to compute the % squared norm of row vector v we type v * v.' % or we can transpose matrix A A.' % the "prime" character is used to get complex conjugate. Example M = [1 + i, -i; -2 - i, i] M.' M' % Note: we used built-in "i" variable to represent complex unit % (sqrt(-1)), although we could use "j" as well. % Note: be careful using this variable. Make sure, that it is not % overwritten by you before you used it. For example you may use "i" and % "j" in for-loop for array indexing. Then after the for-loop these two % variables will hold integers. Consider the following i = 2 j = 3 M = [1 + i, -i; -2 - i, i] % Compare resulting matrix M with the previous result. % -------------------------------------------------------------------------------- % Matlab built-in variables % -------------------------------------------------------------------------------- clear % Floating point bounds % machine precision (\epsilon_{mach}) eps % Largest positive floating point number realmax % Smallest positive floating point number realmin % Infinity inf % Not-a-Number nan % floating point functions isnan(nan) isinf(inf) isfinite(1.0) % Constants % Imaginary unit i j % pi - the ratio between circle length and its diameter pi % If you are not satisfied with output precision for floating point % numbers try the following format long e pi % see more with help format % -------------------------------------------------------------------------------- % Numerical Linear Algebra % -------------------------------------------------------------------------------- clear format % let A = [1 3 -6; 2 -4 3; -4 6 1] b = [3; 2; 1] % Euclidean and matrix norms norm(b) norm(A) % matrix rank rank(A) % rank can be applied to the vector as well rank(b) % determinant (only square matrices) det(A) % Trace trace(A) % Condition number cond(A) % Inverse matrix inv(A) % To solve the system Ax = b we can simply type x = inv(A) * b % or x = A \ b % more matrix functions (see help for details) % lu - LU factorization % qr - QR decomposition % eig - Eigenvalues and eigenvectors % svd - Singular value decomposition % poly - Characteristic polynomial % schur - Schur decomposition % ......... % -------------------------------------------------------------------------------- % Auxiliary functions % -------------------------------------------------------------------------------- clear % let t = 0:0.1:5; % The functions in this class can operate on arrays element-wise. For % example: y = sin(t); % will take sin function in all points of vector t and assign the result % into array y. The result is always the same number of dimensions and % size as the argument % Matlab library has a variety of different functions, here is the list of % categories and some function examples: % % TRIGONOMETRIC % sin, cos, tan, asin, acos, atan, sinh, cosh, ... % EXPONENTIAL % exp, log, log10, sqrt % COMPLEX % abs - Absolute value % angle - Phase angle % imag - Complex imaginary part % real - Complex real part % isreal - True for real array % ROUNDING % fix - Round towards zero % floor - Round towards minus infinity % ceil - Round towards plus infinity % round - Round towards nearest integer % mod - Modulus (signed remainder after division) % rem - Remainder after division % sign - Signum % DATA FUNCTIONS % max - Largest component % min - Smallest component % sort - Sort in ascending order % sortrows - Sort rows in ascending order % sum - Sum of elements % -------------------------------------------------------------------------------- % Plotting data % -------------------------------------------------------------------------------- % simple plot plot(t, y) % add more style plot(t, y, '-.k') % some more plotting functions % loglog - Log-log scale plot % semilogx - Semi-log scale plot % semilogy - Semi-log scale plot % polar - Polar coordinate plot % type hold on to hold previous graph on a plot, and all successive % graphs will be plotted on top hold on plot(t, sin(t + pi / 6.), '-r') plot(t, sin(t + pi / 4.), '--b') plot(t, sin(t + pi / 3.), ':m') % you can scale picture differently using axis function axis equal % we can add title to the graph title('sin function') % labels to the axes xlabel('t') ylabel('sin(t + \phi)') % Note: you can use LaTeX commands to format the text in Matlab % and the last but not the least - legend legend('\phi = 0', '\phi = \pi / 6', '\phi = \pi / 4', '\phi = \pi / 3') % you also can add text to the graph text(1, -1, 'pretty picture') % or use gtext to add text at cursor % and finally print your graph as a bitmap or vector drawing print -depsc -r300 'sin.eps' % you can use .eps file to embed it into % LaTeX document of your Homework print -dpng -r70 'sin.png' % you can use .png to embed your nice % graphs into your cool web page % hold off command will stop holding the graphs in a frame hold off % subplot makes several sub plots in one frame % Example: x = 0:0.1:2; subplot(1,2,1) plot(x, x.^2, '-ro') subplot(1,2,2) plot(x, sqrt(x), '-ms') % -------------------------------------------------------------------------------- % Matlab programming % -------------------------------------------------------------------------------- clear % Some Matlab programming structures, to program with .m files % For loops for k = 1:5 2^k end % note that 1:5 = [1 2 3 4 5], so we can use any vector x = [1.5 2 4.5 8] for k = x 2^k end % while loop k = 0 while (k < 10) k = k + 1 if k == 3 continue end 2^k if k == 5 break end end % Note: we have used conditional operator "<", also other relational % operators are available, such as ">", "==", ">=", "<=", and "~=" % conditional statement if x = 1 y = 2 z = 1.333 if (x < y) k = 1; elseif (y > z) k = 2; else k = 3; end % conditional statement switch switch k case 1 disp('x < y') case 2 disp('x >= y and y > z ') otherwise disp('x >= y and y <= z ') end % -------------------------------------------------------------------------------- % Polynomials and Interpolation % -------------------------------------------------------------------------------- help polyfun % Spline interpolation % spline - Cubic spline interpolation % ppval - Evaluate piecewise polynomial % Polynomials % roots - Find polynomial roots % poly - Convert roots to polynomial % polyval - Evaluate polynomial % polyvalm - Evaluate polynomial with matrix argument % polyfit - Fit polynomial to data % polyder - Differentiate polynomial % polyint - Integrate polynomial analytically % conv - Multiply polynomials % deconv - Divide polynomials % -------------------------------------------------------------------------------- % Functions of a functions % -------------------------------------------------------------------------------- help funfun % Function functions and ODE solvers % Optimization and root finding % fminbnd - Scalar bounded nonlinear function minimization % fminsearch - Multidimensional unconstrained nonlinear minimization % fzero - Scalar nonlinear zero finding % Numerical integration (quadrature) % quad - Numerically evaluate integral, low order method % quadl - Numerically evaluate integral, higher order method % Differential equation solvers % ode45 - Solve non-stiff differential equations, medium order method % ode23 - Solve non-stiff differential equations, low order method % Boundary value problem solver for ODEs % bvp4c - Solve two-point boundary value problems for ODEs by collocation % 1D Partial differential equation solver % pdepe - Solve initial-boundary value problems for parabolic-elliptic PDEs