You are on page 1of 104

Matlab Plots

Part 1 2D plots

MATLAB has many functions and commands that can be used to create various
types of plots. Some examples like below ones:

What kind of graphics is possible in Matlab?

Polar plot:
t=0:.01:2*pi;
polar(t,abs(sin(2*t).*cos(2*t)));

Line plot:
x=0:0.05:5;,y=sin(x.^2);,plot(x,y);

Stem plot:
x = 0:0.1:4;, y = sin(x.^2).*exp(-x);
stem(x,y)

What kind of graphics is possible in Matlab?

Mesh plot:
z=peaks(25);, mesh(z);

Spherical harmonic: spharm2

Surface plot:
z=peaks(25);, surf(z);, colormap(jet);

Contour plot:
z=peaks(25);,contour(z,16);

2D Plots

EXAMPLE OF A 2-D PLOT

Plot title

Legend

Light Intensity as a Function of Distance


1200
Theory
Experiment

y axis
label

1000

Text

Tick-mark

INTENSITY (lux)

800
Comparison between theory and experiment.
600

400

Data symbol
known as
marker

200

10

12

x axis
label

14

16
DISTANCE (cm)

18

20

22

24

Tick-mark label

PLOT OF GIVEN DATA


Given data:

7.5

10

6.5

5.5

A plot can be created by the commands shown below. This can be done in the
Command Window, or by writing and then running a script file.

>> x=[1 2 3 5 7 7.5 8 10];


>> y=[2 6.5 7 7 5.5 4 6 8];
>> plot(x,y)

Once the plot command is executed, the Figure Window opens this plot.

LINE SPECIFIERS IN THE plot() COMMAND


plot(x,y,line specifiers)

Line
Style
Solid
dotted
dashed
dash-dot

Specifier

:
--.

Line
Color
red
green
blue
Cyan
magenta
yellow
black

Specifier

r
g
b
c
m
y
k

Marker Specifier
Type
plus sign
circle
asterisk
point
square
diamond

+
o
*
.
s
d

PLOT OF GIVEN DATA USING LINE SPECIFIERS IN


THE plot() COMMAND
Year

1988

1989

1990

1991

1992

1993

1994

Sales (M)

127

130

136

145

158

178

211

>> year = [1988:1:1994];


>> sales = [127, 130, 136, 145, 158, 178, 211];
>> plot(year,sales,'--r*')

Line Specifiers:
dashed red line and
asterisk markers.

CREATING A PLOT OF A FUNCTION


Consider:

0.5 x

y 3.5

cos(6x)

for 2 x 4

A script file for plotting the function is:


% A script file that creates a plot of
% the function: 3.5^(-0.5x)*cos(6x)
x = [-2:0.01:4];

Creating a vector with spacing of 0.01.

y = 3.5.^(-0.5*x).*cos(6*x);
plot(x,y)

Calculating a value of y
for each x.

Once the plot command is executed, the Figure Window opens with the following
plot.

A PLOT OF A FUNCTION
0.5 x

y 3.5

cos(6x)

for 2 x 4

CREATING A PLOT OF A FUNCTION


If the vector x is created with large spacing, the graph is not accurate.
Below is the previous plot with spacing of 0.3.

x = [-2:0.3:4];
y = 3.5.^(-0.5*x).*cos(6*x);
plot(x,y)

USING THE plot() COMMAND TO PLOT


MULTIPLE GRAPHS IN THE SAME PLOT

plot(x,y,u,v,t,h)
Plots three graphs in the same plot:

y versus x, v versus u,

and h versus t.

By default, MATLAB makes the curves in different colors.


Additional curves can be added.
The curves can have a specific style by adding specifiers after
each pair, for example:

plot(x,y,-b,u,v,r,t,h,g:)

USING THE plot() COMMAND TO PLOT


MULTIPLE GRAPHS IN THE SAME PLOT
and its first and second
y 3x3 26x 10
2 x 4 , all in the same plot.

Plot of the function,

