0% found this document useful (0 votes)
63 views

Matlab

This document provides an overview of MATLAB, including: - MATLAB is a software for numerical computation, visualization, and programming. It is matrix-oriented and used widely in engineering and science. - The interface includes a command window, workspace, help browser, and editor. Basic functions covered include variables, matrices, plotting, scripts/functions, and debugging. - The document outlines MATLAB's capabilities in areas like linear algebra, statistics, signal processing, and more. It also covers basic commands, data types, input/output, plotting, and examples of data conversion.

Uploaded by

Deepak Sahu
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
63 views

Matlab

This document provides an overview of MATLAB, including: - MATLAB is a software for numerical computation, visualization, and programming. It is matrix-oriented and used widely in engineering and science. - The interface includes a command window, workspace, help browser, and editor. Basic functions covered include variables, matrices, plotting, scripts/functions, and debugging. - The document outlines MATLAB's capabilities in areas like linear algebra, statistics, signal processing, and more. It also covers basic commands, data types, input/output, plotting, and examples of data conversion.

Uploaded by

Deepak Sahu
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 251

MATLAB

1
About Presentation
In this workshop you will learn a few of
the basic functions of MATLAB.
First we will start working with basic
numbers, formats, demos, mathematical
functions, setting variables, matrices and
generating plots by using the plot
functions.
Brief overview of how to generate scripts
in MATLAB called M-files

2
Table of Content

 The basic MATLAB interface.


 Basic commands.
 Declaring & manipulating variables.
 Plotting graphs.
 Conditional Operators.
 Functions.

3
Introduction
 MATLAB, which stands for Matrix Laboratory, is a
powerful, general-purpose system or environment for
doing mathematics, scientific and engineering
calculations.
 MATLAB is matrix-oriented, so what would take
several statements in C or Fortran can usually be
accomplished in just a few lines using MATLAB's built-
in matrix and vector operations.
 MATLAB is a "High-Performance Numeric Computation
and Visualization Software" package.
 MATLAB is an interactive system whose basic data
is a matrix that does not require dimensioning.

4
Capability of MATLAB

• Dealing with Matrices and Arrays


• 2-D and 3-D Plotting and graphics
• Linear Algebra
• Algebraic Equations
• Non-linear Functions
• Statistics
• Data Analysis
• Calculus and Differential Equations
• Numerical Calculations
• Integration
• Transforms
• Curve Fitting

5
Features of MATLAB

• It is a high-level language for numerical computation, visualization and


application development.
• It also provides an interactive environment for iterative exploration,
design and problem solving.
• It provides vast library of mathematical functions for linear algebra,
statistics, Fourier analysis, filtering, optimization, numerical
integration and solving ordinary differential equations.
• It provides built-in graphics for visualizing data and tools for creating
custom plots.
• It provides tools for building applications with custom graphical
interfaces.
• It provides functions for integrating MATLAB based algorithms with
external applications and languages such as C, Java, .NET and Microsoft
Excel.

6
Uses of MATLAB

• MATLAB is widely used as a computational tool in science


and engineering encompassing the fields of physics,
chemistry, math and all engineering streams.
• Signal Processing and Communications
• Image and Video Processing
• Control Systems
• Test and Measurement
• Computational Finance
• Computational Biology

7
Basic MATLAB Interface

8
Matlab Window

Command
History
Window

WORKSPACE
WINDOW
Editor Window

Menu and
Toolbar

9
Command Window

This is the main area where you enter commands at the


command line, indicated by the command prompt (>>).

10
Workspace Window

The workspace shows all the variables you create


and/or import from files.

11
Command History Window

This panels shows or rerun commands that you entered


at the command line.

12
Editor Window

This is the main area where you can write program


an can edit in code.

13
Command window: Type your
instructions here and press
ENTER to execute them.

14
Example: Declare a column matrix
with
values 1,2 and 3.

15
Workspace: shows a list of
variables created by MATLAB.
As you can see, the value of ‘aaa’
is shown.

16
Another way to create a variable
Is to press this button.

17
MATLAB will prompt you to enter
the variable name.

18
As you can see, the variable
name has been changed to bbb.

19
2) Or by double clicking
on bbb.

To assign a value to bbb, you can do it in


two ways: 1) Using the command window.

20
When you click on bbb, the variable
editor window appears. You can type
in new values into bbb by filling in the
cells.

21
An example is shown here.
Try and do it yourself.

22
To display variables at the console,
you can type the variable name,
or you can type disp(variable_name).

23
To clear all variables from
memory and close all
figures, use the
clear, close all command.

24
As you can see, all workspace
variables are deleted when
you execute this command.

25
To clear the command window,
use the clc (clear console) command.

26
As you can see, all
console
entries are deleted
when
you execute this
command.

27
.
If you want to see help,
you can type help at the
command window

If you want to see help,


you can type help at the
command window.

28
Or you can press F1
to display the help
window. Click on
Open Help Browser
to search for a
specific function.

29
Example: search for
function mean

30
To create new m file

To create an m-file, 1) type edit at


the command window, or
2) Press this button.

31
The previous command will
display the editor window.
The editor creates an m-file
that can be used to write
your MATLAB programs.

32
To open a exiting m file-
1-Press this button.
Or 2-type open file name

33
To selective text Paste in a m file-
1-Press this button.
Or 2-go to edit and select paste submenu.

To copy a text in m file-


1-Press this button.
Or 2-go to edit and select copy submenu.

To cut a text in m file-


1-Press this button.
Or 2-go to edit and select cut submenu

3434
To Redo a text in m file-
1-Press this button or
2-go to edit and select redo submenu.
To Redo a text in m file-
1-Press this button.
Or 2-go to edit and select redo submenu.
To undo a text in m file-
1-Press this button.
Or 2-go to edit and select undo submenu.

