Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
28 views

IT Workshop - Concepts Notes - Module 2 - MATLAB

Uploaded by

anushka de
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

IT Workshop - Concepts Notes - Module 2 - MATLAB

Uploaded by

anushka de
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 110

UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

Module : Introduction to MATLAB

Dr. Sandip Mandal


Dept. of CSE, UEM Kolkata
Tel : +91-8449007365
Email : sandip.mandal@uem.edu.in

12/9/2021 Sandip Mandal 1


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

Module - MATLAB

12/9/2021 Sandip Mandal 2


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

MATLAB Basics
 MATLAB (an abbreviation of "matrix laboratory") invented in 1970s by Cleve Moler

 MATLAB is a proprietary multi-paradigm programming language and numeric


computing environment.

MATLAB allows matrix manipulations


Plotting of functions and data
Implementation of algorithms
Creation of user interfaces
and Interfacing with programs written in other languages.

 developed by MathWorks

12/9/2021 Sandip Mandal 3


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

MATLAB
 MuPAD - symbolic engine allowing access to symbolic computing abilities.

 Simulink - adds graphical multi-domain simulation and model-based


design for dynamic and embedded systems.

 MATLAB programming language - Common usage of the MATLAB application involves


using the "Command Window" as an interactive mathematical shell or executing text files
containing MATLAB code.

and 49 more packages……………….We are currently using MATLAB 9.9 (R2021a release)

12/9/2021 Sandip Mandal 4


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

MATLAB Contents
 Variables - Variables are defined using the assignment operator =

12/9/2021 Sandip Mandal 5


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

MATLAB Contents
 Vectors and matrices - A simple array is defined using the colon

syntax: initial : increment : terminator.

12/9/2021 Sandip Mandal 6


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

MATLAB Contents
 Scalar Functions - A simple arithmetic operation

12/9/2021 Sandip Mandal 7


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

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.

 MATLAB supports object-oriented programming - including classes, inheritance, virtual


dispatch, packages, pass-by-value semantics, and pass-by-reference semantics.

12/9/2021 Sandip Mandal 8


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

MATLAB File Extensions


File Extensions supports

.m,
.p,
.mex,
.mat,
.fig,
.mlx,
.mlapp,
.mltbx,
.mlappinstall,
.mlpkginstall

12/9/2021 Sandip Mandal 9


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

Introduction

• MATLAB is short for MATrix LABoratory.

• MATLAB is a combination of:


– a procedural programming language;
– an integrated development environment (IDE) + editor and debugger;
– an extremely rich set of built-in functions to perform many types of technical calculations.

12/9/2021 Sandip Mandal 10


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

The Advantages of MATLAB

• Ease of Use – interpreted language, rapid prototyping.


• Platform Independence – Windows, Linux, Unix, Macintosh.
• Predefined Functions – extensive library, prepackaged solutions, special-purpose
toolboxes.
• Device-Independent Plotting – display on any graphical output device.
• Graphical User Interface – design sophisticated programs to be operated by any user.
• MATLAB Compiler – speeds up interpreted language.

12/9/2021 Sandip Mandal 11


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

Disadvantages of MATLAB

• MATLAB has two principal disadvantages:


– Interpreted Language – executes more slowly than compiled languages; slowness can be
mitigated through proper structure, minimizing performance of vectorized code, and use of JIT
compiler.

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

12/9/2021 Sandip Mandal 12


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

Launch the Help


The MATLAB Environment Browser

This control allows a user


to view or change current Workspace Browser
directory shows variables defined
in workspace

Current Folder Browser


shows a list of the files in MATLAB
the current folder Editor

MATLAB Command
Details Window
Window
displays properties of file
selected above

12/9/2021 Sandip Mandal 13


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

Getting Help in MATLAB

• There are three ways to get help in MATLAB.

• The preferred method is to use the Help Browser.

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

12/9/2021 Sandip Mandal 14


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

A Few Important Commands

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

12/9/2021 Sandip Mandal 15


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

The MATLAB Search Path

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

12/9/2021 Sandip Mandal 16


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

Using MATLAB as a Calculator

• In its simplest form, MATLAB can be used as a calculator to perform mathematical


calculations.

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

12/9/2021 Sandip Mandal 17


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

Using MATLAB as a Calculator


• Addition

12/9/2021 Sandip Mandal 18


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

Using MATLAB as a Calculator


• Subtraction