derivatives, for
x = [-2:0.01:4];
y = 3*x.^3-26*x+6;

yd = 9*x.^2-26;

vector x with the domain of the function.


Vector
y with the function value at each x.
2 x 4
Vector yd with values of the first derivative.

ydd = 18*x;

Vector ydd with values of the second derivative.


2 x 4
plot(x,y,'-b',x,yd,'--r',x,ydd,':k')

Create three graphs, y vs. x (solid blue line), yd vs.

x (dashed red line), and ydd vs. x (dotted black


line) in the same figure.

USING THE hold on, hold off, COMMANDS


TO PLOT MULTIPLE GRAPHS IN THE SAME PLOT
Plot of the function,
for

y 3x3 26x 10 and its first and second derivatives,

2 x 4

all in the same plot.

x = [-2:0.01:4];
y = 3*x.^3-26*x+6;
yd = 9*x.^2-26;
ydd = 18*x;
plot(x,y,'-b')
hold on

First graph is created.

plot(x,yd,'--r')

plot(x,ydd,':k')
hold off

Two more graphs are created.

FORMATTING PLOTS
A plot can be formatted to have a required appearance.

With formatting you can:


Add title to the plot.
Add labels to axes.
Change range of the axes.
Add legend.
Add text blocks.
Add grid.

FORMATTING COMMANDS
title(string)
Adds the string as a title at the top of the plot.

xlabel(string)
Adds the string as a label to the x-axis.

ylabel(string)
Adds the string as a label to the y-axis.

axis([xmin xmax ymin ymax])


Sets the minimum and maximum limits of the x- and y-axes.

FORMATTING COMMANDS
legend(string1,string2,string3)
Creates a legend using the strings to label various curves (when
several curves are in one plot). The location of the legend is
specified by the mouse.

text(x,y,string)
Places the string (text) on the plot at coordinate x,y relative to
the plot axes.

gtext(string)
Places the string (text) on the plot. When the command
executes the figure window pops and the text location is clicked
with the mouse.

EXAMPLE OF A FORMATTED PLOT


Below is a script file of the formatted light intensity plot (2nd slide).
(Some of the formatting options were not covered in the lectures, but are
described in the book)
x=[10:0.1:22];

Creating vector x for plotting the theoretical curve.

y=95000./x.^2;

Creating vector y for plotting the theoretical curve.

xd=[10:2:22];

Creating a vector with coordinates of data points.


yd=[950 640 460 340 250 180 140];
Creating a vector with light
intensity from data.
plot(x,y,'-','LineWidth',1.0)
hold on
plot(xd,yd,'ro--','linewidth',1.0,'markersize',10)
hold off

EXAMPLE OF A FORMATTED PLOT


Formatting of the light intensity plot (cont.)

xlabel('DISTANCE (cm)')

Labels for the axes.

ylabel('INTENSITY (lux)')

Title for the plot.


