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

Part 2 - Numbers, Arithmetic Operations, Formats and Variables

This is the second 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 module is to enable you to enter an arithmetic expression in MATLAB and understand the results produced, particularly when these results involve scientific notation, complex numbers and Inf (Infinity) and NaN (Not a Number).
What you should know by the end of this module:

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 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.
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.
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.

MATLAB as calculator

This is the simplest way of using it: evaluating numerical expressions.
Suppose we want to evaluate the numerical expression
Simply type the following code in the Command Window and then press the "Enter/Return" key (or run the current section of this live script)
4 + sqrt(2) - sin(pi/5)^2 + exp(2)
ans = 12.4578
The result is assigned to the predefined variable ans.
If you compare, for example, the current code with a Python equivalent piece of code, they are quite similar;
import math
 
result = 4 + math.sqrt(2) - math.sin(math.pi / 5) ** 2 + math.exp(2)
print(result)
 

Arithmetic operations

The most common arithmetic operations in MATLAB are
This is just like on a calculator, in spreadsheets (Excel) and most programming languages.

Order of Operations

In MATLAB (as many other programming languages) operations are performed in the following order:
  1. expressions in brackets: ( ) ;
  2. powers: ^ ;
  3. multiplication and division: * , / ;
  4. addition and subtraction: + , - .
Operations of the same precedence, for example multiplication and division, are evaluated from left to right.
In ordinary written mathematics we sometimes leave out brackets and rely on the fact that an intelligent human will understand where they ought to go. In contrast, computers obey exactly the rules for evaluating expressions. If you are unsure, adding some extra brackets (parentheses) will not hurt.

A few Examples

1+2*3 % Which operation has higher precedence?
ans = 7
 
(1+2)*3 % And now?
ans = 9
Remember that operations of the same precedence are evaluated left to right:
24/2/3 % The same result as the the second case.
ans = 4
 
24/(2*3) % This version is usually clearer.
ans = 4
A final example:
5^4^3
ans = 244140625
 
5^(4^3) % Note the different result!
ans = 5.4210e+44
 
(5^4)^3 % This is the same as the first case, but clearer.
ans = 244140625

Changing the Displayed Format

By default, MATLAB displays 5 decimal digits, unless the number is too big or too small, when it switches to scientific notation. The format of the answers displayed in the command window can be changed using the format command.
help format
format - Set output display format This MATLAB function changes the output display format to the format specified by style. Syntax format(style) fmt = format fmt = format(style) Input Arguments style - Format to apply character vector | string scalar | DisplayFormatOptions object Output Arguments fmt - Current display format DisplayFormatOptions object Examples Long Format Hexadecimal Format Short and Long Engineering Notation Large Data Range Format Reset Format to Default Get Current Format Save and Restore Display Format See also DisplayFormatOptions, disp, fprintf, formattedDisplayText Introduced in MATLAB before R2006a Documentation for format
Pay attention: format does NOT affect how numbers are stored or calculations are done in MATLAB. It only affects how numbers are displayed.

A Simple Example

format short
x = 3 + 11/16 + 2^1.2
x = 5.9849
 
format compact
x = 3 + 11/16 + 2^1.2
x = 5.9849
 
format long eng
x = 3 + 11/16 + 2^1.2
x = 5.98489670999407e+000
 
format long
x = 3 + 11/16 + 2^1.2
x = 5.984896709994070

Scientific Notation

For very large numbers or very small numbers it is more convenient to express the number in scientific notation using a power of 10.
3.6e+12
ans = 3.600000000000000e+12
 
5.2e-9
ans = 5.200000000000000e-09
 
2^30
ans = 1.073741824000000e+09
 
2^(-40)
ans = 9.094947017729282e-13
0.5/0.1-5
ans = 0
 
0.7/0.1 -7 % Sometimes the result may not be what you expect.
ans = -8.881784197001252e-16

Complex Numbers

MATLAB allows and works with complex numbers. All arithmetic with complex numbers works in the usual way.
You may use both i and j to denote the imaginary unit, if you did not already define any variable named i or j(see below how to set valid variable names).

Example

Define the complex number
2+3*1i
ans = 2.000000000000000 + 3.000000000000000i
 
2+3i
ans = 2.000000000000000 + 3.000000000000000i
 
2+3j % Any of these three expression works.
ans = 2.000000000000000 + 3.000000000000000i
Define the complex expression
(2+3*1i)/(4+6*1i)
ans = 0.500000000000000

Special functions for complex numbers

