Sie sind auf Seite 1von 47

Introduction to MATLAB II

CpE251L/253 Digital Signal Processing


Lecture 2
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 NOT persist after you exit MATLAB. Save
using
save filename.mat

Workspace
Use the clear command to clear all the variables from the
workspace.
Restore data from a MAT-file into the workspace using load.
load myfile.mat
Character Strings
Sequence of any number of characters enclosed in single quotes.
You can assign a string to a variable.
myText = 'Hello, world';
If the text includes a single quote, use two single quotes within the
definition.
otherText = 'You''re right'

otherText =
You're right
Character Strings
Uses
Output commands to display text messages
Formatting commands of plots

Character Strings
myText and otherText are arrays, like all MATLAB variables.
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 you
concatenate numeric arrays.

longText = [myText,' - ',otherText]

longText =

Hello, world - You're right
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
Character Strings
It is also possible to change specific elements by addressing them
directly
>> B(12:21)=Will Smith'
B =
My name is Will Smith
>>
Character Strings
Strings can also be placed in a matrix
Done by typing a semicolon ; (or pressing the Enter key) at the end of
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 spaces to shorter rows to match the longest row
Character Strings
>> Info = ['Student Name:' ; 'John Smith ' ; 'Grade:
' ; 'A+ ]

Info =
Student Name:
John Smith
Grade:
A+
>>
Character Strings
char
MATLAB makes the length of all the rows equal to that of the longest row
Automatically adds spaces at the end of the short lines.
Enter rows are as strings separated by a comma.
>> Info=char('Student Name:','John
Smith','Grade:','A+')
Info =
Student Name:
John Smith
Grade:
A+
>>
Character Strings
Variables can be defined as either a number or a string made up of
the same digits
>> x=536
x =
536
>> y='536'
y =
536
>>
Character Strings
To convert numeric values to strings, use functions, such as
num2str or int2str.
f = 71;
c = (f-32)/1.8;
tempText = ['Temperature is ',num2str(c),'C']

tempText =

Temperature is 21.6667C
Functions
MATLAB provides a large number of functions that perform
computational tasks.
Equivalent to subroutines or methods in other programming
languages.
Example: Assume we have A and B, such as
A = [1 3 5];
B = [10 6 4];
Functions
To call a function, enclose its input arguments in parentheses
max(A);
If there are multiple input arguments, separate them with commas:
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 square
brackets:
[maxA,location] = max(A);
Functions
Enclose any character string inputs in single quotes:
disp('hello world');
To call a function that does not require any inputs and does not
return any outputs, type only the function name:
clc
Note: clc function clears the Command Window.
Plots
Line Plots
To create 2D line plots, use the plot function.
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)
Plots
Line Plots Example 2
Sine function from 0 to 2.

x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y)

Plots
Adding labels
Use the commands xlabel, ylabel, and title to add the necessary
captions/labels.

xlabel('x')
ylabel('sin(x)')
title('Plot of the Sine Function')
Plots
You specify the color and style of the line and the color and type of
markers.
plot(x,y,line
specifiers,PropertyName,PropertyValue)
Line specifiers - specifiers that define the type and color of the line and
markers.
Property Name & Property Value - can be used to specify the line width, and
a markers size and edge, and fill colors.
Plots
Line Specifiers (Line Styles and Color)
Plots
Line Specifiers (Marker Type)
Plots
Examples
plot(x,y,r)

plot(x,y,--y)

plot(x,y,*)

plot(x,y,g:d)
Plots
Property Name and Property
Value
Specifies the thickness of the
line, the size of the marker, and
the colors of the markers edge
line and fill.

Try:
plot(x,y,'--r*','linewidth',2,'markersize',12)
Plots
By adding a third input argument to the plot function, you can plot
the 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 marker

Plots
Plots a function with the form y = f(x).
fplot(function,limits,line specifiers)
Function - function to be plotted
Limits - domain of x and, optionally, the limits of the y axis
Line specifiers already discussed earlier
Plots
Example:
Plot of the function for y = x
2
+ 4sin(2x) 1 for -3 x 3
>> fplot('x^2+4*sin(2*x)-1',[-3 3])
Plots
Two or more graphs can be created in the same plot
Type pairs of vectors inside the plot command
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:)
Plots
Plot the following functions given the limits -2 x 2 (with each
elements of x having a distance of 0.01) in the same plot
y
1
= x2 + 3
y
2
= 4x + 5
y
3
= 10 sin(x)

Plots
By default, MATLAB clears the figure each time you call a plotting function
Reset the axes and other elements to prepare the new plot.
To add plots to an existing figure, use hold. Add the following codes to the
previous one.
hold on
y2 = cos(x);
plot(x,y2,'r:')
legend('sin','cos')
All plots appear in the current figure window until you use hold off or
close the window.

Plots
line command
Add graphs to a plot that already exists
line(x,y,PropertyName,PropertyValue)
Do Slide 29 using the line command.
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)')
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')
Plots with Special Graphics
Stairs Plot
yr=[1988:1994];
sle=[8 12 20 22 18 24 27];
stairs(yr,sle)
Plots with Special Graphics
Stem Plot
yr=[1988:1994];
sle=[8 12 20 22 18 24 27];
stem(yr,sle)
Plots with Special Graphics
Pie Plot
grd=[11 18 26 9 5];
pie(grd)
title('Class Grades')
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 bin

hist(y)
y - vector with the data points
MATLAB divides the range of the data points into 10 equally spaced
subranges.
Plots with Special Graphics
Histograms
>> y=[58 73 73 53 50 48 56 73 73 66 69 63 74 82 84 91
93 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
Plots with Special Graphics
Histograms
Number of bins can be defined
hist(y,nbins)
hist(y,x)
nbins - scalar that defines the number of bins
x - vector that 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)

Plots with Special Graphics
Histograms
hist command can be used with options that provide numerical output in
addition to plotting a histogram
n=hist(y)
n=hist(y,nbins)
n=hist(y,x)
Output n is vector.
n shows how many elements are in each bin
Plots with Special Graphics
Histograms
You can also output the center of the bins.
[n xout]=hist(y)
[n xout]=hist(y,nbins)

Multiple Plots On The Same Page
Multiple plots can be created on the same page with the subplot
command
subplot(m,n,p)
Creates m x n rectangular subplots.
Multiple Figure Windows
>> fplot('x*cos(x)',[0,10])
>> figure
>> fplot('exp(-0.2*x)*cos(x)',[0,10])

Additional commands
close closes the active Figure Window.
close(n) closes the nth Figure Window.
close all closes all Figure Windows that are open.
3-D Plots
Three-dimensional plots typically display a surface defined by a
function in two variables, z = f (x,y).
To evaluate z, first create a set of (x,y) points over the domain of
the 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)
3-D Plots
surf displays both the connecting lines and the faces of the surface
in color.
mesh produces wireframe surfaces that color only the lines
connecting the defining points.
Subplots
Display multiple plots in different subregions of the same window
using the subplot function.
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');
Subplots
subplot(2,2,4)
First two inputs to the subplot function indicate the number of plots in
each row and column.
Third input specifies which plot is active.

Das könnte Ihnen auch gefallen