034IN "Fundamentals of Automatic Control" - Introduction to MATLAB

Part 5 - Visualization and Programming

This is the fifth MATLAB live script of the collection 034IN "Fundamentals of Automatic Control" - Introduction to MATLAB, devoted to introduce the MATLAB environment and tools for solving practical problems related to the topics of the 034IN course, i.e. performance analysis of dynamic systems, design of control law for continuous-time linear dynamical systems, approximate discretization of a continuous-time control law etc.
Use this link to go back to the main live script of the collection.
Table of Contents

Objectives

The aim of this live script is to illustrate
What you should know by the end of this module:

Visualization: An Introduction

Being able to visualize the solution of a differential equation (linear, with constant coefficients), the evolution over time of an LTI system starting from assigned initial conditions and subjected to various external stimuli, or the system's frequency response, will allow us to obtain a lot of useful information about the dynamic system we are analyzing.
How then can we visualize data in MATLAB?

With a Little Help from the 'help' Command!

Here is a list of the main categories of topics, available with the help command, related to the visualisation of data using MATLAB
Two dimensional graphs
help graph2d
Two dimensional graphs. Elementary X-Y graphs. plot - Linear plot. loglog - Log-log scale plot. semilogx - Semi-log scale plot. semilogy - Semi-log scale plot. polar - Polar coordinate plot. plotyy - Graphs with y tick labels on the left and right. Axis control. axis - Control axis scaling and appearance. zoom - Zoom in and out on a 2-D plot. grid - Grid lines. box - Axis box. rbbox - Rubberband box. hold - Hold current graph. axes - Create axes in arbitrary positions. subplot - Create axes in tiled positions. Graph annotation. plotedit - Tools for editing and annotating plots. title - Graph title. xlabel - X-axis label. ylabel - Y-axis label. texlabel - Produces the TeX format from a character string. text - Text annotation. gtext - Place text with mouse. Hardcopy and printing. print - Print graph or Simulink system; or save graph to MATLAB file. printopt - Printer defaults. orient - Set paper orientation. See also graph3d, specgraph.
Three dimensional graphs
help graph3d
Three dimensional graphs. Elementary 3-D plots. plot3 - Plot lines and points in 3-D space. mesh - 3-D mesh surface. surf - 3-D colored surface. fill3 - Filled 3-D polygons. Color control. colormap - Color look-up table. caxis - Pseudocolor axis scaling. shading - Color shading mode. hidden - Mesh hidden line removal mode. brighten - Brighten or darken colormap. colordef - Set color defaults. graymon - Set graphics defaults for gray-scale monitors. cmpermute - Rearrange colors in colormap. cmunique - Eliminate unneeded colors in colormap of indexed image. imapprox - Approximate indexed image by one with fewer colors. Lighting. surfl - 3-D shaded surface with lighting. lighting - Lighting mode. material - Material reflectance mode. specular - Specular reflectance. diffuse - Diffuse reflectance. surfnorm - Surface normals. Transparency. alpha - Transparency (alpha) mode. alphamap - Transparency (alpha) look-up table. alim - Transparency (alpha) scaling Axis control. axis - Control axis scaling and appearance. zoom - Zoom in and out on a 2-D plot. grid - Grid lines. box - Axis box. hold - Hold current graph. axes - Create axes in arbitrary positions. subplot - Create axes in tiled positions. daspect - Data aspect ratio. pbaspect - Plot box aspect ratio. xlim - X limits. ylim - Y limits. zlim - Z limits. Viewpoint control. view - 3-D graph viewpoint specification. viewmtx - View transformation matrix. rotate3d - Interactively rotate view of 3-D plot. Camera control. campos - Camera position. camtarget - Camera target. camva - Camera view angle. camup - Camera up vector. camproj - Camera projection. High level camera control. camorbit - Orbit camera. campan - Pan camera. camdolly - Dolly camera. camzoom - Zoom camera. camroll - Roll camera. camlookat - Move camera and target to view specified objects. cameratoolbar - Interactively manipulate camera. High level light control. camlight - Creates or sets position of a light. lightangle - Spherical position of a light. Graph annotation. title - Graph title. xlabel - X-axis label. ylabel - Y-axis label. zlabel - Z-axis label. text - Text annotation. gtext - Mouse placement of text. plotedit - Experimental graph editing and annotation tools. Hardcopy and printing. print - Print graph or Simulink system; or save graph to MATLAB file. printopt - Printer defaults. orient - Set paper orientation. See also graph2d, specgraph.
More information about data visualization using MATLAB is available online

A Simple Example

Consider the variable
where the time constant τ is
clear % clean the MATLAB workspace
close all
clc
 
Tau_days = 1.5;
 
secPerDay = 60*60*24;
tau = Tau_days * secPerDay;
 
% let's define the time row array tVec
startT = 0;
endT = 648000;
Nsamples = 10000;
 
tVec = linspace(startT, endT, Nsamples);
 
% evaluate the function using the time row-vector
y_vals = (1-exp(-tVec/tau));
 