A MATLAB function to create a complex number: create the complex number
complex(2, 3) % the 1st argument is the real part, the 2nd argument is the imaginary part
ans = 2.000000000000000 + 3.000000000000000i
A MATLAB function to get the real part of the complex number
real(2+3i)
ans = 2
A MATLAB function to get the imaginary part of the complex number
imag(2+3j)
ans = 3
A MATLAB function to get the modulus of the complex number
abs((2+3i)/(4+6i))
ans = 0.500000000000000
A MATLAB function to get the argument of a complex number (in radians)
angle(+1+1j)
ans = 0.785398163397448
 
rad2deg(angle(+1+1j))
ans = 45
 
rad2deg(angle(+1-1j))
ans = -45
 
rad2deg(angle(-1-1j))
ans = -135
 
rad2deg(angle((2+3i)/(4+6i)))
ans = 0
 
rad2deg(angle(2+3i))
ans = 56.309932474020215
 
rad2deg(angle(4+6i))
ans = 56.309932474020215

Special Values for Infinity and for Undefined Operations

MATLAB uses the IEEE standard 754 for floating point numbers, to provide approximations to the real numbers. This standard, which is used in virtually every current computer microprocessor, specifies how floating point numbers are stored and also includes special values for infinity and for undefined operations.

Infinity (Inf)

Operations that would result in a mathematical infinity give a result of Inf, while those that would result in minus infinity give -Inf.
1/0
ans = Inf
 
-3/0
ans = -Inf
 

Not a Number (NaN)

Operations whose value cannot be mathematically determined result in a Not a Number.
0/0
ans = NaN

Propagation of Inf and NaN in Calculations

Both Inf and Nan propagate in calculations without producing any error message.
1e-10*Inf
ans = Inf
 
5*NaN
ans = NaN
isnan(ans)
ans = logical 1
Operations involving Inf and/or NaN are also significantly slower than those using standard floating point numbers.
Operations involving Inf may occasionally produce a NaN.
Inf-Inf
ans = NaN
 
Inf+Inf
ans = Inf
isinf(ans)
ans = logical 1
Once you have produced a NaN, it affects all calculations from then on:
1e-32*NaN
ans = NaN
 
NaN-NaN
ans = NaN

Variables

Variables are essential to store the result of a calculation so it can be subsequently used in a later calculation. This not only makes your programs much more efficient, but also makes them much easier to understand.

Variable Names

A variable name is a sequence of letters, numbers and underscores "_", starting with a letter.
The following are invalid variable names. Try to insert one of those variable name in the code box below, run the section and see what message you will obtain
1x % invalid variable name!
 
_x % another invalid variable name
% insert one of the two invalid variable declaration here and see the
% resulting error message
x_ = 0
x_ = 0
x1 = x_
x1 = 0
Then insert one of the following valid variable names
x1 % valid variable name
 
x_ % valid variable name
You should obtain a different error message: indeed the variable name is valid, but the variable does not exist in the Matlab Workspace.
Length of variable names: although a variable name may have any length, MATLAB only recognizes the first "few" characters. How many characters are recognized is specified by the Matlab command namelengthmax (which is typically 63).

Warnings

Assigning Values to Variables

Matlab uses = to assign a value to a variable.
Note: the left-hand-side of the = must be a valid variable name, while the right-hand-side must be a valid expression.
a = 1
b = -1
c = -2
delta = b^2 - 4*a*c
x1 = (-b + sqrt(delta))/(2*a)
x2 = (-b - sqrt(delta))/(2*a)

Suppressing output

When Matlab does a calculation and assigns the result to a variable, the result is echoed to the command window.
Sometimes, especially when dealing with large vectors or matrices, it is very useful to keep the screen uncluttered by unwanted output. This is simply done by adding a semicolon ; to the end of the command
x = 2;
y = 4;
z = x*y

Useful Commands

There are several useful commands that allow you to see what variables you have created and if necessary remove some or all of them.
Please remember, you can always get more information on a command using the help command.

List of the Variables

who
 
who x* % This command lists all the variables starting with the (lower case) letter x.
whos
 
whos x*

Clearing Variables

To remove a variable, use the clear command
clear x1
 
whos

Predefined Constants

When you start MATLAB, some variables already have predefined values:
pi
1i
 
1j
 
realmax % the largest double precision number
 
4*realmax % What did you expect as the result?
 
realmin % the smallest positive double precision number
MATLAB uses IEEE standard 754 double precision to store floating point numbers which approximate the real numbers. The characteristics of double precision arithmetic are described by the relative machine precision, also known as the machine epsilon: eps returns , which is the distance from 1.0 to the next larger double-precision number
eps
For more details, refer to
doc eps

Caveat

You can give these variables new values. If you do so you may get strange effects afterwards!

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: Starting MATLAB

Use this link to go back to the previous live script of this collection (Part 1).

Go to the Next Part: Vectors & Matrices

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