35
For insert comment in
Matlab.
1)select this option. Or
2) press ctr+r for
selective text

36
For uncomment in
Matlab.
1)select this option. Or
2) Press ctr+T for
selective text.

37
To execute a program, press
the RUN button.

38
This window will appear. Press the
Change Directory button.

39
You can see that the program has
created two new variables in the
Workspace.

40
Debugging
Debug menus
• Set breakpoints to stop the execution of code
>> [i j]=sort2(2,4)
K>>
K>> whos
Name Size Bytes Class
a 1x1 8 double array
b 1x1 8 double array
Grand total is 2 elements using 16 bytes
K>> a
a= local function
2 workspace
K>> return
i=

4 exit debug Click mouse on the left


j= mode of the line of code to
2 create a breakpoint

41
MATLAB - Commands

MATLAB is an interactive program for numerical


computation and data visualization. You can enter a
command by typing it at the MATLAB prompt '>>' on the
Command Window.

42
Commands for Managing a Session

43
Commands for Working with the
System

44
Input and Output Commands

45
Format function

46
Vector, Matrix and Array Commands

47
Plotting Commands

48
Command Purpose

49
Data Types Available in MATLAB

50
Data Type Conversion

51
Example of data conversion
Example- 1:
x=3
isinteger(x)
isfloat(x)
isvector(x)
isscalar(x)
isnumeric(x)
Results:
x=3
ans = 0
ans = 1
ans = 1
ans = 1
ans = 1

52
Cont.…..
Example-2:
x = 23.54
isinteger(x)
isfloat(x)
isvector(x)
isscalar(x)
isnumeric(x)
Reults:
x = 23.5400
ans = 0
ans = 1
ans = 1
ans = 1
ans = 1

53
Cont.…..
Example-3
x = [1 2 3]
isinteger(x)
isfloat(x)
isvector(x)
isscalar(x)
Results:
x=1 2 3
ans = 0
ans = 1
ans = 1
ans = 0

54
Cont.…..
• Example-4
x = 'Hello‘
isinteger(x)
isfloat(x)
isvector(x)
isscalar(x)
isnumeric(x)
Results:
x = Hello
ans = 0
ans = 0
ans = 1
ans = 0
ans = 0

55
Image Manipulation

56
Reading and Displaying an Image

 To read an image, use the imread command.


Example:
read an image file named ‘c:\aaa.jpg’ and store it in
matrix A.
A = imread(‘c:\aaa.jpg’)

 To display an image, use the


imshow(A) command.

57
Example: Read and Display Image

58
Manipulating an Image:

Convert to Grayscale:

•To convert an RGB image to grayscale, use the


rgb2gray command.

•Example: convert image A to grayscale:


– B = rgb2gray(A)

59
Example: Convert to Grayscale