figure('Units','normalized','Position',[0.1,0.1, 0.9, 0.9])
plot(tVec, y_vals, 'LineStyle','-', 'LineWidth', 2.5);
grid on
xlim([min(tVec), max(tVec)]);
xlabel('time $t$ [s]', 'Interpreter', 'latex', 'FontSize',14);
ylabel('function $y(t)$', 'Interpreter','latex', 'FontSize',14);
How to display more than one function graph in the same window?
tau2 = 2* tau;
tau10 = tau*10;
tau10th = tau/10;
 
% evaluate the functions using the time row-vector
y_vals2 = (1-exp(-tVec/tau2));
y_vals10 = (1-exp(-tVec/tau10));
y_vals10th = (1-exp(-tVec/tau10th));
 
figure('Units','normalized','Position',[0.1,0.1, 0.9, 0.9])
plot(tVec, y_vals, 'LineStyle','-', 'LineWidth', 1.5);
 
hold on; % we can now insert more graphs without deleting the previous ones
 
plot(tVec, y_vals2, 'LineStyle','--', 'LineWidth', 1.5);
plot(tVec, y_vals10, 'LineStyle','-.', 'LineWidth', 1.5);
plot(tVec, y_vals10th, 'LineStyle',':', 'LineWidth', 1.5);
 
% Note: A different line style is selected for each graph.
% The color of each graph was chosen automatically,
% cycling through 8 available colors (use the
% help plot command for more information).
 
grid on
 
xlim([min(tVec), max(tVec)]);
xlabel('time $t$ [s]', 'Interpreter', 'latex', 'FontSize',14);
ylabel('function $y(t)$', 'Interpreter','latex', 'FontSize',14);
 
legend('$\tau = \bar \tau$', '$\tau = 2 \bar \tau$',...
'$\tau = 10 \bar \tau$', '$\tau = \bar{\tau}/10$', ...
'Interpreter', 'latex', 'FontSize', 14, ...
'Location', 'best')

Another Example: 3D Line Plot

time=0:0.001:4*pi;
x=sin(time);
y=cos(time);
z=time;
 
figure('Units','normalized','Position',[0.1,0.1, 0.9, 0.9])
plot3(x,y,z,'k','LineWidth',2);
grid on
zlabel('Time');ylabel('y'); xlabel('x');
help xlim
help ylim
help zlim

Programming: An Introduction

Functions are an essential mechanism for grouping a sequence of frequently used MATLAB commands to perform a specific task. Examples include all the standard mathematical functions such as sin, cos, tan, exp, log, sqrt, abs and many others. MATLAB also offers the possibility of defining custom functions. In this live script, we will only look at the simplest way of doing this, using anonymous functions. This is essential for problems such as solving non-linear equations, integrating a function and minimizing or maximizing a function. One of the great powers of MATLAB is the ability to apply functions to vectors and matrices with any number of elements in a single call.

With a Little Help from the 'help' Command!