12/9/2021 Sandip Mandal 19


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

MATLAB Script Files

• Performing complex calculations or a series of calculations by typing single commands


directly into the Command Window can be cumbersome, error prone, and the calculations
may not be saved properly for later use.

• A MATLAB script file is a much better solution for performing a series of calculations
and reusing those calculations later.

• Script files are also called M-files.

12/9/2021 Sandip Mandal 20


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

MATLAB Script Files : Example

12/9/2021 Sandip Mandal 21


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

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.

12/9/2021 Sandip Mandal 22


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

Variables and Arrays

• The fundamental unit of data in any MATLAB program is the array.

• An array is a collection of data values organized into rows and columns and is known by a
single name.

• Arrays can be classified as either vectors or matrices.

12/9/2021 Sandip Mandal 23


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

More on Variables and Arrays

• Scalars are treated as arrays with only one row and one column.

• The size of an array is given as # of rows by # of columns.

• A MATLAB variable is a region of memory containing an array and is known by a user-


specified name.

12/9/2021 Sandip Mandal 24


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

Introduction to Data Types

• The most common types of MATLAB variables are double and char.

• Variables of type double consist of scalars or arrays of 64-bit double-precision floating-


point numbers. They can hold real, imaginary, or complex values.

• 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

Creating and Initializing Variables in MATLAB

• There are three common ways to initialize a variable in MATLAB:


1. Assign data to the variable in an assignment statement
var = expression;
2. Input data into the variable from the keyboard
var = input(‘Enter an input value:’);
3. Read data from a file

12/9/2021 Sandip Mandal 26


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

Initializing with Shortcut Expressions

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

12/9/2021 Sandip Mandal 27


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

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

12/9/2021 Sandip Mandal 28


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

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]

12/9/2021 Sandip Mandal 29


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

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.

12/9/2021 Sandip Mandal 30


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

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.

12/9/2021 Sandip Mandal 31


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

Displaying Output Data

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

• A more flexible way to display data is with the fprintf function


fprintf(‘The value of pi is %f \n’,pi).

• %f is a conversion character (specifying floating point format).

• \n is an escape character (calling for a new line).

12/9/2021 Sandip Mandal 32


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

Data Files

• The save command saves data from the current MATLAB workspace into a disk file
save filename var1 var2 var3

• By default, the data file will be a MAT-file: a special compact format.

• The load command loads data from a disk file into the current MATLAB workspace
load filename

12/9/2021 Sandip Mandal 33


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

Scalar and Array Operations

Arithmetic Operations between Two Scalars


Operation Algebraic Form MATLAB Form
Addition a+b a + b
Subtraction a-b a - b
Multiplication axb a * b
Division a/b a / b
Exponentiation ab a ^ b

12/9/2021 Sandip Mandal 34


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

Array Operations

Operation MATLAB Form Comments

Array Addition a + b Same for array and matrix

Array Subtraction a - b Same for array and matrix

Array Multiplication a .* b Element-by-element multiplication of


a and b

12/9/2021 Sandip Mandal 35


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

Array Operations

Operation MATLAB Form Comments


Array Right Division a ./ b Element-by-element division of a
and b
Array Left Division a .\ b Element-by-element division
of a and b, but with b in the
numerator
Array Exponentiation a .^ b Element-by-element
exponentiation of a and b

12/9/2021 Sandip Mandal 36


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

Matrix Operations

Operation MATLAB Form Comments

Matrix Multiplication a*b Matrix multiplication of a and b

Matrix Right Division a/b Matrix division defined by a * inv(b), where


inv(b) is the inverse of matrix b
Matrix Left Division a\b Matrix division defined by inv(a) * b

12/9/2021 Sandip Mandal 37


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

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.

12/9/2021 Sandip Mandal 38


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

Built-in MATLAB Functions

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

12/9/2021 Sandip Mandal 39


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

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

12/9/2021 Sandip Mandal 40


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

MATLAB Applications: Vector Mathematics

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

12/9/2021 Sandip Mandal 41


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

MATLAB Applications: Matrix Operations and Simultaneous


Equations

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

12/9/2021 Sandip Mandal 42


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

Debugging MATLAB Programs

• There are three types of errors found in MATLAB programs:


1. Syntax error – errors in the statement like spelling and punctuation.
2. Run-time error – illegal mathematical operation attempted.
3. Logical error – runs but produces wrong answer.

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.