clear, output:
close all
clc
aaa = imread('D:\DEEPAK
\sun temple\de.jpg');
figure, imshow(aaa)
bbb = rgb2gray(aaa)
figure, imshow(bbb)

60
Image in gray

Image in rgb

61
Saving an Image

• To save an image,
use the imwrite command.

Example:
write image a into file xxx.jpg:
imwrite(A,’xxx.jpg’,’jpg’)

62
MATLAB - Operators

•Arithmetic Operators
•Relational Operators
•Logical Operators
•Bitwise Operations
•Set Operations

63
Arithmetic Operators

MATLAB allows two different types of arithmetic


operations:

•Matrix arithmetic operations


•Array arithmetic operations

64
Cont.…

65
Relational Operators
• Relational operators can also work on both scalar and non-scalar data.
Relational operators for arrays perform element-by-element
comparisons between two arrays and return a logical array of the
same size, with elements set to logical 1 (true) where the relation is
true and elements set to logical 0 (false) where it is not.

66
Logical Operators

MATLAB offers two types of logical operators and functions:


Element-wise - these operators operate on corresponding
elements of logical arrays.
Short-circuit - these operators operate on scalar, logical
expressions.

•Element-wise logical operators operate element-by-element


on logical arrays. The symbols &, |, and ~ are the logical array
operators AND, OR, and NOT.
•Short-circuit logical operators allow short-circuiting on
logical operations. The symbols && and || are the logical
short-circuit operators AND and OR.
67
Bitwise Operations

 Bitwise operator works on bits and performs bit-by-bit operation. The truth
tables for &, |, and ^ are as follows:

68
Set Operations

• MATLAB provides various functions for set operations, like


union, intersection and testing for set membership, etc.

69
If…else Operator

 The if…else operator tests a condition.

 If the condition is true, then execute the if block.

 If the condition is false, execute the else block.

70
if (condition)
% if block
else
% else block
end

% conditions that can be tested


% == : is equal to
% ~= : is not equal to
% > : larger than
% >= : larger than or equal
% <= : less than or equal
% < : less than
71
Basic Commands

Basic Commands

72
Variables

 MATLAB can be used to initialize and manipulate many


types of variables:
1. Single Values
2. Matrix
3. String

73
Declaring Single Variables

 To declare single variables, type in a variable name and


type in its value.

 MATLAB will decide on the data type automatically, so we


don’t have to declare its data type.

 Example:
var1 = 3;
var2 = 56;

74
Cont.....

75
Cont.....

 Variables cannot have numbers or symbols in front of


them.
 Example of illegal variable names:

1var=1;
#var=45;

76
Cont.....

77
Matrix Variables

78
Cont.....

79
Accessing Matrix Values

 To access a specific value inside a matrix, use this


command:
 syntax
matrixName(rowNumber, colNumber)
 Example: to access a value inside row 3 and column 2.
mat3=[1,2,3;4,5,6;7,8,9];
disp(mat3)
var11=mat3(1,1)
var23=mat3(2,3)

80
Cont.....

81
Accessing Whole Columns and Rows

 To get a whole column, use this command:


 varA = matName(:,colNumber);
 To get a whole row, use this command:
 varA = matName(rowNumber,:);

mat=[4,5,6,5;1,8,6,2;9,8,4,1;3,2,8,9];
disp(mat)
col3=mat(:,3)
row2=mat(2,:)

82
Cont.....

83
Creating a Matrix of Zeros and Ones

 To create a matrix of zeros, use the zeros command.


 To create a matrix of ones, use the ones command.
 Example: create a 6 X 5 matrix of zeros and ones.

zeromatrix=zeros(6,5)
onesmatrix=ones(6,5)

84
Cont.....

85
Creating a Matrix of Random Numbers
and size of Matrix
 To create a matrix of random numbers, use the rand
command.
 To get the size of the matrix, use the size command.
 Example: create a 7 X 5 matrix of random numbers and
find its colum and row size.

randommatrix=rand(7,5)
[columsize,rowsize]=size(randommatrix);
columsize
rowsize

86
Cont.....

87
Transposing a Matrix

 A transpose operation changes the column of a matrix into


rows, and rows into columns.
 To do a transpose, use the single quote operator.
mat1=[1.12,4.36,8.36,7.25]
mat1=mat1‘
mat2=[1.40;8.36;7.96;5.36]
mat2=mat2‘
 Transpose the regular matrix:
mat1=[19.12,47.36,48.36;57.36,47.25,79.36;45.36,18.6,19.65]
mat1=mat1'

88
Cont.....

89
Cont.....

90
Finding the Maximum and Minimum
Value
 To find the maximum value for a matrix, use the max function.
 Syntax:
maxVal = max(mat1);
 To find the minimum value for a matrix, use the min function.
 Syntax:
minVal = min(mat1);
Example:
mat1=[19.12,47.36,48.36;57.36,47.25,79.36;45.36,18.6,19.65]
max(mat1)
max(max(mat1))
mat1=[19.12,47.36,48.36;57.36,47.25,79.36;45.36,18.6,19.65]
min(mat1)
min( min(mat1))
91
Cont.....

Max finds the


maximum value
in each column

When it is run again


on the result, it
returns the single-largest
value in the matrix.

92
Cont.....

Min finds the


minimum value
in each column

When it is run again


on the result, it
returns the minimum
value in the matrix.

93
Finding the Sum of Columns

 To find the sum of each column, use the sum command.


 Syntax:
colSum = sum(mat1);
 Example:
mat1=[19.12,47.36,48.36;57.36,47.25,79.36;45.36,18.6,19.65]
sum(mat1)
sum(sum(mat1))

94
Cont.....

Sum calculate the


sum of each column.

When it is run again


on the result, it
returns the net sum of
values in the matrix.

95
Adding Matrices

 To add matrices, use the + operator.


 Syntax:
mat3=mat1+ mat2
 It is necessary that both matrices are in same size.
 Example:
mat1=[19.12,47.36,48.36;57.36,47.25,79.36;45.36,18.6,19.65]
mat2=[29.12,37.36,68.36;77.36,47.25,89.36;45.36,98.6,39.65]
mat3=mat1+mat2

96
Cont.....

97
Subtracting Matrices

 To subtract matrices, use the - operator.


 Syntax:
mat3=mat1 – mat2
 It is necessary that both matrices are in same size.
 Example:
mat1=[19.12,47.36,48.36;57.36,47.25,79.36;45.36,18.6,19.65]
mat2=[29.12,37.36,68.36;77.36,47.25,89.36;45.36,98.6,39.65]
mat3=mat1-mat2

98
Cont.....

99
Multiplying Matrices

 To multiply matrices, use the .* operator.


 Syntax:
mat3=mat1 .* mat2.
 It is necessary that both matrices are in same size.
 Example:
mat1=[19.12,47.36,48.36;57.36,47.25,79.36;45.36,18.6,19.65]
mat2=[29.12,37.36,68.36;77.36,47.25,89.36;45.36,98.6,39.65]
mat3=mat1.*mat2

100
Cont.....

101
Dividing Matrices

 To divide matrices, use the ./ operator.


 Syntax:
mat3=mat1 ./ mat2
 It is necessary that both matrices are in same size.
 Example:
mat1=[19.12,47.36,48.36;57.36,47.25,79.36;45.36,18.6,19.65]
mat2=[29.12,37.36,68.36;77.36,47.25,89.36;45.36,98.6,39.65]
mat3=mat1./mat2

102
Cont.....

103
Sorting Matrices

 To sort a matrix, use the sort command.


 Syntax:
mat1 = sort(A,’ascend’)
Mat2=sort(A,’descend’)
 Default is ascending mode.
 Example:
• Default ascending mode
mat2=[29.12,37.36,68.36,77.36,47.25,89.36,45.36,98.6,39.65]
sort(mat2)
• Ascending mode
mat2=[29.12,37.36,68.36,77.36,47.25,89.36,45.36,98.6,39.65]
sort(mat2,'ascend')
• Descending mode
mat2=[29.12,37.36,68.36,77.36,47.25,89.36,45.36,98.6,39.65]
sort(mat2,'descend')
104
Default ascending mode

105
Ascending mode

106
Descending mode

107
Ascending and descending of regular
matrix

 Example:

mat2=[29.12,37.36,68.36;77.36,47.25,89.36;45.36,98.6,39.65]
sort(mat2,'descend')
sort(mat2,'ascend')

108
Cont.....

109
Flipping a Matrix

 A matrix can be flipped using the flipud or fliplr commands.


 Command flipud flips the matrix in UP/DOWN direction.
 Command fliplr flips the matrix in LEFT/RIGHT direction.
 Example:
mat2=[29.12,37.36,68.36;77.36,47.25,89.36;45.36,98.6,39.65]
mat3=flipud(mat2)
mat4=fliplr(mat2)

110
Cont.....

111
Strings

 MATLAB also can accept and manipulate string variables.


 A string is defined by enclosing it in single quotes.
 Example:
astring='Digital Communication!';
disp(astring)

112
Initializing a String

113
Converting a String to Lowercase

 To convert a string to lowercase, use the lower command.


 Syntax:
lowcasename = lower(stringname)
 Example:
stringname='DIGITAL COMMUNICATION'
newstring=lower(stringname)

114
Cont.....

115
Converting a String to Uppercase

 To convert a string to uppercase, use the upper command.


 Syntax:
newuppercasestringname = upper(lowercasestringname)
 Example:
stringname='digital communication'
newstring=upper(stringname)

116
Cont.....

117
Concatenate Strings

 Concatenating string means merging two or more strings


together.
 To concatenate strings, use the strcat command.
 Syntax:
newstring = strcat(string1,string2)
 Example:
string1='M. Tech. in'
string2=' Digital Communivation'
newstring=strcat(string1,string2)

118
Cont.....

119
Replace String

 To replace part of the string with a new value, use the strrep
command.
 Syntax: replace the word ‘Advance Network’ with the word
‘Digital Communication’ in the string string1.
newstring=strrep(string1,’lama’,’baru’)
 Example:
string1='M. Tech. in Advance Network'
newstring=strrep(string1,'Advance Network','Digital Communication')

120
Cont.....

121
Line Plot

• The plot function can be used to draw the relationship


between two variables.
• The plot function has different forms, depending on the
input arguments.
• If y is a vector, plot(y) produces a piecewise graph of the
elements of (y) versus the index of the elements of (y).
• Example- >>y =[1 2 3 4 5 7];
>> plot(y)
• If you specify two vectors as arguments, plot(x,y) produces
a graph of y versus x.

122
‘xlabel’, ‘ylabel’, and ‘title’

• To label the axes and add title, ‘xlabel’, ‘ylabel’, and ‘title’
functions can be used.
• Example: >> xlabel('string','name','value');
>> ylabel('string','name','value');
>> title('string','name','value');
• String- Text to display as the x-axis label.
• Name- Argument name. Name must appear inside single
quotes (' ').
• Value- Corresponding value.
• We can specify several name and value pair arguments in
any order as Name1,Value1,...,NameN,ValueN.
123
Name-value pair arguments

1) 'color', 'color name’ -