Here is a list of the main categories of topics, available with the help command, related to general purpose commands, operators and special characters, programming language constructs, character strings, file input/output, time and dates
General purpose commands
help general
General purpose commands. MATLAB Version 25.2 (R2025b) 28-Jul-2025 General information. syntax - Help on MATLAB command syntax. demo - Run demonstrations. ver - MATLAB, Simulink and toolbox version information. version - MATLAB version information. verLessThan - Compare version of toolbox to specified version string. logo - Plot the L-shaped membrane logo with MATLAB lighting. membrane - Generates the MATLAB logo. bench - MATLAB Benchmark. Managing the workspace. who - List current variables. whos - List current variables, long form. clear - Clear variables and functions from memory. onCleanup - Specify cleanup work to be done on function completion. Pack - Consolidate workspace memory. load - Load workspace variables from disk. save - Save workspace variables to disk. saveas - Save Figure or model to desired output format. quit - Quit MATLAB session. exit - Exit from MATLAB. Managing commands and functions. what - List MATLAB-specific files in directory. type - Display MATLAB program file. open - Open files by extension. which - Locate functions and files. pcode - Create pre-parsed pseudo-code file (P-file). mex - Compile MEX-function. inmem - List functions in memory. namelengthmax - Maximum length of MATLAB function or variable name. Managing the search path. path - Get/set search path. addpath - Add directory to search path. rmpath - Remove directory from search path. rehash - Refresh function and file system caches. import - Import packages into the current scope. finfo - Identify file type against standard file handlers on path. genpath - Generate recursive toolbox path. savepath - Save the current MATLAB path in the pathdef.m file. Managing the java search path. javaaddpath - Add directories to the dynamic java path. javaclasspath - Get and set java path. javarmpath - Remove directory from dynamic java path. Controlling the command window. echo - Display statements during function execution. more - Control paged output in command window. diary - Save text of MATLAB session. format - Set output format. beep - Produce beep sound. desktop - Start and query the MATLAB Desktop. preferences - Bring up MATLAB user settable preferences dialog. Operating system commands. cd - Change current working directory. pwd - Show (print) current working directory. perl - Execute Perl command and return the result. Debugging. debug - List debugging commands. Loading and calling shared libraries. calllib - Call a function in an external library. libpointer - Creates a pointer object for use with external libraries. libstruct - Creates a structure pointer for use with external libraries. libisloaded - True if the specified shared library is loaded. loadlibrary - Load a shared library into MATLAB. libfunctions - Return information on functions in an external library. libfunctionsview - View the functions in an external library. unloadlibrary - Unload a shared library loaded with LOADLIBRARY. java - Using Java from within MATLAB. usejava - True if the specified Java feature is supported in MATLAB. See also lang, DataTypes, iofun, graphics, ops, strfun, timefun, matfun, demos, graphics, datafun, uitools, doc, punct. Control System Toolbox -- General Utilities. (R2025b) 28-Jul-2025 abcdchk - Check consistency of A,B,C,D matrices. db2mag - Convert magnitude from absolute value to dB. mag2db - Convert magnitude from dB to absolute value. padecoef - Pade approximation of time delays. residue - Partial-fraction expansion (residues). resi2 - Residue of a repeated pole. ss2tf - Convert state-space system to transfer function. ss2zp - Convert state-space system to zero-pole. tf2ss - Convert transfer function to state-space. tf2zp - Convert transfer function to zero-pole. tfchk - Check for proper transfer function. zp2ss - Convert zero-pole system to state-space. zp2tf - Convert zero-pole system to transfer function. Folders named general
Operators and special characters
help ops
Operators and special characters. Arithmetic operators. plus - Plus + uplus - Unary plus + minus - Minus - uminus - Unary minus - mtimes - Matrix multiply * times - Array multiply .* power - Array power .^ mldivide - Backslash or left matrix divide \ mrdivide - Slash or right matrix divide / ldivide - Left array divide .\ rdivide - Right array divide ./ idivide - Integer division with rounding option. kron - Kronecker tensor product pagemtimes - Page-wise matrix multiply pagetranspose - Page-wise transpose pagectranspose - Page-wise complex conjugate transpose pagemldivide - Page-wise left matrix divide pagemrdivide - Page-wise right matrix divide tensorprod - Tensor products between two tensors Relational operators. eq - Equal == ne - Not equal ~= lt - Less than < gt - Greater than > le - Less than or equal <= ge - Greater than or equal >= isapprox - Equal within a tolerance Logical operators. and - Element-wise logical AND & or - Element-wise logical OR | not - Logical NOT ~ punct - Ignore function argument or output ~ xor - Logical EXCLUSIVE OR any - True if any element of vector is nonzero all - True if all elements of vector are nonzero Special characters. colon - Colon : paren - Parentheses and subscripting ( ) paren - Brackets [ ] paren - Braces and subscripting { } punct - Function handle creation @ punct - Decimal point . punct - Structure field access . punct - Parent directory .. punct - Continuation ... punct - Separator , punct - Semicolon ; punct - Comment % punct - Invoke operating system command ! punct - Assignment = punct - Quote ' punct - Double quote " transpose - Transpose .' ctranspose - Complex conjugate transpose ' horzcat - Horizontal concatenation [,] vertcat - Vertical concatenation [;] subsasgn - Subscripted assignment ( ),{ },. subsref - Subscripted reference ( ),{ },. numArgumentsFromSubscript - Number of arguments for indexing methods subsindex - Subscript index metaclass - Metaclass for MATLAB class ? Bitwise operators. bitand - Bit-wise AND. bitcmp - Complement bits. bitor - Bit-wise OR. bitxor - Bit-wise XOR. bitset - Set bit. bitget - Get bit. bitshift - Bit-wise shift. Set operators. union - Set union. unique - Set unique. intersect - Set intersection. setdiff - Set difference. setxor - Set exclusive-or. allunique - True for sets with all unique members. ismember - True for set member. numunique - Number of unique set members. See also function_handle.
Programming language constructs
help lang
Programming language constructs. Control flow. if - Conditionally execute statements. else - Execute statement if previous IF condition failed. elseif - Execute if previous IF failed and condition is true. end - Terminate scope of control statements. for - Repeat statements a specific number of times. parfor - Parallel FOR-loop. while - Repeat statements an indefinite number of times. break - Terminate execution of WHILE or FOR loop. continue - Pass control to the next iteration of a loop. switch - Switch among several cases based on expression. case - SWITCH statement case. otherwise - Default SWITCH statement case. try - Begin TRY block. catch - Begin CATCH block. return - Return to invoking function. error - Display message and abort function. MException - Constructs MATLAB exception object. assert - Generate an error when a condition is violated. rethrow - Reissue error. Evaluation and execution. eval - Execute string with MATLAB expression. evalc - Evaluate MATLAB expression with capture. feval - Execute the specified function. evalin - Evaluate expression in workspace. builtin - Execute built-in function from overloaded method. assignin - Assign variable in workspace. run - Run script. Scripts, functions, classes, and variables. script - About MATLAB script files. function - Add new function. global - Define global variable. persistent - Define persistent variable. mfilename - Name of currently executing MATLAB code file. lists - Comma separated lists. exist - Check if variables or functions are defined. mlock - Prevents clearing function from memory. munlock - Allow clearing function from memory. mislocked - Determine if function is locked in memory. precedence - Operator Precedence in MATLAB. isvarname - True for valid variable name. iskeyword - Check if input is a keyword. javachk - Validate level of Java support. genvarname - Construct a valid MATLAB variable name from a string. classdef - Define a new class or subclass. Argument handling. nargchk - Validate number of input arguments. nargoutchk - Validate number of output arguments. nargin - Number of function input arguments. nargout - Number of function output arguments. varargin - Variable length input argument list. varargout - Variable length output argument list. inputname - Input argument name. inputParser - Construct input parser object. validateattributes - Check validity of array. validatestring - Check validity of text. ans - Most recent answer. arguments - Declare function argument validation. Message display. warning - Display warning message. lastwarn - Last warning message. disp - Display array. display - Display array. details - Display array. Interactive input. input - Prompt for user input. keyboard - Invoke keyboard from MATLAB code file. Abstract superclasses. handle - Superclass of all handle classes. dynamicprops - Support for dynamic properties. See also general, iofun, ops, DataTypes, matfun, funfun, elfun, polyfun. Parallel computing programming language constructs. Single program multiple data support spmd - Single Program Multiple Data Composite - Construct a Composite object Map Reduce Framework mapreduce - Solve out-of-memory problems with the MapReduce framework. See also parallel, parallel/parallel, parfor, parpool.
Character strings
help strfun
Character arrays and strings. Conversion functions. char - Convert to a character array. double - Convert to a double array. string - Convert to a string array. strings - Create string array with no characters. cellstr - Convert to a cell array of character vectors. blanks - Character vector of spaces. Text determination functions. iscellstr - True for cell array of character vectors. ischar - True for character array. isstring - True for string array. isstrprop - Check whether elements are of a specified category. String operations. compose - Converts data into formatted string arrays. contains - True if pattern is found. count - Number of occurrences of a pattern. deblank - Remove trailing whitespaces. endsWith - True if string ends with pattern. erase - Remove substring from string elements. eraseBetween - Remove bounded substrings. extractAfter - Extract substring after a specified position. extractBefore - Extract substring before a specified position. extractBetween - Extract bounded substrings. insertAfter - Insert substring after a specified position. insertBefore - Insert substring before a specified position. join - Append string elements. lower - Convert string to lowercase. pad - Insert leading and trailing spaces. regexp - Match regular expression. regexpi - Match regular expression, ignoring case. regexprep - Replace string using regular expression. replace - Find and replace substring. replaceBetween - Replace bounded substrings. reverse - Reverse the order of characters. split - Split strings at delimiter. splitlines - Split strings at newlines. startsWith - True if string starts with pattern. strsplit - Split strings at delimiter. strjoin - Append string elements. strcat - Append strings together. strcmp - Compare strings. strncmp - Compare first N characters. strcmpi - Compare strings ignoring case. strncmpi - Compare first N characters ignoring case. strfind - Find one string within another. strip - Remove leading and trailing whitespaces. strjust - Justify character array. strlength - Lengths of string elements. strrep - Find and replace substring. strtok - Split string into tokens. strtrim - Remove leading and trailing whitespaces. upper - Convert string to uppercase. Character set conversion. native2unicode - Convert bytes to Unicode characters. unicode2native - Convert Unicode characters to bytes. Conversion between text and numbers. double - Convert to a double array. int2str - Convert integer to character vector. mat2str - Convert a 2-D matrix to a character vector in MATLAB syntax. num2str - Convert numbers to a character vector. str2double - Convert string to double precision value. str2num - Convert character vector to numeric array. string - Convert to string array. sprintf - Write formatted data to string. sscanf - Read string under format control. Base number conversion. hex2num - Convert hexadecimal string to double precision number. hex2dec - Convert hexadecimal string to decimal integer. dec2hex - Convert decimal integer to hexadecimal string. bin2dec - Convert binary string to decimal integer. dec2bin - Convert decimal integer to a binary string. base2dec - Convert base B string to decimal integer. dec2base - Convert decimal integer to base B string. num2hex - Convert singles and doubles to IEEE hexadecimal strings. See also general, lang, iofun, ops, DataTypes.
File input/output
help iofun
Spreadsheet IO Functions (Not Recommended) xlsread - (Not recommended) Read spreadsheet file xlswrite - (Not recommended) Write spreadsheet file xlsfinfo - (Not recommended) Determine if file contains Microsoft Excel spreadsheet Contents of text/iofun (Not Recommended) csvread - (Not recommended) Read comma-separated value (CSV) file. csvwrite - (Not recommended) Write comma-separated value file. dlmread - (Not recommended) Read ASCII-delimited file of numeric data into matrix. dlmwrite - (Not recommended) Write matrix to ASCII-delimited file. textread - (Not Recommended) Read data from text file; write to multiple outputs. Contents of tabular/iofun: Import/Export Functions readtable - Create table from file. readtimetable - Create timetable from file. readmatrix - Read matrix from file. readcell - Create cell array from file. readvars - Read variables from file. writetable - Write table to file. writetimetable - Write timetable to file. writematrix - Write a matrix to a file. writecell - Write cell array to file. writelines - Write text to file. Import Options detectImportOptions - Create import options based on file content delimitedTextImportOptions - Import options object for delimited text files fixedWidthImportOptions - Import options object for fixed-width text files spreadsheetImportOptions - Import options object for Spreadsheet files xmlImportOptions - Import options object for XML files htmlImportOptions - Import options object for HTML files wordDocumentImportOptions - Import options object for Microsoft Word document files Contents of matlab/iofun: Import Functions daqread - Read Data Acquisition Toolbox (.daq) data file. importdata - Load data from file. matfile - Save and load parts of variables in MAT-files. matfinfo - Text description of MAT-file contents. Internet Services sendmail - Send e-mail. urlread - Download URL content to character vector. (not recommended) urlwrite - Download URL content and save to file. (not recommended) callSoapService - Send a SOAP message off to an endpoint. createClassFromWsdl - Create a MATLAB object based on a WSDL-file. createSoapMessage - Create a SOAP message, ready to send to the server. parseSoapResponse - Convert the response from a SOAP server into MATLAB types. Path and Configuration matlabroot - Root directory of MATLAB installation. deployprefdir - Get the MATLAB preferences directory for a deployed component. prefdir - Preference directory name. partialpath - Partial pathnames. pathsep - Path separator for this platform. Command Window home - Send the cursor home. clc - Clear command window.
Time and dates
help timefun
Timing functions. cputime - CPU time in seconds. tic - Start stopwatch timer. toc - Stop stopwatch timer. etime - Elapsed time. pause - Wait in seconds.
Refer to the online courses on MATLAB Onramp, MATLAB Fundamentals and MATLAB Programming Techniques for more information.