12/9/2021 Sandip Mandal 43


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

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.

• Quick look at built-in functions, plotting, and debugging.

12/9/2021 Sandip Mandal 44


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA
Topic Name : Various Plotting functions in MATLAB

Dr. Sandip Mandal


Dept. of CSE, UEM Kolkata
Tel : +91-8449007365
Email : sandip.mandal@uem.edu.in

12/9/2021 Sandip Mandal 45


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

Additional Plotting Features for Two-Dimensional Plots

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

12/9/2021 Sandip Mandal 46


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

SemilogX

12/9/2021 Sandip Mandal 47


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

SemilogY

12/9/2021 Sandip Mandal 48


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

Multiple Plots and Figures


• Normally, a new plot is created each time that a plot command is issued.

• This behavior can be modified with the hold command.

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

12/9/2021 Sandip Mandal 49


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

Multiple Plots and Figures

12/9/2021 Sandip Mandal 50


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

Subplots

• It is possible to place more than one set of axes on a single figure, creating multiple subplots.

• Subplots are created with the subplot command of the form


subplot(m,n,p)

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

12/9/2021 Sandip Mandal 51


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

Subplots

12/9/2021 Sandip Mandal 52


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

Enhanced Control of Plotted Lines

• 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,…)

12/9/2021 Sandip Mandal 53


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

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.

12/9/2021 Sandip Mandal 54


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

Annotating and Saving Plots

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

12/9/2021 Sandip Mandal 55


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

Additional Types of Two-Dimensional Plots

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.

12/9/2021 Sandip Mandal 56


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

Additional Types of Two-Dimensional Plots (continued)

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.

12/9/2021 Sandip Mandal 57


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

Using the plot Function with Two- Dimensional Arrays

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

12/9/2021 Sandip Mandal 58


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

Plots with Two y Axes

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

12/9/2021 Sandip Mandal 59


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

Plots with Two y Axes


• The forms of the yyaxis command are:

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

12/9/2021 Sandip Mandal 60


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

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.

12/9/2021 Sandip Mandal 61


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA
Topic Name : Various Plotting functions in MATLAB

Dr. Sandip Mandal


Dept. of CSE, UEM Kolkata
Tel : +91-8449007365
Email : sandip.mandal@uem.edu.in

12/9/2021 Sandip Mandal 62


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

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

Introduction to Top-Down Design Techniques

• 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

• 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

The switch Construct


UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

The try/catch Construct


UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

More on Debugging MATLAB Programs

• 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

• A code section is a block of code in the MATLAB Editor/Debugger. It can be used to


examine the results of each line or set of lines as the program is being executed. The
block of code can be tested and executed independently.

• 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

Run Section and Run and Advance Buttons

• 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

MATLAB Applications: Roots of Polynomials

• Solving for roots is critically important in many areas of


engineering, since the roots of certain polynomials correspond
to the vibrational modes of structures and similar real-world
problems.

• A polynomial equation nth order has n roots, each of which


may be real, repeated, or imaginary. There is no simple
closed-form solution for the roots of arbitrary polynomials of
any order, so solving for roots can be a difficult problem.
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

The MATLAB roots Function

• 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

• In Chapter 4, we have presented the basic types of MATLAB branches


and the relational and logic operations used to control them.

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

• The standard MATLAB function roots can be used to find advanced


solutions to complex problems such as the roots of polynomials.
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

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])

12/9/2021 Sandip Mandal 82


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

Common Function Functions

Function Name Description


feval Evaluates a function passed as a calling argument at a specified input
value.
fminbnd Minimizes a function of one variable.
fzero Finds a zero of a function of one variable.
integral Numerically integrates a function.
fplot Two-dimensional function by name.
fplot3 Three-dimensional function by name.

12/9/2021 Sandip Mandal 83


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

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.

12/9/2021 Sandip Mandal 84


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

Functions eval and feval


• The keys to the operation of function functions are two special MATLAB functions, eval and
feval.

• Function eval evaluates a character array as though it had been typed in the Command Window
x = eval(‘sin(pi/4)’)

• Function feval evaluates a named function at a specific input value


x = feval(‘sin’,pi/4)

12/9/2021 Sandip Mandal 85


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

Local Functions, Private Functions, and Nested Functions


• The scope of a function is defined as the locations within MATLAB from which the function can be
accessed.

• The scope of an ordinary MATLAB function is the current working directory.

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

