IT Workshop - Concepts Notes - Module 2 - MATLAB
IT Workshop - Concepts Notes - Module 2 - MATLAB
Module - MATLAB
MATLAB Basics
MATLAB (an abbreviation of "matrix laboratory") invented in 1970s by Cleve Moler
developed by MathWorks
MATLAB
MuPAD - symbolic engine allowing access to symbolic computing abilities.
and 49 more packages……………….We are currently using MATLAB 9.9 (R2021a release)
MATLAB Contents
Variables - Variables are defined using the assignment operator =
MATLAB Contents
Vectors and matrices - A simple array is defined using the colon
MATLAB Contents
Scalar Functions - A simple arithmetic operation
MATLAB Contents
Functions - When creating a MATLAB function, the name of the file should match the name
of the first function in the file.
Valid function names begin with an alphabetic character, and can contain letters,
numbers, or underscores. Variables and functions are case sensitive.
.m,
.p,
.mex,
.mat,
.fig,
.mlx,
.mlapp,
.mltbx,
.mlappinstall,
.mlpkginstall
Introduction
Disadvantages of MATLAB
– Cost – full copy of MATLAB costs 5-10 times as much as a conventional C or Fortran compiler;
cost-effective for businesses, not for individuals (student editions available).
MATLAB Command
Details Window
Window
displays properties of file
selected above
• There are also two command-line oriented ways to get help: the help and lookfor commands.
• The help command searches for an exact function name match, while the lookfor command
searches the quick summary information in each function for a match.
Function Description
demo run MATLAB’s built-in demonstrations
clc clear the Command Window
clf clear the contents of the current figure window
clear clear the variables in the workspace
^c abort running program, returns a command prompt
diary keep track of everything done in MATLAB session
• If a user enters a name at the MATLAB prompt, the MATLAB interpreter attempts to find the name as
follows:
1. It looks for the name as a variable. If it is a variable, MATLAB displays the current contents of the variable.
2. It checks to see if the name is an M-file in the current directory. If it is, MATLAB executes that function or
command.
3. It checks to see if the name is an M-file in any directory in the search path. If it is, MATLAB executes that
function or command.
• MATLAB includes the which command to help you find out just which version of a file is being executed
and where it is located.
• Use the symbols +, -, *, /, and ^ for addition, subtraction, multiplication, division, and
exponentiation, respectively.
• The value in ans can be used in later calculations. But be careful! Every time a new
expression without an equal sign is evaluated, the value saved in ans will be overwritten.
• A MATLAB script file is a much better solution for performing a series of calculations
and reusing those calculations later.
Summary
• We learned about the MATLAB desktop (Command Window, Toolstrip, Document Window,
Workspace Browser, Current Folder, etc.).
• A MATLAB user can get help by either using the Help Browser or the command-line help functions
help and lookfor.
• When a user types a command in the Command Window, MATLAB searches for that command in
the directories specified in the MATLAB path and executes the first M-file in the path that matches
the command.
• An array is a collection of data values organized into rows and columns and is known by a
single name.
• Scalars are treated as arrays with only one row and one column.
• The most common types of MATLAB variables are double and char.
• Variables of type char consist of scalars or arrays of 16-bit values, each representing a
single character. Arrays of this type are used to hold character strings.
• The type of data assigned to a variable determines its type when it is created.
25
12/9/2021 Sandip Mandal 25
sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA
• The colon operator specifies a whole series of values by specifying the first value in the
series, the stepping increment, and the last value in the series
• first:incr:last
• The transpose operator (denoted by an apostrophe) swaps the row and columns of any
array to which it is applied.
Multidimensional Arrays
• MATLAB allows us to create arrays with as many dimensions as needed for a particular
problem.
• You access an element in an array using its indices:
• a(1, 5) a(:, :, 1) a(5)
• MATLAB always allocates array elements in column major order (i.e., allocating the first
column in memory, then the second, then the third).
Subarrays
• It is possible to select and use subsets of MATLAB arrays as though they were separate arrays.
• To select a portion of an array, just include a list of all of the elements to be selected in the
parentheses after the array name.
• When used in an array subscript, the special function end returns the highest value taken on by
that subscript
arr3 = [1 2 3 4 5 6 7 8];
arr3(5:end) = [5 6 7 8]
Special Values
Value Description
pi Contains π to 15 significant digits.
i, j Contain the value √-1.
Inf This symbol represents machine infinity. It is usually generated as
a result of a division by 0.
NaN This symbol stands for Not-a-Number. It is the result of an
undefined mathematical operation, such as the division of zero by
zero.
Special Values
Value Description
clock This special variable contains the current date and time in the form of a 6-
element row vector containing the year, month, day, hour, minute, and
second.
date Contains the current data in a character string format, such as 24-Nov-
1998.
eps This variable name is short for “epsilon.” It is the smallest difference
between two numbers that can be represented on the computer.
ans A special variable used to store the result of an expression if that result is
not explicitly assigned to some other variable.
• When data is echoed in the Command Window, some values are printed using a default format.
• This default format can be changed in one of two ways: from the main MATLAB Window menu or using the format
command.
Data Files
• The save command saves data from the current MATLAB workspace into a disk file
save filename var1 var2 var3
• The load command loads data from a disk file into the current MATLAB workspace
load filename
Array Operations
Array Operations
Matrix Operations
Hierarchy of Operations
Precedence Operation
1 The contents of all parentheses are evaluated, starting from the innermost
parentheses and working outward.
2 All exponentials are evaluated, working from left to right.
3 All multiplications and divisions are evaluated, working from left to right.
4 All additions and subtractions are evaluated, working from left to right.
• One of MATLAB’s greatest strengths is that it comes with an incredible variety of built-in functions
ready for use.
• Unlike mathematical functions, MATLAB functions can return more than one result to the calling
program. For example,
[maxval, index] = max([1 –5 6 –3])
• Some functions, like sin and cos, can take an array of input values and calculate an array of
output values on an element-by-element basis (refer to Table 2.8 in the text for a long list of
common functions).
Introduction to Plotting
• To plot a data set, just create two vectors containing the x and y values to be plotted, and use the
plot function
x = 0:1:10;
y = x.ˆ2 – 10.*x + 15;
plot(x,y).
• MATLAB allows a programmer to select the color of a line to be plotted, the style of the line to be
plotted, and the type of marker to be used for data points on the line
plot(x,y,‘r--’).
• A vector is a mathematical quantity that has both a magnitude and a direction (i.e.,
the velocity of a car as it has both speed and direction).
• A scalar is a quantity that has a magnitude only (i.e., the temperature of a room).
• MATLAB can be used to calculate the magnitude and angle of a vector as well as
perform vector addition, subtraction, and multiplication.
• The matrix operations in MATLAB provide a powerful way to represent and solve
systems of simultaneous equations.
• The inverse of a matrix is computed by the MATLAB function inv
(A).
The determinant of a matrix is computed by the MATLAB function det
(A).
MATLAB includes a special debugging tool called a symbolic debugger, which allows you to walk
through the execution of your program one statement at a time and to examine the values of any
variables at each step along the way.
Summary
• Introduced two data types (double and char), assignment statements, input/output
statements, and data files.
• Listed arithmetic operations for scalars, array operations, and matrix operations.
• There are four possible combinations of linear and logarithmic scales on the x- and y-
axes:
1. The plot function plots both x and y data on linear axes.
2. The semilogx function plots x data on a logarithmic axis and y data on a linear axis.
3. The semilogy function plots x data on a linear axis and y data on a logarithmic axis.
4. The loglog function plots both x and y data on logarithmic axes.
SemilogX
SemilogY
• hold on forces additional plots to be laid on top of the previously existing plots, while hold off
switches back to default behavior.
• The figure command takes the form figure(n). When executed, n becomes the current figure
and the figure is created (if it did not already exist).
Subplots
• It is possible to place more than one set of axes on a single figure, creating multiple subplots.
• This command divides the current figure into m × n equal-sized regions, arranged in m rows and n
columns, and creates a set of axes at position p to receive all current plotting commands.
Subplots
• In addition to color, style, and marker type for a line, there are four more properties
associated with each line:
– LineWidth – specifies the width of each line in points.
– MarkerEdgeColor – specifies the color of the marker or the edge color for filled markers.
– MarkerFaceColor – specifies the color of the face of filled markers.
– MarkerSize – specifies the size of the marker in points.
plot(x, y,‘PropertyName’,value,…)
Polar Plots
• MATLAB includes a special function called polar, which plots two-dimensional data in
polar coordinates instead of rectangular coordinates
polar(theta,r)
• The angle theta is the angle (in radians) of a point counterclockwise from the right-hand
horizontal axis, and r is distance from the center of the plot to the point.
• Once a plot has been created by a MATLAB program, a user can edit and annotate the
plot using the GUI-based tools available from the plot toolbar.
• You can save the entire plot in a modifiable form using the
• “File/Save As” menu item from the Figure Window.
• The figure file (*.fig) contains all the information required to re-create the figure plus
annotations at any time in the future.
Function Description
bar(x,y) This function creates a vertical bar plot. Values in x label each bar. Values in
y set height of the bar.
barh(x,y) This function creates a horizontal bar plot.
compass(x,y) This function creates a polar plot, with an arrow drawn from the origin to the
location of each (x,y) point. Note: Cartesian coordinates are used, not polar
coordinates.
Function Description
pie(x) This function creates a pie plot.
stairs(x,y) This function creates a stair plot, with each stair step centered on
an (x,y) point.
stem(x,y) This function creates a stem plot, with a marker at each (x,y)
point and a stem drawn vertically from that point to the x-axis.
• What happens if you give the plot function a two-dimensional array of data instead of a
vector of data?
• MATLAB will treat each column of the 2D array as a separate line, and it plots as many
lines as there are columns in the data set.
• Thus, if x is a vector and y is an array, plot(x,y) will plot the columns of y against x.
• MATLAB allows us to plot two or more data items with very different output ranges or with
different units. For example, we might want to plot both the distance traveled by an
accelerating object and the velocity of that object.
• MATLAB supports a command that allows us to plot both distance and velocity on a single
set of axes with different scales on the left y axis and the right y axis to support the two
different data types. This is the yyaxis command.
• yyaxis left
• yyaxis right
• After selecting an axis on which to plot, the yyaxis left command will cause all following
commands to be referred to the left-hand axis, and the scale of the left-hand axis will adjust to
match the data.
• Similarly, the yyaxis right command will cause all following commands to be referred to the
right-hand axis and the scale of the right-hand axis will adjust to match the data. All plot-related
commands will be referred to whichever axis is currently active.
Summary
• The axis command allows you to select the specific range of x and y data to be plotted.
• The hold command allows later plots to be plotted on top of earlier ones.
• The figure command allows an engineer to create and select among multiple Figure Windows.
• The subplot command allows an engineer to create and select among multiple plots within a
single Figure Window.
Introduction
• In the next two chapters, we will introduce a number of MATLAB statements that allow us
to control the order in which statements are executed in a program.
• There are two broad categories of control statements: branches and loops.
• We will also introduce a formal program design procedure, pseudocode, and the logical
data type.
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA
• Top-down design is the process of starting with a large task and breaking it down into
smaller, more easily understandable pieces (sub-tasks). It is the basis of our formal
program design process, which goes as follows:
1. Clearly state the problem that you are trying to solve.
2. Define the inputs required by the program and the outputs to be produced by the program.
3. Design the algorithm that you intend to implement in the program.
4. Turn the algorithm into MATLAB statements.
5. Test the resulting MATLAB program.
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA
Use of Pseudocode
• As a part of the design process, it is necessary to describe the algorithm that you intend to
implement in a way that is easy for both you and other people to understand.
• You can accomplish this using pseudocode, a hybrid mixture of MATLAB and English.
• It is structured like MATLAB, with a separate line for each distinct idea or segment of
code, but the descriptions on each line are in English.
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA
• The logical data type is a special type of data that can have one of only two possible values:
true or false.
• Logical values are stored in a single byte of memory. These values are produced by the two special
functions true and false, e.g.,
a1 = true;
• They are also produced by two types of MATLAB operators: relational operators and logic
operators.
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA
Relational Operators
Operator Operation
== Equal to
~= Not equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA
Logic Operators
Operator Operation
& Logical AND
&& Logical AND with shortcut evaluation
| Logical Inclusive OR
|| Logical Inclusive OR with shortcut
evaluation
xor Logical Exclusive OR
~ Logical NOT
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA
Logic Functions
Function Purpose
ischar(a) Returns true if a is a character array, false
otherwise.
isempty(a) Returns true if a is an empty array, false
otherwise.
isinf(a) Returns true if the value of a is infinite, false
otherwise.
isnan(a) Returns true if the value of a is NaN, false
otherwise.
isnumeric(a) Returns true if a is a numeric array, false
otherwise.
logical Converts numerical values to logical values.
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA
Branches
• Branches are MATLAB statements that permit us to select and execute specific sections
of code (called blocks) while skipping other sections of code.
• They are variations of the if construct, the switch construct, and the try/catch
construct.
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA
The if Construct
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA
• It is much easier to make a mistake when writing a program containing branches and
loops than it is when writing simple sequential programs.
• Once programs start to include loops and branches, the best way to locate an error is to
use the symbolic debugger supplied with MATLAB.
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA
Breakpoints
• First, open the file that you would like to debug using the File/Open menu selection in the MATLAB
Command Window.
• To determine what happens when the program is executed, set one or more breakpoints by
clicking the mouse on the horizontal dash mark at the left of the line(s) of interest.
• When a breakpoint is set, a red dot appears to the left of that line containing the breakpoint. The
program will run until it reaches the breakpoint and stop there, allowing you to examine the
workspace up to that point.
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA
Code Analyzer
• The Code Analyzer (previously called M-Lint) examines a MATLAB file and looks for potential
problems.
• It runs automatically over any script loaded into the Edit/Debug Window. If it finds a problem it
shades that part of the code in the editor. If you mouse over the shaded area, a popup will appear
describing the problem.
• The Code Analyzer is a great tool for locating errors, poor usage, or obsolete features in MATLAB
code, including such things as variables that are defined but never used.
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA
Code Sections
• Each block is separated from other blocks by a double comment character(%%)in the first
two columns of a line.
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA
• The programmer can select a section and execute it repeatedly by clicking the Run
Section button.
• Alternatively, the user can click the Run and Advance button and the code in that section
will be executed and the execution will stop with the next section selected.
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA
• The standard MATLAB function roots can be used to find advanced solutions to
complex problems such as the roots of polynomials. It solves for the roots of any
polynomial in a robust fashion.
• If you can represent the behavior of the system you are studying as a polynomial, the
MATLAB roots function provides an easy way to solve for its roots.
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA
Summary
• The principal type of branch is the if construct, but there are also the
switch and try/catch constructs.
• The MATLAB symbolic debugger and related tools such as the Code
Analyzer make debugging MATLAB code much easier.
Function Functions
• Function function is the rather awkward name that MATLAB gives to a function whose
input arguments include the names or handles of other functions.
• For example, MATLAB contains a function function called fzero. This function locates a
zero of the function that is passed to it. To locate a zero of cos between 0 and π, you
would write:
fzero(‘cos’,[0 pi])
Function Handles
• A function handle is a MATLAB data type that holds information to be used in referencing a
function.
•
• A function handle can be created in either of two possible ways: the @ operator or the str2func
function.
• To create a function handle with the @ operator, just place it in front of the function name.
• To create a function handle with the str2func function, call the function with the function name in a
string.
• Function eval evaluates a character array as though it had been typed in the Command Window
x = eval(‘sin(pi/4)’)
• If a function lies in a directory on the MATLAB path, then the scope extends to all MATLAB
functions in a program, because they all check the path when trying to find a function with a given
name.
• In contrast, the scope of the other function types that we will discuss in the rest of this chapter is
more limited.
• If more than one function is present in a file, the top function is a normal or primary
function, while the ones below it are called local functions.
• Private functions are functions that reside in subdirectories with the special name
private. They are only visible to other functions in the private directory or to
functions in the parent directory.
Nested Functions
• Nested functions are functions that are defined entirely within the body of another
function, called the host function.
• They are only visible to the host function in which they are embedded and to other nested
functions embedded at the same level within the same host function.
• A nested function has access to any variables defined with it, plus any variables defined
within the host function.
• However, function handles have certain advantages over function names, such as:
1. Passing function access information to other functions.
2. Improved performance in repeated operations.
3. Allow wider access to local functions and private functions.
4. Include more functions per M-File for easier file management.
• A differential equation is an equation that includes a variable and one or more of its
derivatives.
Anonymous Functions
• An anonymous function is a function “without a name.”
• It is a function that is declared in a single MATLAB statement that returns a function handle, which
can then be used to execute the function. The general form is:
fhandle = @ (arglist) expr
• For example,
myfunc = @ (x) x.ˆ2 - 2*x - 2
» myfunc(2)
ans = -2
Recursive Functions
ì
ï 1 n=0
n! = í
î n ´ (n - 1) ´ (n - 2)´ ... ´ 2´ 1
ï n>0
ì
ï 1 n=0
n! = í
î n ´ (n - 1)!
ï n>0
Plotting Functions
• In all previous plots, we have created arrays of data to plot and passed those arrays to the
plotting function.
• MATLAB also includes a function, fplot, that will plot a function directly.
Histograms
• The definite integral of a function is interpreted as the total area under the curve of the
function between the starting and ending points.
Summary
• Function functions, local functions, private functions, and nested functions were all introduced.
• Function handles and the concept of anonymous functions were also introduced.
• Function fplot is a function function that can directly plot a user-specified function without having to create
output data first.
• Anonymous functions are simple functions without a name that are created in a single line and called by their
function handles.
• Histograms are plots of the number of samples from a data set that fall into each of a series of amplitude bins.
Introduction
• Well-designed functions enormously reduce the effort required on a large programming project.
Their benefits include:
In poorly written programs, it is common for the engineer modifying the program to make a change in
one region of the code and to have that change cause unintended side effects in a totally different part of
the program. The use of well-designed functions minimizes this problem by data hiding.
• So far we have seen script files, which are just collections of MATLAB statements that
are stored in a file.
• In contrast, a MATLAB function is a special type of M-file that runs in its own
independent workspace.
• It receives input data through an input argument list and returns results to the caller
through an output argument list.
More on Functions
• The first comment line in a function after the function statement, called the H1 comment
line, serves a special purpose.
• The special significance of this line is that it is searched and displayed by the lookfor
command.
• When a function call occurs, MATLAB makes a copy of the actual arguments and passes them to
the function.
• This copying means that even if the function modifies the input arguments, it won’t affect the
original data in the caller.
• This feature helps to prevent unintended side effects, in which an error in the function might
unintentionally modify variables in the calling program.
Optional Arguments
• Many MATLAB functions support optional input arguments and output arguments.
• For example, we have seen calls to the plot function with as few as two or as many as
seven input arguments.
• There are eight special functions that can be used by MATLAB functions to get
information about their optional arguments and to report errors in those arguments (six of
these functions are introduced here).
• In addition to the argument list, MATLAB functions can exchange data with each other
and with the base workspace through global memory.
• Global memory is a special type of memory that can be accessed from any workspace.
• A global variable is declared with the global statement. The form of a global statement
is
global var1 var2 var3 ...
• Persistent memory is a special type of memory that can only be accessed from within the
function, but is preserved unchanged between calls to the function.
• MATLAB includes two built-in sorting functions that are extremely efficient.
• The sort function sorts a data set into ascending or descending order.
• If the data is a column or row vector, the entire data set is sorted. If the data is a two-
dimensional matrix, the columns of the matrix are sorted separately.
• The sortrows function sorts a matrix of data into ascending or descending order
according to one or more specified columns.
• MATLAB includes two standard functions that generate random values from different
distributions.
• They are:
– rand – generates random values from a uniform distribution on the range [0,1); and
– randn – generates random values from a standard normal distribution.
Summary
• Functions are special types of M-files that receive data through input arguments and return results
through output arguments.
• MATLAB functions can support varying numbers of input and output arguments.
• Data can also be shared between MATLAB functions by placing the data in global memory.
• Internal data within a function can be preserved between calls to that function by placing the data in
persistent memory.
Thank You