Table- Predefined colors and their RGB equivalents.


124
Contd.

2) 'FontAngle',‘value’ –Specifies the character slant, one of


these values: 'normal', 'italic', or 'oblique‘. Default value is
‘normal’.
3) 'FontName',‘Font name’ - Specifies the name of the font to
use for the text object.
4) 'FontSize',value – Specifies the font size.
5) 'FontWeight',‘value’ - Weight of text characters, one of the
following strings: 'normal‘, 'bold’, 'light’, 'demi‘.

125
Contd.

6) 'Interpreter',‘value’ - Character interpretation, one of the


following strings.

126
Legend

• The legend function places a legend on various types of


graphs. For each line plotted, the legend shows a sample of
the line type, marker symbol, and color beside the text
label we specify.
• Example: >> legend(‘legend name', 'location', ’location
name');

127
Location name can be one of the following
strings.

128
Example

• Plot the values of a random matrix.


x=1:50;
y=rand(1,50);
plot(x, y);
xlabel('x axis');
ylabel('y axis');
title('plot of random matrix.');
legend(‘random variable','location','southeast');

129
Contd.
Title

Y label

Legend

Y label
130
Example

• Draw sin(x)
x = 0:pi/36:10*pi;
y = sin(x);
plot(x,y);

131
Contd.

xlabel('x axis','color','red');
ylabel('y axis','color','blue');

Y label

X label

132
Contd.

title('plot of sin(X)','fontsize',12); Title of the graph

133
Contd.

legend('sin(x)','location','northeast');

Legend

134
Plotting Multiple Data Sets in One Graph

• Multiple x-y pair arguments create multiple graphs with a


single call to plot.
• Example- x = 0:pi/100:2*pi;
y = sin(x);
y2 = sin(x-.25);
y3 = sin(x-.5);
plot(x,y,x,y2,x,y3);
xlabel(‘x axis’);
ylabel(‘y axis’);
title(‘multiple sine plot’);

135
Contd.

Multiple plots

136
Contd.

legend('plot1','plot2','plot3','location','northeast');

Legend

137
Create line plot from Matrix

• Example- y=[16 2 3 13; 5 11 10 8; 9 7 6 12; 4 14 15 1 ];


plot(y);

138
Specifying line color and style

• Basic format of plot is given by-


• plot(x, y, line parameters);
• It is possible to specify color, line styles, and markers (such
as plus signs or circles) when you plot your data using the
plot command:
• plot(x,y,'color_style_marker');
• For example:
plot(x,y,'r:+')
• It plots a red-dotted line and places plus sign markers at
each data point.

139
Line style

140
Marker style

141
Plotting the lines using line parameters

• Example-
x=1:10;
y=[3 4 2 6 4 5 2 4 5 3];
plot(x,y,'b:v');
xlabel(‘x axis’);
ylabel(‘y axis’);
title(‘Plot’);
legend('plot1','location','northeast');

142
Contd.

Marker style

Line style

143
Multiple plot using line parameter

• Example- x = 0:0.2:10;
y0 = besselj(0,x);
y1 = besselj(1,x);
y2 = besselj(2,x);
y3 = besselj(3,x);
y4 = besselj(4,x);
y5 = besselj(5,x);
y6 = besselj(6,x);
plot(x, y0, 'r+', x, y1, 'go', x, y2, 'b*', x, y3,
'cx',x, y4, 'ms', x, y5, 'yd', x, y6, 'kv');

144
Contd.

Marker style

145
Specify line width, marker size and marker
color

• Example-
x = -pi:pi/10:pi;
y = tan(sin(x)) - sin(tan(x));
plot(x,y,'--gs','LineWidth',2,'MarkerSize',10,
'MarkerEdgeColor','b', 'MarkerFaceColor','r');

146
Contd.

147
Sub plot

• It divides the current figure into a grid that is numbered


row- wise.
• Basic format is : subplot(m,n,p).
• It breaks the window in m-by-n grid and create an axes
object in the pth location for the current plot.
• m= number of rows
• n= number of column
• Example-
s(1) = subplot(2,1,1);
s(2) = subplot(2,1,2);

148
Contd.

Sub plot s(1)

Sub plot s(2)

149
Example

• Draw two plots in one figure.


x= 0:pi/36:10*pi;
y= sin(x);
y1=cos(x)+sin(x);
subplot(2,1,1);
plot(y,'b-.');
subplot(2,1,2);
plot(y1,'r-');

150
Contd.

Plot (y)

Plot (y1)

151
Example

• Divide figure into 4 grid i.e., s(1), s(2), s(3), s(4).


s(1)=subplot(2,2,1);
s(2)=subplot(2,2,2);
s(3)=subplot(2,2,3);
s(4)=subplot(2,2,4);

152
Contd.

Subplot s(1) Subplot s(2)

Subplot s(3) Subplot s(4)

153
Adding Plots to an Existing Graph

• MATLAB command hold on is used to add the plot to an


existing graph.
• MATLAB does not replace the existing graph when we
issue another plotting command; it adds the new data to
the current graph, rescaling the axes if necessary.
• Command hold off reset the hold state.

154
Example

• Add plot to an existing graph


x = -pi:pi/20:pi;
y1 = sin(x);
y2 = cos(x);
plot(x,y1);
hold on
plot(x,y2);
hold off

155
Contd.

Plot of y1

Plot of y2

156
Plotyy

• It is a 2-D line plots with y-axes on both left and right side.
• Baisc format-
plotyy(X1,Y1,X2,Y2);
• It plots X1 versus Y1 with y-axis labelling on the left and
plots X2 versus Y2 with y-axis labelling on the right.
• plotyy(X1,Y1,X2,Y2,function) uses the specified plotting
function to produce the graph.
• plotyy(X1,Y1,X2,Y2,'function1','function2') uses function1
(X1,Y1) to plot the data for the left axis and function2
(X2,Y2) to plot the data for the right axis.

157
Example

• Plot two data sets with different y axes.


x = 0:0.01:20;
y1 = 200*exp(-0.05*x).*sin(x);
y2 = 0.8*exp(-0.5*x).*sin(10*x);
plotyy(x,y1,x,y2);

158
Contd.

Plot of y1

Plot of y2

159
Example

• Plot two data sets using a graph with two y-axes. Add a title
and axis labels.
x = 0:0.01:20;
y1 = 200*exp(-0.05*x).*sin(x);
y2 = 0.8*exp(-0.5*x).*sin(10*x);
[HA,hLine1,hLine2] = plotyy(x,y1,x,y2);
title('Multiple Decay Rates');
xlabel('Time (\musec)');
ylabel(HA(1),'Slow Decay');
ylabel(HA(2),'Fast Decay');

160
Contd.

Title

y1 label
y2 label

x label 161
Contd.

• Plot two data sets using a graph with two y-axes. Change
the line styles.
x = 0:0.01:20;
y1 = 200*exp(-0.05*x).*sin(x);
y2 = 0.8*exp(-0.5*x).*sin(10*x);
[hAx,hLine1,hLine2] = plotyy(x,y1,x,y2);
set(hLine1,'LineStyle','--');
set(hLine2,'LineStyle',':');

162
Contd.

Line style 1

Line style 2

163
Example

• Plot two data sets using a graph with two y-axes. Use a line
plot for the data associated with the left y-axes. Use a stem
plot for the data associated with the right y-axes.
x = 0:0.1:10;
y1 = 200*exp(-0.05*x).*sin(x);
y2 = 0.8*exp(-0.5*x).*sin(10*x);
plotyy(x,y1,x,y2,'plot','stem');

164
Contd.

Line plot

Stem plot

165
Example

• Plot three data sets using a graph with two y-axes. Plot one
set of data associated with the left y-axis. Plot two sets of
data associated with the right y-axis by using two-column
matrices.
x = 0:0.1:10;
y1 = 200*exp(-0.05*x).*sin(x);
y2 = 0.8*exp(-0.5*x).*sin(10*x);
y3 = 0.2*exp(-0.5*x).*sin(10*x);
plotyy(x,y1,[x',x'],[y2',y3']);

166
Example

Plot of y2 Plot of y1

y1 axis

y2 and
y3 axis

Plot of y3

167
Example
• Plot two data sets with different y axes. Plot one data using
semilogarithmic scaling and plot other data using linear
scaling on y axes.
t = 0:900;
z1 = 1000*exp(-0.005*t);
z2 = sin(a*t);
[haxes,hline1,hline2] = plotyy(t,z1,t,z2,'semilogy','plot');
ylabel(haxes(1),'Semilog Plot');
ylabel(haxes(2),'Linear Plot');
xlabel(haxes(2),'Time');
set(hline1,'LineStyle','--','LineWidth',2);
set(hline2,'LineWidth',2);
168
Contd.

Semi log
axes

Linear
axes

169
Plot3

• The plot3 function displays a three-dimensional plot of a


set of data points.
• Basic format:
plot3(X1,Y1,Z1);
• Example- Plot a 3-D helix.
t = 0:pi/50:10*pi;
st = sin(t);
ct = cos(t);
h=plot3(st,ct,t);

170
Contd.

z axes

x axes
y axes
171
Loglog

• Basic format:
loglog(x,y,LineSpec)
• It plots the y versus x using log scale on both axis.
• Example-
x = logspace(-1,2);
y = exp(x);
loglog(x,y,'-s');
grid on
• grid on adds major grid lines to the current axes.
• grid off removes all grid lines from the current axes.

172
Contd.

Log axes

173
Semilogx

• Basic format:
semilogx(x,y,LineSpec)
• semilogx plot data as logarithmic scales for the x-axis.
• Example-
x = 0:1000;
y = log(x);
semilogx(x,y);
grid on

174
Contd.

Linear axes

Semilog axes
175
Semilogy

• Basic format:
semilogy(x,y,LineSpec)
• semilogy plot data as logarithmic scales for the y-axis.
• Example-
x = 0:0.1:10;
y = exp(x);
semilogy(x,y);
grid on

176
Contd.

Semilog axes

177
Fplot

• fplot plots a function between specified limits.


• Basic format:
fplot(fun,limits,LineSpec)
• Example-
a= @tanh;
fplot(a,[-2,2])

178
Contd.

Limited by -2 to 2

179
Ezplot

• It is a easy-to-use function plotter.


• Formats:
• ezplot(fun) - plots the expression fun(x) over the default
domain -2π < x < 2π, where fun(x) is an explicit function of
only x.
• ezplot(fun,[xmin,xmax]) - plots fun(x) over the domain:
xmin < x < xmax.
• ezplot(fun,[xmin,xmax,ymin,ymax]) - plots fun(x,y) over
xmin < x < xmax and ymin < y < ymax.
• Example-
ezplot('x^2')

180
Contd.

181
Bar plot

• Types of bar plot:

• Example-
Y = [5,2,1 8,7,3 9,8,6 5,5,5 4,3,2];
bar(Y);

182
Contd.

Distribute the bars


along x axes

183
Contd.

• To stack the elements in a row, specify the stacked option


for the bar function.
>>bar(Y,'stacked');

Stacked the elements


in a row

184
Contd.

• To distributes bars along the y-axis.


>>barh(Y);

Distribute the bars


along y axes

185
Contd.

• To draws each element as a separate 3-D block and


distributes the elements of each column along the y-axis.
>>bar3(Y);

186
Contd.

• To stack the elements in a row, specify the stacked option


for the bar3 function.
>>bar3(Y,'stacked');

187
Contd.

• To draws each element as a separate 3-D block and


distributes the elements of each column along the z-axis.
>>bar3h(Y);

188
Pie graph

• pie(X) draws a pie chart using the data in X. Each element


in X is represented as a slice in the pie chart.
• If sum(X) ≤ 1, then the values in X directly specify the area
of the pie slices. pie draws only a partial pie if sum(X) < 1.
• If the sum of the elements in X is greater than one, then pie
normalizes the values by X/sum(X) to determine the area
of each slice of the pie.
• Example-
x = [1,3,0.5,2.5,2];
pie(x);

189
Contd.

190
Contd.

• To offset the second and fourth pie slices, set the


corresponding explode elements to 1.
• Example- explode = [0,1,0,1,0];
pie(x,explode);

Second pie slice Fourth pie slice

191
Contd.
• To specify the text labels for a pie chart.
• Example- x = 1:3;
labels ={'Taxes','Expenses','Profit'};
pie(x,labels);

192
Contd.

• To create a partial pie chart.


• Example-
x = [0.19,0.22,0.41];
pie(x);

• Since the sum of the elements in x is less than 1, pie draws


a partial pie.

193
Contd.

Fourth pie slice


is not present

194
Pie3

• It draws a three-dimensional pie chart using the data in X.


Each element in X is represented as a slice in the pie chart.
• If sum(X) ≤ 1, then the values in X directly specify the area
of the pie slices. pie3 draws only a partial pie if sum(X) < 1.
• If the sum of the elements in X is greater than one, then pie
normalizes the values by X/sum(X) to determine the area
of each slice of the pie.
• Example-
x = [1,3,0.5,2.5,2];
pie3(x);

195
Contd.

196
Contd.
• To offset the second pie slice, set the corresponding
explode element to 1.
• Example- explode = [0,1,0,0,0];
pie3(x,explode);

197
Area graph

• An area graph displays elements in Y as one or more curves


and fills the area beneath each curve. When Y is a matrix,
the curves are stacked showing the relative contribution of
each row element to the total height of the curve at each x
interval.
• area(Y) plots the vector Y or plots each column in matrix Y
as a separate curve and stacks the curves. The x-axis
automatically scales to 1:size(Y,1).
• area(X,Y) For vectors X and Y, area(X,Y) is the same as
plot(X,Y) except that the area between 0 and Y is filled.
When Y is a matrix, area(X,Y) plots the columns of Y as
filled areas. For each X, the net result is the sum of
corresponding values from the rows of Y.
198
Example

• Plot the data in matrix Y as an area graph.


• Example- Y = [1, 5, 3; 3, 2, 7; 1, 5, 3; 2, 6, 1];
area(Y); Stacked the second
Column with the
first column.

Plot the first


column of y matrix

199
Example

• By default, area uses the y-axis as the base value. Change


the base value by setting the basevalue input argument to -
4.
Y = [1, 5, 3; 3, 2, 7; 1, 5, 3; 2, 6, 1];
basevalue = -4;
area(Y,basevalue);

200
Contd.

Base value set


to -4

201
Stem plot

• stem(Y) plots the data sequence, Y, as stems that extend


from a baseline along the x-axis. The data values are
indicated by circles terminating each stem.
• stem(X,Y) plots the data sequence, Y, at values specified by
X. The X and Y inputs must be vectors or matrices of the
same size. Additionally, X can be a row or column vector
and Y must be a matrix with length(X) rows.

202
Example

• Create a stem plot of 50 data values between -2*pi and


2*pi.
Y = linspace(-2*pi,2*pi,50);
stem(Y);

203
Example

• Plot two data series using a two-column matrix.


X = linspace(0,2*pi,50)';
Y = [cos(X), 0.5*sin(X)]; Sine plot
stem(Y);

Cos plot

204
Example

• Plot 50 data values of cosine evaluated between 0 and specify the set
of x values for the stem plot.
X = linspace(0,2*pi,50)';
Y = cos(X);
stem(X,Y);

205
Example

• Plot 50 data values of sine and cosine evaluated between 0


and specify the set of x values for the stem plot.
X = linspace(0,2*pi,50)';
Y = [cos(X), 0.5*sin(X)]; Sine plot
stem(X,Y);

Cos plot

206
Example

• Plot 50 data values of sine and cosine evaluated at different


sets of x values. Specify the corresponding sets of x values
for each series.
x1 = linspace(0,2*pi,50)';
x2 = linspace(pi,3*pi,50)';
X = [x1, x2];
Y = [cos(x1), 0.5*sin(x2)];
stem(X,Y);

207
Contd.

Cos and sine plot


with different
x values

208
Example

• Create a stem plot and fill in the circles that terminate


X = linspace(0,10,20)';
Y = (exp(0.25*X));
stem(X,Y,'fill');

209
Example

• Create a figure with two subplots and return the handles to


each axes, s(1) and s(2). Create a stem plot in the lower
subplot by referring to its axes handle, s(2).
s(1) = subplot(2,1,1);
s(2) = subplot(2,1,2);
X = 0:25;
Y = [exp(0.1*X); -exp(.05*X)]';
stem(s(2),X,Y);

210
Contd.
S(1) subplot

S(2) subplot

211
Stair step graph

• stairs(Y) draws a stairstep graph of the elements in Y.


• If Y is a vector, then the x-axis scale ranges from 1 to
length(Y).
• If Y is a matrix, then stairs draws one line per matrix
column and the x-axis scale ranges from 1 to the number of
rows in Y.
• stairs(X,Y) plots the elements in Y at the locations specified
in X. The inputs X and Y must be vectors or matrices of the
same size. Additionally, X can be a row or column vector
and Y must be a matrix with length(X) rows

212
Example

• Create a stairstep plot of sine evaluated at 40 equally


spaced values between 0 and 4*pi.
X = linspace(0,4*pi,40);
Y = sin(X);
stairs(Y);

213
Example

• Create a stairstep plot of two cosine functions evaluated at


50 equally spaced values between 0 and 4*pi.
X = linspace(0,4*pi,50)';
Y = [0.5*cos(X), 2*cos(X)]; 2*cos(X)
stairs(Y);

0.5*cos(X)

214
Example

• Create a stairstep plot of two cosine waves evaluated at


equally spaced values between 0 and . Specify the set of x-
values for the plot.

X = linspace(0,4*pi,50)';
Y = [0.5*cos(X), 2*cos(X)];
stairs(X,Y);

215
Example

• Create a stairstep plot of two sine waves evaluated at


different values. Specify a unique set of x-values for
plotting each data series.

x1 = linspace(0,2*pi)';
x2 = linspace(0,pi)';
X = [x1,x2];
Y = [sin(5*x1),exp(x2).*sin(5*x2)];
stairs(X,Y);

216
Contd.

exp(x2).*sin(5*x2)
sin(5*x1)

217
Example

• Create a figure with two subplots and return the two axes
handles, s(1) and s(2). Create a stairstep plot in each
subplot by referring to the axes handles.
s(1) = subplot(2,1,1);
s(2) = subplot(2,1,2);
X = linspace(0,2*pi);
Y1 = 5*sin(X);
Y2 = sin(5*X);
stairs(s(1),X,Y1);
stairs(s(2),X,Y2);

218
Contd.

5*sin(X)

sin(5*X)

219
Stem3

• stem3(Z) plots entries in Z as stems extending from the xy-


plane and terminating with circles at the entry values. The
stem locations in the xy-plane are automatically generated.
• stem3(X,Y,Z) plots entries in Z as stems extending from the
xy-plane where X and Y specify the stem locations in the xy-
plane. The inputs X, Y, and Z must be vectors or matrices of
the same size.

220
Example

• Create a 3-D stem plot of cosine values between and with a


row vector input.
X = linspace(-pi/2,pi/2,40);
Z = cos(X);
stem3(Z);

221
Example

• Create a 3-D stem plot of sine and cosine values –pi/2


between pi/2 and with a matrix input.
X = linspace(-pi/2,pi/2,40);
Z = [sin(X); cos(X)];
stem3(Z);

222
Example

• Create a 3-D stem plot and specify the stem locations along
a curve. Use view to adjust the angle of the axes in the
figure.
X = linspace(-5,5,60);
Y = cos(X);
Z = X.^2;
stem3(X,Y,Z);
view(-8,30);

223
Example

• Create a 3-D stem plot with matrix data and specify the
stem locations in the xy-plane.
[X,Y] = meshgrid(0:.1:1);
Z = exp(X+Y);
stem3(X,Y,Z);

224
Example

• Create a 3-D stem plot of cosine values between -pi and pi .


Use 'fill' to fill in the markers.
X = linspace(-pi,pi,40);
Z = cos(X);
stem3(Z,'fill');

225
Example

• Create a 3-D stem plot and specify the stem locations along
a circle. Set the stem to a dotted line style, the marker
symbols to stars, and the color to magenta.

theta = linspace(0,2*pi);
X = cos(theta);
Y = sin(theta);
Z = theta;
stem3(X,Y,Z,':*m');

226
Contd.

Marker style symbol

Dotted line style

227
Scatter plot

• Scatter(X,Y) displays circles at the locations specified by


the vectors X and Y. This type of graph is also known as a
bubble plot.
• Scatter(X,Y,S) draws each circle with the size specified by S.
To plot each circle with equal size, specify S as a scalar. To
plot each circle with a specific size, specify S as a vector
with length equal to the length of X and Y.
• Scatter(X,Y,S,C) draws each circle with the color specified
by C.

228
Example

• Define x to contain 200 equally spaced values between 0


and . Initialize the random-number generator to make the
output of rand repeatable, and define y to contain cosine
values with random noise.
x = linspace(0,3*pi,200);
y = cos(x)+ rand(1,200);
scatter(x,y);

229
Example

• Vary circle size and color.


s = linspace(1,50,length(x)); Large size circles
c = linspace(1,10,length(x));
scatter(x,y,s,c);
zoom(2);

Small size circles

230
Example

• To fill the circles.


scatter(x,y,s,c,'fill');

Large size filled circles

Small size
filled circles

231
Example

• Create a figure with two subplots and return the handles to


the two subplot axes in array hs. Create a scatter plot in the
upper subplot using the axes handle, hs(1). In the lower
subplot, create another scatter plot from the same data
sample and use filled, diamond markers.
hs(1) = subplot(1,2,1);
hs(2) = subplot(1,2,2);
s = 30;
c = linspace(1,10,length(x));
scatter(hs(1),x,y,s,c);
scatter(hs(2),x,y,s,c,'fill','d');
232
Example

Subplot 2
Subplot 1

Diamond
Circle marker marker

233
Scatter3

• Scatter3(X,Y,Z) displays circles at the locations specified by


the vectors X, Y, and Z.
• Scatter3(X,Y,Z,S) draws each circle with the size specified
by S. To plot each circle with equal size, specify S as a
scalar. To plot each circle with a specific size, specify S as a
vector.
• Scatter3(X,Y,Z,S,C) draws each circle with the color
specified by C.

234
Example

• Create a 3-D scatter plot. Use sphere to define vectors x, y,


and z.

[X,Y,Z] = sphere(16);
x = [0.5*X(:); 0.75*X(:); X(:)];
y = [0.5*Y(:); 0.75*Y(:); Y(:)];
z = [0.5*Z(:); 0.75*Z(:); Z(:)];
scatter3(x,y,z);

235
Contd.

Z-axis

Y-axis X-axis
236
Example

• Vary marker size, marker color and fill the marker.

S = repmat([50,25,10],numel(X),1);
C = repmat([1,2,3],numel(X),1);
s = S(:);
c = C(:);
scatter3(x,y,z,s,c, 'fill');

237
Contd.

Large size filled circles


Small size filled circles

238
Polar coordinate plot

• The polar function accepts polar coordinates, plots them in


a Cartesian plane, and draws the polar grid on the plane.
• Polar(theta,rho) creates a polar coordinate plot of the
angle theta versus the radius rho. theta is the angle from
the x-axis to the radius vector specified in radians; rho is
the length of the radius vector specified in data space units.
• polar(theta,rho,LineSpec) LineSpec specifies the line type,
plot symbol, and color for the lines drawn in the polar plot.

239
Example

• Create a simple polar plot using a dashed red line.


theta = 0:0.01:2*pi;
rho = sin(2*theta).*cos(2*theta);
polar(theta,rho,'--r');

240
Ezpolar

• It is easy-to-use polar coordinate plotter.


• Ezpolar(fun) plots the polar curve rho = fun(theta) over the
default domain 0 < theta < 2π.
• Where, fun can be a function handle or a string.
• Example- Plot the function 1+cos(t) over the domain [0,
2π] .
ezpolar('1+cos(t)');

241
Contd.

242
Contour plot

• A contour plot displays isolines of matrix Z.


• Contour(Z) draws a contour plot of matrix Z, where Z is
interpreted as heights with respect to the x-y plane.
• Contour(X,Y,Z), contour(X,Y,Z,n), and contour(X,Y,Z,v) draw
contour plots of Z using X and Y to determine the x- and y-
axis limits.
• If X and Y are vectors, then the length of X must equal the
number of columns in Z and the length of Y must equal the
number of rows in Z.
• If X and Y are matrices, then their sizes must equal the size
of Z.

243
Example

• Use the meshgrid function to generate matrices X and Y.


Create a third matrix, Z, and plot its contours.

x = linspace(-2*pi,2*pi);
y = linspace(0,4*pi);
[X,Y] = meshgrid(x,y);
Z = sin(X)+cos(Y);
contour(X,Y,Z);

244
Contd.

245
Example

• Store the data from the peaks function in matrices X, Y, and


Z. Plot 20 contours of the data in Z.
[X,Y,Z] = peaks;
contour(X,Y,Z,20);

246
Example
• Set up matrices X, Y, and Z. Create a contour plot and
display the contour labels by setting the ‘show text’
property to on.

x = -2:0.2:2; y = -2:0.2:3;
[X,Y] = meshgrid(x,y);
Z = X.*exp(-X.^2-Y.^2);
contour(X,Y,Z,'ShowText','on‘);

247
Example

• Create a contour plot of the peaks function and display


only one contour level at Z = 1.
x = -3:0.125:3;
y = -3:0.125:3;
[X,Y] = meshgrid(x,y);
Z = peaks(X,Y);
v = [1,1];
contour(X,Y,Z,v);

248
Contourf

• This is a filled 2-D contour plot.


• Example- Use the peaks function to define z as a 20-by-20
matrix. Create a filled contour plot of z with 10 contour
lines.
Z = peaks(20);
contourf(Z,10);

249
Contour3

• It creates a 3-D contour plot of a surface defined on a


rectangular grid.
• Example- Set up matrices X and Y using the meshgrid
function. Plot 30 contours of matrix Z.

x = -2:0.25:2;
[X,Y] = meshgrid(x);
Z = X.*exp(-X.^2-Y.^2);
contour3(X,Y,Z,30);

250
Contd.

251

You might also like