12/9/2021 Sandip Mandal 86


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

Local Functions and Private Functions

• It is possible to place more than one function in a single file.

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

12/9/2021 Sandip Mandal 87


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

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.

12/9/2021 Sandip Mandal 88


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

Significance of Function Handles


• Either function names or function handles can be used to execute most functions.

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

12/9/2021 Sandip Mandal 89


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

An Example Application: Solving Ordinary Differential Equations

• A differential equation is an equation that includes a variable and one or more of its
derivatives.

• MATLAB includes a plethora of functions to solve differential equations under various


conditions, but the most useful function is ode45. ode45 can also solve systems of
simultaneous differential equations.

12/9/2021 Sandip Mandal 90


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

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

12/9/2021 Sandip Mandal 91


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

Recursive Functions

• A function is said to be recursive if it calls itself. A typical example of a recursive function


is the factorial function. It can be written explicitly and recursively as follows:

ì
ï 1 n=0
n! = í
î n ´ (n - 1) ´ (n - 2)´ ... ´ 2´ 1
ï n>0

ì
ï 1 n=0
n! = í
î n ´ (n - 1)!
ï n>0

12/9/2021 Sandip Mandal 92


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

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.

12/9/2021 Sandip Mandal 93


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

Histograms

• A histogram is a plot showing the distribution of values within a data set.

• The standard MATLAB histogram function is histogram.

12/9/2021 Sandip Mandal 94


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

An Example Application: Numerical Integration

• The definite integral of a function is interpreted as the total area under the curve of the
function between the starting and ending points.

• The calculation of a definite integral by numerical methods is known as the numerical


quadrature or numerical integration.

• MATLAB includes a built-in function to perform numerical integration called integral.


integral automatically adjusts the step size depending on the function being integrated.

12/9/2021 Sandip Mandal 95


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

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.

12/9/2021 Sandip Mandal 96


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

Introduction

• Well-designed functions enormously reduce the effort required on a large programming project.
Their benefits include:

1. Independent testing of sub-tasks;


2. Reusable code;
3. Isolation from unintended side effects.

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.

12/9/2021 Sandip Mandal 97


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

Introduction to MATLAB Functions

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

12/9/2021 Sandip Mandal 98


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

General Form of a Function

12/9/2021 Sandip Mandal 99


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

More on Functions

• The first comment line in a function after the function statement, called the H1 comment
line, serves a special purpose.

• It should always contain a one-line summary of the purpose of the function.

• The special significance of this line is that it is searched and displayed by the lookfor
command.

12/9/2021 Sandip Mandal 100


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

Variable Passing in MATLAB: The Pass-By-Value Scheme

• MATLAB programs communicate with their functions using a pass-by-value scheme.

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

12/9/2021 Sandip Mandal 101


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

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

12/9/2021 Sandip Mandal 102


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

Optional Argument Functions


Function Description
nargin returns the number of actual input arguments that were used to call the function
nargout returns the number of actual output arguments that were used to call the function
narginchk returns a standard error message if a function is called with too few or too many
arguments
error displays an error message and aborts the function producing the error
warning displays a warning message, continues function execution
inputname returns the actual name of the variable that corresponds to a particular argument number

12/9/2021 Sandip Mandal 103


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

Sharing Data Using Global Memory

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

12/9/2021 Sandip Mandal 104


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

Preserving Data Between Calls to a Function


• When a function finishes executing, the special workspace created for that function is destroyed.
However, it is sometimes useful to preserve some local information within a function between calls
to the function.

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

• A persistent variable is declared using the following form


persistent var1 var2 var3 ...

12/9/2021 Sandip Mandal 105


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

Built-in MATLAB Functions: Sorting Functions

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

12/9/2021 Sandip Mandal 106


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

Built-in MATLAB Functions: Random Number Functions

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

12/9/2021 Sandip Mandal 107


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

Random Number Function Calling Sequences

– Functions rand and randn have the following calling sequences:


• rand() or randn() – generates a single random value.
• rand(n) or randn(n) – generates an n × n array of random values.
rand(m,n) or randn(m,n) – generates an m × n array of random values.

12/9/2021 Sandip Mandal 108


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

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.

12/9/2021 Sandip Mandal 109


sandip.mandal@uem.edu.in
UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA

Thank You

12/9/2021 Sandip Mandal WhatsApp - 8449007365 110


sandip.mandal@uem.edu.in

You might also like