Upload
mark-claracay
View
228
Download
0
Embed Size (px)
Citation preview
8/11/2019 CpE253 - Lecture 2 - Introduction to MATLAB
1/47
Introduction to MATLABCpE251L/253Digital Signal Processing
Lecture 2
8/11/2019 CpE253 - Lecture 2 - Introduction to MATLAB
2/47
Workspace
Contains variables You created within
Imported into MATLAB from data files or other programs
Example: Create variables A and B in the workspace.
A = magic(4);
B = rand(3,5,2); View the contents of the workspace using whos.
Variables also appear in the Workspace pane.
Workspace variables do NOTpersist after you exit MATLAB. using
save filename.mat
8/11/2019 CpE253 - Lecture 2 - Introduction to MATLAB
3/47
Workspace
Use the clearcommand to clear all the variables from theworkspace.
Restore data from a MAT-file into the workspace using loa
load myfile.mat
8/11/2019 CpE253 - Lecture 2 - Introduction to MATLAB
4/47
8/11/2019 CpE253 - Lecture 2 - Introduction to MATLAB
5/47
Character Strings
Uses Output commands to display text messages
Formatting commands of plots
8/11/2019 CpE253 - Lecture 2 - Introduction to MATLAB
6/47
Character Strings
myTextand otherTextare arrays, like all MATLAB varia Each character, including a space, is an element in the array.
Data type is char(character)
You can concatenate strings with square brackets, just as yoconcatenate numeric arrays.
longText = [myText,' - ',otherText]
longText =
Hello, world - You're right
8/11/2019 CpE253 - Lecture 2 - Introduction to MATLAB
7/47
Character Strings
The elements of the vectors are addressed by position.>> B='My name is John Barry'
B =
My name is John Barry
>>
>> B(4)
ans =
n
>> B(12)
ans =
J
8/11/2019 CpE253 - Lecture 2 - Introduction to MATLAB
8/47
Character Strings
It is also possible to change specific elements by addressingdirectly>> B(12:21)=Will Smith'
B =
My name is Will Smith
>>
8/11/2019 CpE253 - Lecture 2 - Introduction to MATLAB
9/47
Character Strings
Strings can also be placed in a matrix Done by typing a semicolon; (or pressing the Enter key) at
each row.
Each row must be typed as a string
Must be enclosed in single quotes
All rows must have the same number of elements Add spacesto shorter rows to match the longest row
8/11/2019 CpE253 - Lecture 2 - Introduction to MATLAB
10/47
Character Strings
>> Info = ['Student Name:' ; 'John Smith ' ;' ; 'A+ ]
Info =
Student Name:
John Smith
Grade:A+
>>
8/11/2019 CpE253 - Lecture 2 - Introduction to MATLAB
11/47
Character Strings
char MATLAB makes the length of all the rows equal to that of the long
Automatically adds spaces at the endof the short lines.
Enter rows are as strings separated by a comma.
>> Info=char('Student Name:','JohnSmith','Grade:','A+')
Info =
Student Name:
John Smith
Grade:
A+
>>
8/11/2019 CpE253 - Lecture 2 - Introduction to MATLAB
12/47
Character Strings
Variables can be defined as either a number or a string madthe samedigits
>> x=536
x =
536
>> y='536'
y =
536
>>
8/11/2019 CpE253 - Lecture 2 - Introduction to MATLAB
13/47
Character Strings
To convert numeric values to strings, use functions, such asnum2stror int2str.
f = 71;
c = (f-32)/1.8;
tempText = ['Temperature is ',num2str(c),'C']
tempText =
Temperature is 21.6667C
8/11/2019 CpE253 - Lecture 2 - Introduction to MATLAB
14/47
Functions
MATLAB provides a large number of functions that performcomputational tasks.
Equivalent to subroutinesor methodsin other programminlanguages.
Example: Assume we have Aand B, such as
A = [1 3 5]; B = [10 6 4];
8/11/2019 CpE253 - Lecture 2 - Introduction to MATLAB
15/47
Functions
To call a function, enclose its input arguments in parenthesemax(A);
If there are multiple input arguments, separate them with c
max(A,B);
Return output from a function by assigning it to a variable:
maxA = max(A); When there are multiple output arguments, enclose them in
brackets:
[maxA,location] = max(A);
8/11/2019 CpE253 - Lecture 2 - Introduction to MATLAB
16/47
Functions
Enclose any character string inputs in single quotes:disp('hello world');
To call a function that does not require any inputs and does return any outputs, type only the function name:
clc
Note: clcfunction clears the Command Window.
8/11/2019 CpE253 - Lecture 2 - Introduction to MATLAB
17/47
Plots
Line Plots To create 2D line plots, use the plotfunction.
Example:
X = [1 2 3 5 7 7.5 8 10];
Y = [2 6.5 7 7 5.5 4 6 8];
plot(X,Y)
8/11/2019 CpE253 - Lecture 2 - Introduction to MATLAB
18/47
Plots
Line Plots Example 2
Sine function from 0 to 2.
x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y)
8/11/2019 CpE253 - Lecture 2 - Introduction to MATLAB
19/47
Plots
Adding labels
Use the commandsxlabel, ylabel, and titleto add the necaptions/labels.
xlabel('x')
ylabel('sin(x)')
title('Plot of the Sine Function')
8/11/2019 CpE253 - Lecture 2 - Introduction to MATLAB
20/47
Plots
You specify the color and style of the line and the color andmarkers.
plot(x,y,linespecifiers,PropertyName,PropertyValue)
Line specifiers - specifiers that define the type and color of the linmarkers.
Property Name & Property Value - can be used to specify the line a markers size and edge, and fill colors.
8/11/2019 CpE253 - Lecture 2 - Introduction to MATLAB
21/47
Plots
Line Specifiers (Line Styles and Color)
8/11/2019 CpE253 - Lecture 2 - Introduction to MATLAB
22/47
Plots
Line Specifiers (Marker Type)
8/11/2019 CpE253 - Lecture 2 - Introduction to MATLAB
23/47
Plots
Examples
plot(x,y,r)
plot(x,y,--y)
plot(x,y,*)
plot(x,y,g:d)
8/11/2019 CpE253 - Lecture 2 - Introduction to MATLAB
24/47
Plots
Property Name and PropertyValue
Specifies the thickness of theline, the size of the marker, andthe colors of the markers edgeline and fill.
Try:
plot(x,y,'--r*','linewidth',2,'markersize',12
8/11/2019 CpE253 - Lecture 2 - Introduction to MATLAB
25/47
Plots
By adding a third input argument to the plotfunction, youthe same variables using a red dashed line.
plot(x,y,'r--')
The 'r--' string is a line specification.
Specification can include characters for the line color, style, and m
8/11/2019 CpE253 - Lecture 2 - Introduction to MATLAB
26/47
Plots
Plots a function with the form y = f(x).fplot(function,limits,linespecifiers)
Function - function to be plotted
Limits - domain of x and, optionally, the limits of the y axis
Line specifiersalready discussed earlier
8/11/2019 CpE253 - Lecture 2 - Introduction to MATLAB
27/47
Plots
Example:
Plot of the function for y = x2+ 4sin(2x)1 for -3 x 3
>> fplot('x^2+4*sin(2*x)-1',[-3 3])
8/11/2019 CpE253 - Lecture 2 - Introduction to MATLAB
28/47
Plots
Two or more graphs can be created in the same plot
Type pairs of vectors inside the plotcommand
plot(x,y,u,v,t,h)
Creates three graphsy vs. x, v vs. u, and h vs. t in the same plot
Vectors of each pair must be of the same length
MATLAB automatically plots the graphs in different colors
It is also possible to add line specifiers following each pair plot(x,y,-b,u,v,--r,t,h,g:)
8/11/2019 CpE253 - Lecture 2 - Introduction to MATLAB
29/47
Plots
Plot the following functions given the limits -2 x 2 (with elements of x having a distance of 0.01) in the same plot
y1= x2 + 3
y2= 4x + 5
y3= 10 sin(x)
8/11/2019 CpE253 - Lecture 2 - Introduction to MATLAB
30/47
Plots
By default, MATLAB clears the figure each time you call a plottin
Reset the axes and other elements to prepare the new plot.
To add plots to an existing figure, use hold. Add the following cprevious one.
hold on
y2 = cos(x);
plot(x,y2,'r:')
legend('sin','cos')
All plots appear in the current figure window until you use holclose the window.
8/11/2019 CpE253 - Lecture 2 - Introduction to MATLAB
31/47
Plots
linecommand
Add graphs to a plot that already exists
line(x,y,PropertyName,PropertyValue)
Do Slide 29 using the linecommand.
8/11/2019 CpE253 - Lecture 2 - Introduction to MATLAB
32/47
Plots with Special Graphics
Vertical Bar plots
yr=[1988:1994];
sle=[8 12 20 22 18 24 27];
bar(yr,sle,'r')
xlabel('Year')
ylabel('Sales (Millions)')
8/11/2019 CpE253 - Lecture 2 - Introduction to MATLAB
33/47
Plots with Special Graphics
Horizontal Bar Plot
yr=[1988:1994];
sle=[8 12 20 22 18 24 27];
barh(yr,sle)
xlabel('Sales (Millions)')
ylabel('Year')
8/11/2019 CpE253 - Lecture 2 - Introduction to MATLAB
34/47
Plots with Special Graphics
Stairs Plot
yr=[1988:1994];
sle=[8 12 20 22 18 24 27];
stairs(yr,sle)
8/11/2019 CpE253 - Lecture 2 - Introduction to MATLAB
35/47
Plots with Special Graphics
Stem Plot
yr=[1988:1994];
sle=[8 12 20 22 18 24 27];
stem(yr,sle)
8/11/2019 CpE253 - Lecture 2 - Introduction to MATLAB
36/47
Plots with Special Graphics
Pie Plot
grd=[11 18 26 9 5];
pie(grd)
title('Class Grades')
8/11/2019 CpE253 - Lecture 2 - Introduction to MATLAB
37/47
Plots with Special Graphics
Histograms
Shows the distribution of data
Shows how many data points are in each bin
Width of each bar is equal to the range of the corresponding bin
Height of the bar corresponds to the number of data points in the
hist(y) y - vector with the data points
MATLAB divides the range of the data points into 10 equally spacesubranges.
8/11/2019 CpE253 - Lecture 2 - Introduction to MATLAB
38/47
Plots with Special Graphics
Histograms
>> y=[58 73 73 53 50 48 56 73 73 66 69 63 74 893 89 91 80 59 69 56 64 63 66 64 74 63 69];
>> hist(y)
Smallest value in the data set is 48 and the largest is 93
Range is 45 and the width of each bin is 4.5
Range of the first bin is from 48 to 52.5 and contains two points
Range of the second bin is from 52.5 to 57 and contains three points
Two of the bins (75 to 79.5 and 84 to 88.5) do not contain any points
8/11/2019 CpE253 - Lecture 2 - Introduction to MATLAB
39/47
Plots with Special Graphics
Histograms Number of bins can be definedhist(y,nbins)
hist(y,x)
nbins - scalarthat defines the number of bins
x - vectorthat specifies the location of the center of each bin
>> hist(y,3)
>> x=[45:10:95]
x =
45 55 65 75 85 95
>> hist(y,x)
8/11/2019 CpE253 - Lecture 2 - Introduction to MATLAB
40/47
8/11/2019 CpE253 - Lecture 2 - Introduction to MATLAB
41/47
Plots with Special Graphics
Histograms
You can also output the center of the bins.
[n xout]=hist(y)
[n xout]=hist(y,nbins)
8/11/2019 CpE253 - Lecture 2 - Introduction to MATLAB
42/47
Multiple Plots On The Same Page
Multiple plots can be created on the same page with the su
command subplot(m,n,p)
Creates mx nrectangular subplots.
8/11/2019 CpE253 - Lecture 2 - Introduction to MATLAB
43/47
Multiple Figure Windows
>> fplot('x*cos(x)',[0,10])
>> figure>> fplot('exp(-0.2*x)*cos(x)',[0,10])
Additional commands
closecloses the active Figure Window.
close(n)closes the nth Figure Window. close all closes all Figure Windows that are open.
8/11/2019 CpE253 - Lecture 2 - Introduction to MATLAB
44/47
3-D Plots
Three-dimensional plots typically display a surface defined b
function in two variables, z = f (x,y).
To evaluate z, first create a set of (x,y) points over the dthe function using meshgrid.
[X,Y] = meshgrid(-2:.2:2);
Z = X .* exp(-X.^2 - Y.^2);
Then, create a surface plot.surf(X,Y,Z)
8/11/2019 CpE253 - Lecture 2 - Introduction to MATLAB
45/47
3-D Plots
surfdisplays both the connecting lines and the faces of th
in color.
meshproduces wireframe surfaces that color only the linesconnecting the defining points.
8/11/2019 CpE253 - Lecture 2 - Introduction to MATLAB
46/47
Subplots
Display multiple plots in different subregions of the same w
using the subplotfunction.
Create four plots in a 2-by-2 grid within a figure window
t = 0:pi/10:2*pi;
[X,Y,Z] = cylinder(4*cos(t));
subplot(2,2,1); mesh(X); title('X');
subplot(2,2,2); mesh(Y); title('Y');subplot(2,2,3); mesh(Z); title('Z');
subplot(2,2,4); mesh(X,Y,Z); title('X,Y,Z');
8/11/2019 CpE253 - Lecture 2 - Introduction to MATLAB
47/47
Subplots
subplot(2,2,4)
First two inputs to the subplotfunction indicate the number of each row and column.
Third input specifies which plot is active.