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

Part 1 - Starting MATLAB

This is the first 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

Goals

The aim of this live script is to make you familiar with the MATLAB environment.
What you should know by the end of this part:

Starting MATLAB

Starting MATLAB on the PCs in the Computer Lab "Aula Nettuno" - C1 Building

MATLAB is installed on the computers in the Computer Labs of the Dept. of Architecture & Engineering at the University of Trieste. Moreover, the University of Trieste has subscribed to a MATLAB TAH (Total Academic Headcount) license that allows students (as well as professors and university staff) to download the software and install it on their PCs. For more details regarding the available products and how to download and activate the software, please visit the dedicated MathWorks web portal.

Starting MATLAB on your own PC or Laptop

The MATLAB logo is similar to the image, shown below, of an L-shaped membrane
MatlabLogoNoBackground.png

MATLAB Online on your own PC or Laptop

This is the preferred mode of use during the course exercises.
Features of using MATLAB Online :
To start using MATLAB Online, go to https://matlab.mathworks.com/ , sign in with your Mathworks account
MATLABOnlineSIGNin.png
and then click the Open MATLAB Online button:
MATLABonlineBUTTON.png

The MATLAB Interface - MATLAB Online

When you start MATLAB for the first time (both MATLAB online or using your own PC/laptop) you should see the following group of windows:
MATLABonlineGUIdefault.png
The most important window is the Command Window (the biggest one), in which you type MATLAB commands and see the results of the commands.
There are also the Files and Workspace panels.
What are these windows for?
Specifically:
Other useful panels (hidden in the default layout)
You may modify the MATLAB user interface layout, using the "Layout " menu
LayoutMenu_view.png
Moreover, you can customize your settings using the Preferences menu in the Environment section of the Home tab. Initially it is simplest to use MATLAB default settings. When you have decided what is the most effective way for you to work, you may close some or all of these windows. However you will always need a Command Window.

Managing Folders and Uploading Files using MATLAB Online

How to create a new folder in MATLAB Online

Use folders to keep your programs and data organized.
To create a "new folder" using MATLAB Online, use the following procedure:

newFolderOnline.png

How to upload files and folder in MATLAB Online

uploadFilesOnline.png

A First Example

To see how MATLAB works, please type the following two lines in the MATLAB Command Window, with Enter after each command.
x = 2
x = x/2 + 1/x
assignmentExample_CommandANDWorkspace.png
assignmentExampleBIS_CWindow_WorkspaceHistory.png
Note: after the execution of the second assignment, the value of the variable x has been updated (check the Workspace Panel). Moreover, the Command History Panel contains the list of the command you typed in the Command Window, in chronological order.

The MATLAB Programming Language

MATLAB is an interpreted programming language. This means that every command is evaluated when you type it into the Command Window and press the Enter key. It is possible to create sequences of commands and save them in a text file (a script) or create more complex programs using functions and also classes. Even when you execute a MATLAB script or function, the code is interpreted.
This has the great advantage of allowing interaction with MATLAB.
There are several ways to return to a previous command, edit it to correct any errors and then execute it again, when typing the code directly in the Command Window. The easiest way to do this is to use the arrow keys on the keyboard: the up arrow allows you to return to the previous command (pressing several times can go back several commands), while the left and right arrow keys position the cursor within the command and the Backspace or Delete keys remove a character that can be typed again. Pressing the Enter key executes the edited command.
If you type a few characters from the the beginning of a command, for example x =, and then press the up arrow key, you go back to the most recent command that started with these characters. Alternatively you can find the command you want in the Command History sub-window, and double click on it to execute it again. You may also copy commands from the Command History sub-window using the menu opened when you right-click on them.

Example: Using the Arrow Keys in the Command Window

Use the arrow keys to go back to the previous command and execute it again, several times
x = x/2+ 1/x
Check that every time you execute the command (i.e., every time you press the Enter key after recalling the command using the arrow key), the command itself has been stored in the Command History command list.

Getting Help

There are several ways of getting help within MATLAB. It is essential you become familiar with both the MATLAB help command and the MATLAB Help browser which has extensive documentation. MATLAB also contains a number of demonstration videos that can help you become familiar with it.

Help Command

The quick way to get information about a MATLAB command is to type
help command_name
in the MATLAB Command Window. This may produce more information that will fit in one screen so you will have to scroll back to the beginning of the output.

Examples

Use the help command to find out more information about the help command
help help
help - Help for functions in Command Window This MATLAB function displays the help text for the functionality specified by name, such as a function, method, class, toolbox, variable, or namespace. Syntax help name help Input Arguments name - Functionality name character vector | string scalar Examples Display Function and Overloaded Method Help Display Namespace, Class, and Method Help Display Variable Help Display Help for Functions in Folder See also doc, lookfor, more, what, which, whos Introduced in MATLAB before R2006a Documentation for help Other uses of help Folders named help
Use the help command to find out information about a MATLAB toolbox (a collection of MATLAB functions and apps, with focus on a particular topic, as Signal Processing, Control Systems, Statistics etc.):
help control
Control System Toolbox Version 24.2 (R2024b) 21-Jun-2024 Table of Contents ----------------- Modeling - Create and combine models of linear systems Analysis - Analyze systems in the time or frequency domain Design - Design and tune control systems Reduction - Obtain reduced-order models Plotting - Create and customize response plots General - Preferences, linear algebra utilities Apps - Control System Toolbox apps Examples - Control System Toolbox examples Control System Toolbox Documentation Other uses of control Folders named control