Here is a list of the main categories of topics, available with the help command, related to the predefined and custom functions
Elementary math functions
help elfun
Elementary math functions. Trigonometric. sin - Sine. sind - Sine of argument in degrees. sinh - Hyperbolic sine. asin - Inverse sine. asind - Inverse sine, result in degrees. asinh - Inverse hyperbolic sine. cos - Cosine. cosd - Cosine of argument in degrees. cosh - Hyperbolic cosine. acos - Inverse cosine. acosd - Inverse cosine, result in degrees. acosh - Inverse hyperbolic cosine. tan - Tangent. tand - Tangent of argument in degrees. tanh - Hyperbolic tangent. atan - Inverse tangent. atand - Inverse tangent, result in degrees. atan2 - Four quadrant inverse tangent. atan2d - Four quadrant inverse tangent, result in degrees. atanh - Inverse hyperbolic tangent. sec - Secant. secd - Secant of argument in degrees. sech - Hyperbolic secant. asec - Inverse secant. asecd - Inverse secant, result in degrees. asech - Inverse hyperbolic secant. csc - Cosecant. cscd - Cosecant of argument in degrees. csch - Hyperbolic cosecant. acsc - Inverse cosecant. acscd - Inverse cosecant, result in degrees. acsch - Inverse hyperbolic cosecant. cot - Cotangent. cotd - Cotangent of argument in degrees. coth - Hyperbolic cotangent. acot - Inverse cotangent. acotd - Inverse cotangent, result in degrees. acoth - Inverse hyperbolic cotangent. hypot - Square root of sum of squares. deg2rad - Convert angles from degrees to radians. rad2deg - Convert angles from radians to degrees. Exponential. exp - Exponential. expm1 - Compute exp(x)-1 accurately. log - Natural logarithm. log1p - Compute log(1+x) accurately. log10 - Common (base 10) logarithm. log2 - Base 2 logarithm and dissect floating point number. pow2 - Base 2 power and scale floating point number. realpow - Power that will error out on complex result. reallog - Natural logarithm of real number. realsqrt - Square root of number greater than or equal to zero. sqrt - Square root. nthroot - Real n-th root of real numbers. nextpow2 - Next higher power of 2. Complex. abs - Absolute value. angle - Phase angle. complex - Construct complex data from real and imaginary parts. conj - Complex conjugate. imag - Complex imaginary part. real - Complex real part. unwrap - Unwrap phase angle. isreal - True for real array. cplxpair - Sort numbers into complex conjugate pairs. Rounding and remainder. 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.
Specialized math functions
help specfun
Specialized math functions. Specialized math functions. airy - Airy functions. besselj - Bessel function of the first kind. bessely - Bessel function of the second kind. besselh - Bessel functions of the third kind (Hankel function). besseli - Modified Bessel function of the first kind. besselk - Modified Bessel function of the second kind. beta - Beta function. betainc - Incomplete beta function. betaincinv - Inverse incomplete beta function. betaln - Logarithm of beta function. ellipj - Jacobi elliptic functions. ellipke - Complete elliptic integral. erf - Error function. erfc - Complementary error function. erfcx - Scaled complementary error function. erfinv - Inverse error function. erfcinv - Inverse complementary error function. expint - Exponential integral function. gamma - Gamma function. gammainc - Incomplete gamma function. gammaincinv - Inverse incomplete gamma function. gammaln - Logarithm of gamma function. psi - Psi (polygamma) function. legendre - Associated Legendre function. cross - Vector cross product. dot - Vector dot product. Number theoretic functions. factor - Prime factors. isprime - True for prime numbers. primes - Generate list of prime numbers. gcd - Greatest common divisor. lcm - Least common multiple. rat - Rational approximation. rats - Rational output. perms - All possible permutations. nchoosek - All combinations of N elements taken K at a time. factorial - Factorial function. Coordinate transforms. cart2sph - Transform Cartesian to spherical coordinates. cart2pol - Transform Cartesian to polar coordinates. pol2cart - Transform polar to Cartesian coordinates. sph2cart - Transform spherical to Cartesian coordinates. hsv2rgb - Convert hue-saturation-value colors to red-green-blue. rgb2hsv - Convert red-green-blue colors to hue-saturation-value.
Interpolation and polynomials
help polyfun
Interpolation and polynomials. Data interpolation. interp1 - 1-D interpolation (table lookup). interpft - 1-D interpolation using FFT method. interp2 - 2-D interpolation (table lookup). interp3 - 3-D interpolation (table lookup). interpn - N-D interpolation (table lookup). griddata - Data gridding and surface fitting. griddatan - Data gridding and hyper-surface fitting (dimension >= 2). scatteredInterpolant - Interpolant for scattered data griddedInterpolant - Interpolant for gridded data Cubic interpolation. makima - Modified Akima cubic Hermite interpolation. pchip - Piecewise cubic Hermite interpolating polynomial. spline - Cubic spline interpolation. ppval - Evaluate piecewise polynomial. Geometric analysis. boundary - Boundary of a set of points in 2D/3D space delaunay - Delaunay triangulation. delaunayn - N-D Delaunay triangulation. dsearchn - Search N-D Delaunay triangulation for nearest point. tsearchn - N-D closest triangle search. convhull - Convex hull. convhulln - N-D convex hull. voronoi - Voronoi diagram. voronoin - N-D Voronoi diagram. inpolygon - True for points inside polygonal region. rectint - Rectangle intersection area. polyarea - Area of polygon. Shape Representation alphaShape - Alpha Shape in 2D and 3D alphaSpectrum - Sorted vector of alpha values giving distinct shapes criticalAlpha - Alpha value defining a critical transition in the shape numRegions - Number of regions in the shape inShape - Test whether a point is within the alpha shape alphaTriangulation - Triangulation that fills the alpha shape boundaryFacets - Boundary facets of alpha shape perimeter - Perimeter of a 2D alpha shape area - Area of a 2D alpha shape surfaceArea - Surface area of a 3D alpha shape volume - Volume of a 3D alpha shape plot - Plot an alpha shape nearestNeighbor - Nearest point on the alpha shape boundary Triangulation Representation. triangulation - A Triangulation Representation triangulation/barycentricToCartesian - Converts the coordinates of a point from barycentric to cartesian triangulation/cartesianToBarycentric - Converts the coordinates of a point from cartesian to barycentric triangulation/circumcenter - Circumcenter of triangle or tetrahedron triangulation/edges - Triangulation edges triangulation/edgeAttachments - Triangles or tetrahedra attached to an edge triangulation/faceNormal - Triangulation face normal triangulation/featureEdges - Triangulation sharp edges triangulation/freeBoundary - Triangulation facets referenced by only one triangle or tetrahedron triangulation/incenter - Incenter or triangle or tetrahedron triangulation/isConnected - Test if a pair of vertices is connected by an edge triangulation/neighbors - Neighbors to a triangle or tetrahedron triangulation/size - Returns the size of the Triangulation matrix triangulation/vertexAttachments - Triangles or tetrahedra attached to a vertex triangulation/vertexNormal - Triangulation vertex normal triangulation/nearestNeighbor - Vertex closest to a specified point triangulation/pointLocation - Triangle or tetrahedron containing a specified point Delaunay Triangulation. delaunayTriangulation - Delaunay triangulation in 2-D and 3-D delaunayTriangulation/convexHull - Convex hull delaunayTriangulation/isInterior - Test if a triangle is in the interior of a 2-D constrained Delaunay triangulation delaunayTriangulation/voronoiDiagram - Voronoi diagram 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.
Function functions and ODE solvers
help funfun
Function functions and ODE solvers. Numerical integration (quadrature). integral - Numerically evaluate integral. integral2 - Numerically evaluate double integral. integral3 - Numerically evaluate triple integral. quad - Numerically evaluate integral, low order method. quadgk - Numerically evaluate integral, adaptive Gauss-Kronrod quadrature. quadl - Numerically evaluate integral, higher order method. quadv - Vectorized QUAD. quad2d - Numerically evaluate double integral over a planar region. dblquad - Numerically evaluate double integral over a rectangle. triplequad - Numerically evaluate triple integral. Plotting. ezplot - Easy to use function plotter. ezplot3 - Easy to use 3-D parametric curve plotter. ezpolar - Easy to use polar coordinate plotter. ezcontour - Easy to use contour plotter. ezcontourf - Easy to use filled contour plotter. ezmesh - Easy to use 3-D mesh plotter. ezmeshc - Easy to use combination mesh/contour plotter. ezsurf - Easy to use 3-D colored surface plotter. ezsurfc - Easy to use combination surf/contour plotter. fplot - Plot function. Inline function object. inline - Construct INLINE function object. argnames - Argument names. formula - Function formula. char - Convert INLINE object to character array. Differential equation solvers. Initial value problem solvers for ODEs. (If unsure about stiffness, try ODE45 first, then ODE15S.) ode45 - Solve non-stiff differential equations, medium order method. ode23 - Solve non-stiff differential equations, low order method. ode113 - Solve non-stiff differential equations, variable order method. ode23t - Solve moderately stiff ODEs and DAEs Index 1, trapezoidal rule. ode15s - Solve stiff ODEs and DAEs Index 1, variable order method. ode23s - Solve stiff differential equations, low order method. ode23tb - Solve stiff differential equations, low order method. Initial value problem solver for fully implicit ODEs/DAEs F(t,y,y')=0. decic - Compute consistent initial conditions. ode15i - Solve implicit ODEs or DAEs Index 1. Initial value problem solver for delay differential equations (DDEs). dde23 - Solve delay differential equations (DDEs) with constant delays. ddesd - Solve delay differential equations (DDEs) with variable delays. ddensd - Solve delay differential equations (DDEs) of neutral type. Boundary value problem solver for ODEs. bvp4c - Solve boundary value problems by collocation, 3-stage Lobatto formula. bvp5c - Solve boundary value problems by collocation, 4-stage Lobatto formula. 1D Partial differential equation solver. pdepe - Solve initial-boundary value problems for parabolic-elliptic PDEs. Option handling. odeset - Create/alter ODE OPTIONS structure. odeget - Get ODE OPTIONS parameters. ddeset - Create/alter DDE OPTIONS structure. ddeget - Get DDE OPTIONS parameters. bvpset - Create/alter BVP OPTIONS structure. bvpget - Get BVP OPTIONS parameters. Input and Output functions. deval - Evaluates the solution of a differential equation problem. odextend - Extends the solutions of a differential equation problem. odeplot - Time series ODE output function. odephas2 - 2-D phase plane ODE output function. odephas3 - 3-D phase plane ODE output function. odeprint - Command window printing ODE output function. bvpinit - Forms the initial guess for BVP4C and BVP5C. bvpxtend - Forms a guess structure for extending BVP solution. pdeval - Evaluates by interpolation the solution computed by PDEPE.

Polynomials in MATLAB

clear variables

Introduction

To represent polynomials, MATLAB uses numeric row vectors, which contain the coefficients of the polynomial, ordered by decreasing power.
For example, the polynomial
corresponds to the MATLAB row vector
p = [4, 8, 15, 16, 23, 42];

Important Remarks

Examples

The representation in MATLAB of the polynomial is the row-vector
q = [1 -4 3 -1 12];
 
degree_q = numel(q)-1
degree_q = 4
The row vector
px = [4 -4 1];
corresponds to the second order polynomial .
Given the polynomials
the corresponding descriptions in MATLAB are the row vectors
p_tildeX = [3 0 0 81];
 
bar_qX = [42 0 16 0 4];

Evaluation of Polynomials

Given the description of a polynomial , how can the polynomial be evaluated at a specific value? For example, how do we compute ?
Use the MATLAB command polyval:
clear p
 
p = [1 -4 0 -1 0]; % the coefficient of the polynomial p(x)
 
xVAL = 42;
pVAL = polyval(p, xVAL)
pVAL = 2815302

Roots of a Polynomial

Given the polynomial , described by means of the row vector containing the polynomial coefficients, you can determine the roots of using the MATLAB command roots:
p1 = [1 -1 -6];
roots(p1)
ans = 2×1
3 -2
 
p2 = [1 0 -4 0 4 ];
roots(p2)
ans = 4×1 complex
-1.414213562373094 + 0.000000029994132i -1.414213562373094 - 0.000000029994132i 1.414213575565480 + 0.000000000000000i 1.414213549180710 + 0.000000000000000i
What about the inverse problem? Given the roots of a polynomial, how can you determine the coefficients' vector?
Use the MATLAB function poly:
clear px
 
px = [3 0 24 0 48];
r_px = roots(px)
r_px = 4×1 complex
-0.000000000021964 + 2.000000013342683i -0.000000000021964 - 2.000000013342683i 0.000000000021963 + 1.999999986657315i 0.000000000021963 - 1.999999986657315i
 
px_1 = poly(r_px)
px_1 = 1×5
1.000000000000000 0.000000000000001 7.999999999999990 0.000000000000003 15.999999999999959

Fundamentals Operations with Polynomials

Adding or Subtracting Polynomials
Remember: you can add and subtract any polynomials, but only combine terms (monomials), which must have the same degree (exponent) [of course they must also have the same variable base]. Thus, how have these rules been applied when using the MATLAB numeric notation for polynomials? Obviously, they became rules on addition and subtraction of row vectors!
An Example:
The algebraic operations
translate in the following lines of code
clear p q
p = [1 -4 0 -1 0]; % p(x) <--> a polynomial of 4th degree
 
q = [0 0 1 -1 -6]; % q(x) as a polynomial of 4th degree (indeed it is a 2nd degree polynomial!)
 
sum_p_q = p+q
sum_p_q = 1×5
1 -4 1 -2 -6
 
subtract_p_q = p-q
subtract_p_q = 1×5
1 -4 -1 0 6
Of course:
Multiplying or Dividing Polynomials
Given the polynomials
determine the following polynomials
Multiplying polynomials:
w = conv(p,q)
returns the convolution of the vectors p and q. If p and q are vectors of polynomial coefficients, their convolution is equivalent to multiplying the two polynomials.
clear p q
p = [1 -4 0 -1 0]; % p(x) <--> a polynomial of 4th degree
 
q = [1 -1 -6]; % q(x) as a polynomial of 2nd degree
 
w = conv(p, q) % Note: w must be a 6th degree polynomial, thus the corresponding row-vector contains 7 elements
w = 1×7
1 -5 -2 23 1 6 0
The resulting polynomial is indeed
Polynomial long division: Given the vectors of polynomial coefficients p and q,
[m, r] = deconv(p, q)
deconvolves the vector q out of the vector p using polynomial long division, and returns the quotient m and remainder r such that: p = conv(q, m) + r
[m, r] = deconv(w, q)
m = 1×5
1 -4 0 -1 0
r = 1×7
0 0 0 0 0 0 0
As expected, the quotient vector contains the coefficients of the polynomial p, whereas the reminder r is null.
One more example:
clear m r
[m, r] = deconv(p, q)
m = 1×3
1 -3 3
r = 1×5
0 0 0 -16 18
Thus:

Integrating and Differentiating Polynomials

Integrating polynomials: simply apply the MATLAB command polyint.
Let's start with an example involving the evaluation of an indefinite integral:
clear p q
p = [3 0 -2]; % coefficients of the polynomial p(x)
 
q0 = 4.815; % NB we cannot keep the integration constant "c" as symbolic element! We must assign a numeric value to it!
q = polyint(p, q0)
q = 1×4
1.000000000000000 0 -2.000000000000000 4.815000000000000
In case we assign the null value to the integration constant c, then we may write simply
q1 = polyint(p) % NB this time the integration constant c is null
q1 = 1×4
1 0 -2 0
Note the last coefficient in the row-vector q1.
What about the evaluation of the definite integral of a polynomial?
clear p q
p = [1 -4 0 -1 0];
q = polyint(p)
q = 1×6
0.200000000000000 -1.000000000000000 0 -0.500000000000000 0 0
% let's assign the integration extrema
a = -3;
b = +4;
Let's evaluate the integral:
Ival1 = polyval(q, b) - polyval(q, a)
Ival1 = 74.900000000000034
 
IvalALT = diff(polyval(q, [a, b]))
IvalALT = 74.900000000000034
Differentiating polynomials
Use polyder to obtain the derivative of a polynomial
clear p q
p = [1/5 -1 0 -1/2 0 0];
q = polyder(p)
q = 1×5
1 -4 0 -1 0
Thus
You can compute also the derivative of the product of two polynomials:
clear p q
p = [1 -4 0 -1 0];
q = [1 -1 -6];
 
% pay attention to the command syntax!
m = polyder(p, q) % <<<--- 2 inputs, only 1 output <-> derivative of the product p*q
m = 1×6
6 -25 -8 69 2 6
You can exploit the command polyder also to compute the derivative of a rational function
clear p q
q = [1 -4 0 -1 0];
p = [1 -1 -6];
 
% pay attention to the command syntax!
[m, d] = polyder(p, q) % <<<--- 2 inputs, 2 outputs <-> derivative of the rational function p(x)/q(x)
m = 1×6
-2 7 16 -73 0 -6
d = 1×9
1 -8 16 -2 8 0 1 0 0
Thus

Functions: The General Syntax

MATLAB provides the ability to define your own functions:
function [output variable list] = function_name (input variable list)

An Example

Calculating the area of any triangle according to the formula
where are the lengths of the triangle sides.
The function then (in its simplest version) has 3 input parameters and only 1 output parameter:
edit evalTriangleArea
Please note the initial comment lines in the M-file text. They are useful to implement the help contents for the custom MATLAB function.
To see how the help command uses such helping lines, just run the following
help evalTriangleArea
The function evalTriangleArea(a, b, c) computes the area of a triangle whose sides have length a, b and c. Inputs: a,b,c: Lengths of sides Output: A: area of triangle Usage: Area = evalArea(2,3,4); Written by XXX, MM/DD/YY.
Using the custom function
format short
Area = evalTriangleArea(10,15,20)
Area = 72.6184
evalTriangleArea(10,15,20)
ans = 72.6184

Functions Applied to a Vector

Most MATLAB functions have been modified (overloaded) so they work with inputs which are vectors as well as scalars. When an argument is a vector the function is applied to each element of the vector, producing a vector of the same size as the input vector.

Examples

sqrt(1:10)
ans = 1×10
1.0000 1.4142 1.7321 2.0000 2.2361 2.4495 2.6458 2.8284 3.0000 3.1623
 
xv = -1:1/2:1 % a row vector with 5 elements
xv = 1×5
-1.0000 -0.5000 0 0.5000 1.0000
sin( (pi/2)*xv )
ans = 1×5
-1.0000 -0.7071 0 0.7071 1.0000
Sometimes the result of the function has fewer elements than the input:
sum(xv)
ans = 0
 
max(xv)
ans = 1

Summary

Using this live script you have:

Back to the Index

Use this link to go back to the main live script of the collection.

Back to the Previous Part: Symbolic Math Computations

Use this link to go back to the previous live script of this collection.

Go to the Next Part: LTI Systems

Use this link to go to the next live script of the collection.