title('\fontname{Arial}Light Intensity as a Function of Distance','FontSize',14)
axis([8 24 0 1200])
text(14,700,'Comparison between theory and
experiment.','EdgeColor','r','LineWidth',2)

Setting limits of the axes.

legend('Theory','Experiment',0)

Creating text.

Creating a legend.
The plot that is obtained is shown again in the next slide.

THE fplot COMMAND


The fplot command can be used to plot a function
with the form: y

= f(x)

fplot(function,limits)
The function is typed in as a string.
The limits is a vector with the domain of x, and optionally with limits
of the y axis:

[xmin,xmax]

or

[xmin,xmax,ymin,ymax]

Line specifiers can be added.

PLOT OF A FUNCTION WITH THE fplot() COMMAND


A plot of:

y x 2 4 sin(2x) 1

>> fplot('x^2 + 4 * sin(2*x) - 1', [-3 3])

for 3 x 3

fplot(@(x) sin(x+pi/5),'Linewidth',2);
hold on
fplot(@(x) sin(x-pi/5),'--or');
fplot(@(x) sin(x),'-.*c')
hold off

xt = @(t) cos(3*t);
yt = @(t) sin(2*t);
fplot(xt,yt)

What if you do not want to see the figures?


How can you save them to a file?
fig_x=figure;
creating a figure handle
set(fig_x,visible,off);
copy and paste line 75
adjust figure handle for this line
% pause

be sure to comment out the pauses

saveas(fig_x,[outpath,xy_scatter.tif]);
copy and paste line 77
adjust figure handle and name of file

Using zoom on Matlab plots


Click on zoom at top of figure

Select area you want enlarged


Save as

Supporting Commands
Several functions let you control the plot appearance
axis(): determines the axis scaling (see help for options)
hold on/off: controls whether or not the plot is erased before another
plot is drawn (toggles if no argument given)
>> x=0:0.1:2*pi;
>> plot(x,sin(x))
>> axis
ans =
0
7
-1
>> axis([0 7 -.5 .5])

>> x=0:0.1:2*pi;
>> plot(x,sin(x))
>> hold on

>> plot(x,cos(x))
1

0.5

0.5

-0.5

-0.5

-1

Using Lines or Markers or Both


Plots must follow the following logic:
Lines: whenever plotting analytical functions like sin(x) where you can
compute y for any value of x
Markers: whenever plotting discrete experimental data or whenever the data
are known only discretely
Both: connecting markers with straight lines is appropriate when you want to
show a sequence
>>
>>
>>
>>
>>

>> plot(x,cos(x),'r:')
>> hold on
>> plot(x,sin(x),'b--')
1

>>
>>
>>
>>
>>

x=0:0.02:1;
y=x.^1.5;
yr=randn(size(x));
yy=y+0.1.*yr;
plot(x,yy,'rx')

x=0:.02:1;
y=x.^1.5;
yr=randn(size(x));
yy=y+0.1.*yr;
plot(x,yy,'ro',x,yy)

1.2

1.2

1
1

0.5

0.8
0.8

0.6
0.6

0.4
0.4

0.2

0.2

-0.5

0
-0.2

-1

-0.2
0

0.2

0.4

0.6

0.8

0.2

0.4

0.6

0.8

Using Both Markers & Lines


Use lines to show analytical fit through discrete data
>> x=0:.02:1;
>> y=x.^1.5;
>> yr=randn(size(x));
>> yy=y+0.1.*yr;
>> plot(x,yy,'x')
>> p=polyfit(x,yy,1)
p =
1.0159
-0.0927
>> hold on
>> plot(x,polyval(p,x),'r')

>>
>>
>>
>>
>>
>>

1.2

15

10

0.8

x=0:0.2:2.*pi;
y=sin(x);
yr=randn(size(x));
plot(x,10.*y+yr,'ro')
hold on
plot(x,10.*y)

0.6

0
0.4

-5

0.2

-10

0
-0.2

0.2

0.4

0.6

0.8

-15

Plotting Multiple Curves


Problem: How can you compare several curves?
Lets start with the following:
>> X
>> Y1
>> Y2
>> Y3
>> Y4

=
=
=
=
=

0.0:pi/100:2*pi;
cos(X);
3*cos(X);
cos(2*X);
sin(X);

We could plot these using:

>>
>>
>>
>>
>>

plot(X,Y1)
hold on
plot(X,Y2)
plot(X,Y3)
plot(X,Y4)

-1

-2

-3

Plotting Multiple Curves (contd)


Or we could do:
>> plot(X,Y1,X,Y2,X,Y3,X,Y4)

Or we could do this:
>> Z = [Y1;Y2;Y3;Y4];
>> plot(X,Z)

-1

-2

-3

What if we did this?


3

>> plot(X, Z, 'o')


2

Do a help plot for more markers.

How could we see the data points more


distinctly?

-1

-2

-3

Using 2 Y-axis Scales


Sometimes it is useful to plot two curves with widely
different y-axis scales
>>
>>
>>
>>

>>
>>
>>
>>

x=0:0.1:3.*pi;
y1=sin(x+0.5);
y2=90.*sin(x-0.5);
plot(x,y1,x,y2)

100

50

0.5

-50

-0.5

-100

-1

10

x=0:0.1:3.*pi;
y1=sin(x+0.5);
y2=90.*sin(x-0.5);
plotyy(x,y1,x,y2)
100

50

-50

-100
10

Multiple Y-Axes

Multiple X and Y-Axes


Can go more low level than plotyy
Create plots with multiple x and y axes
Use line function to create individual lineseries objects
line will also create the figure object for you if you havent created one
yourself

Nice example in MATLAB help


Search Using Multiple X- and Y-Axes

Basic Plot Commands


axis - freezes current axis scaling
axis([xmin, xmax, ymin, ymax]) sets axis limit values (note
use of [ ] )
axis off turns off display of axes (plot unchanged)
axis on turns on display of axes
grid on/off turns on/off display of a grid
text(x,y,string) - places horizontal text starting at (x,y)
gtext(string) places horizontal text starting wherever user clicks
with mouse
line(x,y) adds line specified by x & y vectors

Example of Log Plots


Using a log scale can reveal large dynamic ranges
>>
>>
>>
>>
>>
>>

x=linspace(.1,10,1000);
Describes the behavior of
damp=0.05;
vibrating systems
y=1./sqrt((1-x.^2).^2 + (2.*damp.*x).^2);
plot(x,y)
1
y

1/ 2
semilogx(x,y)
(1 x 2 )2 (2 x )2
loglog(x,y)

10

10

10

10

-1

10

0
10 -1
10

-2

10

10
1

-1

10 10

10

10

Subplot Command
There are times when it is better to create several smaller plots arranged
in some kind of grid; subplot(m,n,k) does this
m=rows, n=columns in the grid
k=current focus (numbered row-wise)

Lets define a 2x3 subplot grid for: subplot(2,3,1) with the focus
on the first plot.
3
1

Subplots
SUBPLOT- display multiple axes in the same figure window
subplot(#rows, #cols, index)
subplot(2,2,1);
plot(1:10)
subplot(2,2,2)

x = 0:.1:2*pi;
plot(x,sin(x))
subplot(2,2,3)
x = 0:.1:2*pi;
plot(x,exp(-x),r)
subplot(2,2,4)
plot(peaks)
subplotex

Alternative Scales for Axes

LOGLOG
Both axes
logarithmic

SEMILOGY
log Y
linear X

SEMILOGX
log X
linear Y

PLOTYY
2 sets of
linear axes

other_axes

On Your Own:
Putting it all together
X=0:0.5:50;
Y=5*x.^2;
subplot(2,2,1), plot(X,Y), title(Polynomial Linear/Linear), ...
ylabel(y), grid
subplot(2,2,2), semilogx(X,Y), title(Polynomial Log/Linear), ...
ylabel(y), grid

subplot(2,2,3), semilogy(X,Y), title(Polynomial Linear/Log), ...


ylabel(y), grid
subplot(2,2,4), loglog(X,Y), title(Polynomial Log/Log), ...
ylabel(y), grid

What does grid do?


Whats the quickest way to execute this code?

Specialized 2D Plots
There are a number of other specialized 2D plots

area(x,y): builds a stacked area plot


pie(): creates a pie chart (with options)
bar(x,y): creates a vertical bar chart (with many options)
stairs(x,y): similar to bar() but shows only outline
errorbar(x,y,e): plots x vs y with error bars defined by e
scatter(x,y): creates a scatter plot with options for markers
semilogx(x,y): plots x vs y with x using a log scaling
semilogy(x,y): plots x vs y with y using a log scaling
loglog(x,y): plots x vs y using log scale for both axes

And many others (explore these yourself)

Bar Graphs and Pie Charts


MATLAB includes a whole family of bar graphs and pie charts

bar(x) vertical bar graph


barh(x) horizontal bar graph
bar3(x) 3-D vertical bar graph
bar3h(x) 3-D horizontal bar graph
pie(x) pie chart
pie3(x) 3-D pie chart

41

Bar Graphs
MATLAB will plot horizontal and vertical bar graphs

Pie Charts
MATLAB can also make pie charts

Stem Plots
And stem plots for discrete data

45

46

Histograms
A histogram is a plot showing the distribution of a set
of values

47

Stem()
stem()is to plot discrete sequence data
The usage of stem() is very similar to plot()
cos(n/4)
1

>>
>>
>>
>>

n=-10:10;
f=stem(n,cos(n*pi/4))
title('cos(n\pi/4)')
xlabel('n')

0.5

-0.5

-1
-10

-5

0
n

10

Kids actually believe that they can distinguish between 21


different versions of pure sugar Jerry Seinfeld

Bar

C_suger = [1 2 3];
kid1_score = [7;8;9];
kid2_score = [6;6;10];
kid3_score = [5;5;10];
kids_scores =[kid1_score,kid2_score,
kid3_score];
figure;
subplot(3,1,1)

bar(C_suger,kids_scores);
title('bar ''group''');
legend('Kid1','Kid2','Kid3');

subplot(3,1,2)

bar(C_suger,kids_scores, 'stacked');
title('bar ''stacked''');
legend('Kid1','Kid2','Kid3');

subplot(3,1,3)

barh(C_suger,kids_scores);
title('group barh');
legend('Kid1','Kid2','Kid3');

Hist /Histc
x=-3:0.1:3;
y = randn(1,1000);
figure;
subplot(3,1,1);

# bins

hist(y,50);
title('hist - k bins');

subplot(3,1,2);

Centers of bins

hist(y,x);
title('hist - bin centers given by x');
subplot(3,1,3);

edges of bins

[n,bin] = histc(y,x);
n=n/sum(n);
Converting to percent
bar(x,n);
title('histc & bar');

of values

Bin index for each element


50

Fill Filling a Polygon


What does this code draws?
figure;

Fills a polygon
(connecting start to end)

t =(1:2:15)'*pi/8;
x = sin(t);

y = cos(t);
fill(x,y,'r');
axis square off;
text(0,0,'STOP','Color', [1 1 1], ...

'FontSize', 80, ...


'FontWeight','bold', ...
'HorizontalAlignment', 'center');

Errorbar & pie


figure; Like plot but with error bars
errorbar(x,y,e);
title('errorbar');
a = [ 10 , 5 , 20, 30]
figure;
subplot(2,1,1); Explode logical array
pie(a, [0,0,0,1]);
legend('A','B','C','D')
subplot(2,1,2);
pie3(a, [0,0,0,1]);
legend('A','B','C','D');

52

Polar Plots
Some functions are easier to specify using polar coordinates than by
using rectangular coordinates
For example the equation of a circle is
y=sin(x)
in polar coordinates

53

54

Example:

t=[0:0.1:10];
polar(t,t);

90
120
150

10
8
6
4
2

60
30

180

(x,y)=(tcost, tsint)
0

210

330
240

300
270

Logarithmic Plots
A logarithmic scale (base 10) is convenient when
a variable ranges over many orders of magnitude, because the wide range of
values can be graphed, without compressing the smaller values.
data varies exponentially.
Aplot uses a linear scale on both axes
semilogy uses a log10 scale on the y axis
semilogx uses a log10 scale on the x axis
loglog use a log10 scale on both axes

56

57

58

Use of feval in an M-function


Let's create an M-function to evaluate an arbitrary function that we
will define with another M-function
call it "evaluate"
see listing below (or help) for calling syntax

To use this, we will need to write another M-file to define our own
special function.
myfun will contain the function name as a string (or explicit call)
we must specify the start, stop values and number of points

Using Your New Function: evaluate()


Here is a particular user-defined function to
evaluate over the specified range of x values

Executing:

>> [x,y]=evaluate('trig',0,5.*pi,100);
>> plot(x,y), xlabel('x'), ylabel('y')
>>

And here is the graphical result

-5

10

12

14

16

A More Complicated Example


Suppose we want to find the minimum of a function
Let's use the "humps" function in Matlab (rather than writing one)
Let's use Matlab's powerful fminbnd function
100

>> x=-0.5:0.05:2;
80

>> y=humps(x);

60

>> plot(x,y), xlabel('x'), ylabel('y')

40
20
0
-20
-0.5

0.5

1
x

Minimum

1.5

Using fminbnd()
See help fminbnd and the textbook for many more details about this
function
On your own: figure out how to find zeros (roots)
>> x=-0.5:0.05:2;
>> y=humps(x);

NOTE: maxima of f(x) are


minima of -f(x)

>> plot(x,y), xlabel('x'), ylabel('y')


>>
>> [x,y]=fminbnd('humps', 0.4, 1.0)
x =

100

0.6370
y =

80

11.2528
60

>> plot(x,y,'ro')

>> hold on

40

>>
20
0
-20
-0.5

0.5

1
x

1.5

Lorenz attractor
The Lorenz attractor defines a 3-dimensional
trajectory by the differential equations:

, r, b are parameters.

dx
( x y)
dt
dy
rx y xz
dt
dz
xy bz
dt

63

Lorenz attractor: MATLAB code

64

Application: Solving ODEs


Matlab includes a number of functions to solve Ordinary
Differential Equations (ODEs), including Initial Value
Problems (IVPs), Boundary Value Problems (BVPs) and
Partial Differential Equations (PDE)
Lets consider a simple IVP in the form of a familiar ODE
(an sdof vibration problem):
d2y
dy
dy

g
(
t
)
where
y
(0)

y
and
y1
0
2
dt
dt
dt t 0

Matlabs ode23() and ode(45) functions use the


Runge-Kutta-Fehlberg method to solve ODEs expressed
as:
dyk
f k (t , y1 , y2 ,
dt

yN ) for k 1

This is advanced
material you will see this
during numerical
methods course

Solving an ODE:
setup
th

We can convert an N order ODE into N first order ODEs using a


simple algorithm:
y1 y
dy1
dt
dy
y3 2
dt
etc

y2

dy1
y2
dt
dy2 d 2 y1 d 2 y
dy
2 2 g (t ) 2
y g (t ) 2 y2 y1
dt
dt
dt
dt

In more compact forms:


y1 y2

y2 g (t ) 2 y2 y1

or

y 0
1 y1 0
1

g
(
t
)

y2

Matlab ode45( ) Syntax


>> help ode45
ODE45 Solve non-stiff differential equations, medium order method.
[T,Y] = ODE45(ODEFUN,TSPAN,Y0) with TSPAN = [T0 TFINAL] integrates the
system of differential equations y' = f(t,y) from time T0 to TFINAL with
initial conditions Y0. Function ODEFUN(T,Y) must return a column vector
corresponding to f(t,y). Each row in the solution array Y corresponds to
a time returned in the column vector T. To obtain solutions at specific
times T0,T1,...,TFINAL (all increasing or all decreasing), use
TSPAN = [T0 T1 ... TFINAL].
(truncated)

[T,Y] are the returned values and each row defines a value of t
where the solution is computed along with the corresponding
solutions, yi , in successive columns.
But we need to provide a function to compute f(t,y) whenever
ode45( ) needs it
We also need to specify the start and end times and initial
conditions in the arguments to ode45( )

rhs( ) function for ode45( )


m-function will compute f(t,y) for ode45( )
returns the RHS column vector y
y

g
(
t
)

2
1
y2
1

NOTE:
If you need to pass parameter values to compute
the RHS (e.g, zeta or g(t)), these can be added to
the ode45( ) function call (see help ode45)

Solving the Problem


>> [tt,yy]=ode45('rhs', [0 35],[1 0]');
>> whos
Name
Size
Bytes Class
tt
yy

205x1
205x2

1640
3280

double array
double array

Grand total is 615 elements using 4920 bytes


>> plot(tt,yy(:,1))

You supply this


m-function

Note the sizes of the


returned variables

You can plot either


column of yy as needed
How would you construct
a phase plane plot (e.g., y
versus y)?

See help ode45


for more options

A More Interesting RHS


Note how g(t) is
formed here

Result is familiar
square pulse with
ringing oscillations

Fall 2006

AE6382 Design Computing

70

Figure Window
All editing of figure can be done manually in figure window
Can insert title, axis labels, legend, change axis scaling, tick marks and
labels, etc
Essentially anything you can do from function calls you can do by hand in the
figure window
It just takes longer and you have to do it to every figure every time it is created

Figure Window
Four important menus on figure
window
File, edit, insert and tools drop down
menus

Figure Window
File menu

Save, open, close, print figure


Can save as many different image
formats: png, jpg, eps, tif, etc.

Edit menu
Edit axis properties, figure properties

Insert menu
Insert title, legend, axis labels

Tools menu
Change view of plot, add basic
regression lines

Figure Window
Top toolbar
From left to right:
New figure, open file, save figure, print figure, edit figure,
zoom in , zoom out, pan, rotate 3D, data cursor,
brush/select data, link plot, insert colorbar, insert legend,
hide plot tools, show plot tools and dock figure

Figure Window
Edit plot icon
Probably most important
When selected it allows you to move placement of title, axis labels, legend,
colorbar, any other text or items on plot
Allows you to select objects of the figure to then edit properties of under the
edit menu, edit current object properties option

Figure Window
Plot tools
Clicking on plot tools icon in toolbar opens up plot tools window
Can also be done with plottools from command line or m-file
Easy way to insert text boxes, arrows, other things

Plot Tools Window

Basic Plotting
grid command will turn on x, y-axis grid lines
axis([xmin xmax ymin ymax])

Command to set axis limits


axis square will set the axis limits such that the plot is square
axis equal will set scale factor and tick marks to be equal on each axis
axis auto will return axis scaling to auto, which is default

Basic Plotting
xlabel(text)
ylabel(text)
title(text)
These three commands will set the xlabel, ylabel and title of the plot for you
The grid, axis and labeling commands all need to be performed after the plot
command

Basic Plotting
h = plot(x,y)
h is a vector of handles to lineseries objects
This allows you to use h to edit the appearance of the data being plotted (i.e.
line color, line style, line width)

h = figure(n)
h is a handle to figure n
This allows you to modify properties of the figure object
Useful if you are creating many figures and want to modify them at different points in
the program

Modifying Plots
set(h,'PropertyName',PropertyValue,...)
The set command takes object handle h and sets property values for give
property names for that object handle
If h is an array, the property values will be set for all object handles in h

a = get(h,'PropertyName')
get returns the value of a given property

Modifying Plots
gcf stands for get current figure handle
Will return handle of current figure

gca stands for get current axis handle


Will return handle of current axis

These two commands are very useful when used in


conjunction with the set and get commands
Allows you to edit the properties of the current figure
or axis without having the handle specified in a
variable

Modifying Plots
MATLAB has many properties for various objects
We will only go over some of the basics
MATLAB help is great for discovering the rest

Line color
Specified by either an RGB triplet from 0 to 1, or short or
long name

Modifying Plots
Line width
Specified by an integer, default is 0.5 points
Each point is 1/72 of an inch

Line style

Modifying Plots
Line markers
Can choose to add markers at each data point
Can have only markers, no line

Modifying Plots
Example syntax
Edit line style, line width and line color in plot command (with error)

Edit same things using lineseries handle

Modifying Plots
You can also quickly specify line style, marker type
and color in the plot command

These all set the line color to blue


The first sets the line style to a solid line with x at every
data point
Second sets line style to none with an x at every data point
Third is the same as second, except marker is o instead of x

Modifying Plots
Setting axis tick marks and labels
Use the xtick, ytick, ztick and xticklabel, yticklabel, zticklabel property names
Can specify one or both or none to let MATLAB auto select tick interval and
labels
Puts tick marks at x = 1,3,5
set(gca, 'xtick', []);
Will remove all tick marks

Modifying Plots
Four different ways to set the tick labels
set(gca,'XTickLabel',{'1';'10';'100'}) set(gca,'XTickLabel','1|10|100')
set(gca,'XTickLabel',[1;10;100]) set(gca,'XTickLabel',['1 ';'10 ';'100'])
MATLAB runs through the label array until it labels all tick locations
If label array is too small MATLAB wraps around and begins again

Multiple Lineseries
The plot command can plot up to n lineseries at one time
You can also specify line style, color and marker symbol for each

In this case h would be an array of length 4


Typical array notation would be used to edit a given lineseries

Contour Plots

Use contour and contourf to make contour and filled


contour plots respectively

Contour Plots
contourf syntax very similar to contour
Can do interactive contour labeling
clabel(C,h,'manual')
Using this function call after a contour call will bring up the figure and let you
manually select where the contours will be labeled

Contour group properties can also be modified to set various


properties of contour lines

Contour Plots

To change the properties of the contour labels you


need to create a text object and use that object
handle

Contour Plots
Contour labeling done using clabel function as weve
seen

Colormaps
Colormaps can be specified for contour plots
MATLAB has many built in colormaps
colormap(map)
This sets the colormap to the one specified

colormap(map(n))
This will set the colormap and use n colors evenly spaced from the given colormap

Colormaps
Can create your own colormaps
Need to be an array of RGB triplets (3 column array) in the range of 01
Then pass array name to colormap function

Images

Reduced Memory Requirements:


Images represented as UINT8 - 1 byte

a = magic(4)
a =

Use Row 2
of colormap
13 for pixel (1,2)

16

11

10

12

14

15

image(a);
map = hsv(16)
map =

1.0000

1.0000

0.3750

1.0000

0.7500

colormap(map)
imagex

0
0 Row 2
0 .....

Example: Images
load cape
image(X)
colormap(map)

Deleting Objects - DELETE


delete(h_object)

addgraph
h = findobj('Color', [0 0 1])
delete(h)

Practice Problems

Plot the following signals in linear scale

x(t ) sin(3t )
y (t ) e 2t 3

5 t 5
0t 5

Plot the following signals, use log scale for y-axis

x(t ) et 2 (2t 1) 0 t 10

Plot the real part and imaginary part of the following signal

x(t ) e0.5t j (t / 3)

0 t 10

For the signal in previous question, plot its phase and magnitude

Try

Represent the functions:


y1= sin(3 x)/ex
y2=cos(3 x)/ex
with x between 0 and 3 ,obtaining only one figure like:

Practice Exercise 5.3


Try these exercises to create some
interesting shapes
90

90

120

60

10

120

60

3
150

150

30

30

150

30

1
180

210

180

210

330

240

90

120

60
4

180

330

240

300

210

330

300

240

270

270

90

90

120

60
0.8
0.6

3
150

30

30
0.4

0.2

1
180

210

330

240

300
270

120

60
4

150

300
270

180

210

330

240

300
270

maxIterations = 500;
gridSize = 1000;
xlim = [-0.748766713922161, -0.748766707771757];
ylim = [ 0.123640844894862,

0.123640851045266];

t = tic();
x = linspace( xlim(1), xlim(2), gridSize );
y = linspace( ylim(1), ylim(2), gridSize );

[xGrid,yGrid] = meshgrid( x, y );
z0 = xGrid + 1i*yGrid;
count = zeros( size(z0) );
z = z0;
for n = 0:maxIterations
z = z.*z + z0;
inside = abs( z )<=2;
count = count + inside;
end
count = log( count+1 );
cpuTime = toc( t );

set( gcf, 'Position', [200 200 600 600] );


imagesc( x, y, count );
axis image
colormap( [jet();flipud( jet() );0 0 0] );
title( sprintf( '%1.2fsecs', cpuTime ) );

x=-50:0.5:.50;
y=x;
[X,Y]=meshgrid(x,y);
Z=(cos(X))^2+(cos(Y))^2;
pcolor(X,Y,Z);
shading interp
axis('equal','square','off')

You might also like