With a Little Help from the 'help' Command!

Here is a list of the main categories of topics available using the help command
General purpose commands
help general
General purpose commands. MATLAB Version 24.2 (R2024b) 21-Jun-2024 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. (R2024b) 21-Jun-2024 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. ismember - True for set member. 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.
Elementary matrices and matrix manipulation
help elmat
Elementary matrices and matrix manipulation. Elementary matrices. zeros - Zeros array. ones - Ones array. eye - Identity matrix. repmat - Replicate and tile array. repelem - Replicate elements of an array. combinations- Generate all element combinations of arrays. linspace - Linearly spaced vector. logspace - Logarithmically spaced vector. freqspace - Frequency spacing for frequency response. meshgrid - X and Y arrays for 3-D plots. accumarray - Construct an array with accumulation. : - Regularly spaced vector and index into matrix. Basic array information. size - Size of array. length - Length of vector. ndims - Number of dimensions. numel - Number of elements. disp - Display matrix or text. isempty - True for empty array. isequal - True if arrays are numerically equal. isequaln - True if arrays are numerically equal, treating NaNs as equal. height - Number of rows. width - Number of columns. Matrix manipulation. cat - Concatenate arrays. reshape - Reshape array by rearranging existing elements. resize - Resize data by adding or removing elements. paddata - Pad data. trimdata - Trim data. diag - Diagonal matrices and diagonals of matrix. blkdiag - Block diagonal concatenation. tril - Extract lower triangular part. triu - Extract upper triangular part. fliplr - Flip matrix in left/right direction. flipud - Flip matrix in up/down direction. flip - Flip the order of elements. rot90 - Rotate matrix 90 degrees. : - Regularly spaced vector and index into matrix. find - Find indices of nonzero elements. end - Last index. sub2ind - Linear index from multiple subscripts. ind2sub - Multiple subscripts from linear index. bsxfun - Binary singleton expansion function. Multi-dimensional array functions. ndgrid - Generate arrays for N-D functions and interpolation. permute - Permute array dimensions. ipermute - Inverse permute array dimensions. shiftdim - Shift dimensions. circshift - Shift array circularly. squeeze - Remove singleton dimensions. Array utility functions. isscalar - True for scalar. isvector - True for vector. isrow - True for row vector. iscolumn - True for column vector. ismatrix - True for matrix. Special variables and constants. eps - Floating point relative accuracy. realmax - Largest positive floating point number. realmin - Smallest positive floating point number. intmax - Largest positive integer value. intmin - Smallest integer value. flintmax - Largest consecutive integer in floating point format. pi - 3.1415926535897.... i - Imaginary unit. inf - Infinity. nan - Not-a-Number. isnan - True for Not-a-Number. isinf - True for infinite elements. isfinite - True for finite elements. j - Imaginary unit. true - True array. false - False array. Specialized matrices. compan - Companion matrix. gallery - Test matrices. hadamard - Hadamard matrix. hankel - Hankel matrix. hilb - Hilbert matrix. invhilb - Inverse Hilbert matrix. magic - Magic square. pascal - Pascal matrix. rosser - Classic symmetric eigenvalue test problem. toeplitz - Toeplitz matrix. vander - Vandermonde matrix. wilkinson - Wilkinson's eigenvalue test matrix. Controlling multithreading setting. maxNumCompThreads - Controls the maximum number of computational threads.
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.
Matrix functions - numerical linear algebra
help matfun
Matrix functions - numerical linear algebra. Arithmetic operators. mpower - Matrix power ^ Matrix analysis. bandwidth - Matrix bandwidth. isbanded - Determine whether a matrix has certain bandwidth. isdiag - Determine whether a matrix is diagonal. ishermitian - Determine whether a matrix is Hermitian. issymmetric - Determine whether a matrix is symmetric. istril - Determine whether a matrix is lower triangular. istriu - Determine whether a matrix is upper triangular. norm - Matrix or vector norm. pagenorm - Page-wise matrix or vector norm. vecnorm - Vector norm. normest - Estimate the matrix 2-norm. rank - Matrix rank. det - Determinant. trace - Sum of diagonal elements. null - Null space. orth - Orthogonalization. rref - Reduced row echelon form. subspace - Angle between two subspaces. Linear equations. \ and / - Linear equation solution. pagemldivide - Page-wise left matrix divide. pagemrdivide - Pagr-wise right matrix divide. linsolve - Linear equation solution with extra control. decomposition - Linear equation solution using precomputed object. inv - Matrix inverse. pageinv - Page-wise matrix inverse rcond - LAPACK reciprocal condition estimator cond - Condition number with respect to inversion. condest - 1-norm condition number estimate. normest1 - 1-norm estimate. chol - Cholesky factorization. ldl - Block LDL' factorization. lu - LU factorization. qr - Orthogonal-triangular decomposition. pinv - Pseudoinverse. pagepinv - Page-wise pseudoinverse. lsqminnorm - Least squares with minimum norm of x. pagelsqminnorm - Page-wise minimum-norm solution of least-square system lscov - Least squares with known covariance. sylvester - Sylvester equation solver. Eigenvalues and singular values. eig - Eigenvalues and eigenvectors. pageeig - Page-wise eigenvalues and eigenvectors. svd - Singular value decomposition. pagesvd - Page-wise singular value decomposition. gsvd - Generalized singular value decomposition. eigs - A few eigenvalues. svds - A few singular values. poly - Characteristic polynomial. polyeig - Polynomial eigenvalue problem. condeig - Condition number with respect to eigenvalues. hess - Hessenberg form. schur - Schur decomposition. qz - QZ factorization for generalized eigenvalues. ordschur - Reordering of eigenvalues in Schur decomposition. ordqz - Reordering of eigenvalues in QZ factorization. ordeig - Eigenvalues of quasitriangular matrices. Matrix functions. expm - Matrix exponential. logm - Matrix logarithm. sqrtm - Matrix square root. funm - Evaluate general matrix function. Factorization utilities qrdelete - Delete a column or row from QR factorization. qrinsert - Insert a column or row into QR factorization. rsf2csf - Real block diagonal form to complex diagonal form. cdf2rdf - Complex diagonal form to real block diagonal form. balance - Diagonal scaling to improve eigenvalue accuracy. planerot - Givens plane rotation. cholupdate - rank 1 update to Cholesky factorization. qrupdate - rank 1 update to QR factorization.
Interpolation and polynomials
help polyfun
polyfun not found. Search the documentation for polyfun
Function functions and ODE solvers
help funfun
Sparse matrices
help sparfun
Two dimensional graphs
help graph2d
Three dimensional graphs
help graph3d
Character strings
help strfun
File input/output
help iofun
Time and dates
help timefun
Control Systems Toolbox
help control
Symbolic Math Toolbox
help symbolic
Simulink
help simulink

The Help Browser

More extensive information about MATLAB and its commands is available through the Help Browser using a web based interface. This can be accessed in a number of ways
HelpBrowserWindow.png
doc sqrt

MATLAB Scripts and Interactive Live Scripts

A MATLAB script is simply a plain text file containing a sequence of MATLAB commands. It is called also an M-file, because the file has extension .m
Using M-files allows you to
An M-file is executed (it means all the commands within the M-file are executed) simply by typing the name of the file (without the .m extension) in the Command Window.

The MATLAB Editor

MATLAB provides an editor, which allows you to easily create and edit M-files. Beside the basic editing functionalities, the MATLAB Editor has some features useful specifically for writing programs:
MATLAB_script.png
Syntax highlighting:
Debugging:

MATLAB Script: an Example

The following command opens the existing M-file named simple_Mscript_example.m in the MATLAB Editor window
edit simple_Mscript_example
Do not worry about the meaning of the MATLAB commands for now, but you should try executing the M-file by typing simple_Mscript_example in the MATLAB Command Window.

MATLAB Interactive Live Scripts

MATLAB live scripts are interactive documents that combine MATLAB code with formatted text, equations and images in a single environment. In addition, live scripts store and display the output together with the code that creates it (from the MATLAB documentation). More details and examples of live scripts are available in the MATLAB documentation.
The actual document is a MATLAB Live Script.

MATLAB Live Script: an Example

This is what the live script that corresponds to the M-file seen above looks like
open simple_LiveScript_example

The First Code Example in an Interactive Environment: a MATLAB Live Script

If not already done, open this document (the file named Intro_MATLAB_034IN_FAC_p1.mlx) directly using MATLAB. Put the mouse cursor in this document section and select the command "Run Section" from the Live Editor tab or, alternatively, click the vertical striped bar to the left of the code
x = 2
x = x/2+ 1/x
Executing this portion of code within the live script produces the same result, displayed in the same way, as code executed by entering commands directly in the Command Window.

Example: Repeating a Command in a Live Script

Neither the up arrow key nor the Command History command list approach works when using a live script. If you want to repeat a command (or a piece of code) in a live script, you should use the following approach (by means of a so called Control Button - more details in the MATLAB documentation on Live Scripts and Interactive Controls):
We have already defined the variable x in this live script, assigning it an initial value and then performing a simple calculation that assigns the result back to the variable x.
Now, let's run the following piece of code clicking on the "Run Again" button more than once. What happens?
 
disp(x)
 
x = x/2 + 1/x
 
 

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.

Go to the Next Part: Numbers, Arithmetic Operations, Formats and Variables

Use this link to go to the next live script (Part 2) of the collection.