Docsity

2D Plotting in Matlab: Understanding Anatomy and Choosing Plot Types, Study notes of Computer Science

Partial preview of the text

Download 2D Plotting in Matlab: Understanding Anatomy and Choosing Plot Types and more Study notes Computer Science in PDF only on Docsity!

CS

Introduction to Computing

for Engineers

2-D Plotting

Two Dimensional Plotting

Learning Objectives

– Understand the

anatomy of a 2D plot

– How to choose

different plot types for

best effects

Topics

– Construction of 2D

plots using plot()

– Modification and

enhancements to the

plot

– Different types of 2D

plots you can create

Background

• While numerical methods are the heart (and origin) of

Matlab, graphics has become the major component since

the release of Version 4.

• Version 6 adds to this legacy with refinements and new

functions.

• Professional Matlab comes with two thick manuals: (a)

basic commands & programming and (b) graphics

• The graphics capabilities are so broadly defined that we

will be able to cover only a small part

– we'll focus on graphics you will find immediately

useful

– we will point to some of the areas where you will find

powerful new capabilities when you need them later

• Like all of us, you will find yourselves frequently looking

up "help" or checking the manuals for graphics!

0 5 10 15 20 25 30 35

-0.

0

1

X axis description

Y axis description

Title for plot goes here

Legend for graph

Manually inserted text...

x=0:0.05:10pi; y=exp( -.1.x).*sin(x); plot(x,y) xlabel('X axis description') ylabel('Y axis description') title('Title for plot goes here') legend('Legend for graph') grid on

Basic 2D Plotting

• The simplest kind of plot is a cartesian plot of (x,y) pairs

defined by symbols or connected with lines

NOTE #1:

Reversing the x,y order

(y,x) simply rotates the

plot 90 degrees!

NOTE #2:

line(x,y) is similar to plot(x,y)

but does not have additional options

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. hold on plot(x,polyval(p,x),'r')

0 0.2 0.4 0.6 0.8 1 -0.

0

1

0 2 4 6 8

0

5

10

15

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)

Plotting Multiple Curves

• Problem: How can you compare several curves?

• Let’s start with the following:

• We could plot these using:

X = 0.0:pi/100:2pi; Y1 = cos (X); Y2 = 3cos (X); Y3 = cos(2*X); Y4 = sin(X);

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

-3 0 1 2 3 4 5 6 7

0

1

2

3

Plotting Multiple Curves (cont’d)

• Or we could do:

• Or we could do this:

• What if we did this?

• Do a “ help plot ” for more

markers.

• How could we see the data

points more distinctly?

-3 0 1 2 3 4 5 6 7

0

1

2

3

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

>> Z = [Y1;Y2;Y3;Y4];

plot(X,Z)

-3 0 1 2 3 4 5 6 7

0

1

2

3

plot(X, Z, 'o')

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); plotyy(x,y1,x,y2)

0 2 4 6 8 10

-0.

0

1

0 2 4 6 8 10

0

50

100

0 2 4 6 8 10

0

50

100

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

NOTE : it is complicated to label the 2nd axis…

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)

• Let’s define a 2x3 subplot grid for: subplot(2,3,1) with the focus

on the first plot.

On Your Own:

• Putting it all together…

• What does grid do?

• What’s the quickest way to execute this code?

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

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; you may find a

good use in a later course)

A Special M-function: feval

• Sometimes you may want to pass along the NAME of a

function that you want another function to use…

– Suppose you have an M-function called, fmax, and it

finds the maximum of a given function, like the one

shown below.

– Suppose you invoke fmax as: [f, x]=fmax(x0, x1)

where f is the max value which occurs at x in the

range x0→x

– How do you tell fmax to use myfunc(x) which defines

f(x)?

f(x)

x

f(x)=myfunc(x)

Using Your New Function: evaluate()

• Here is a particular user-

defined function to

evaluate over the

specified range of x

values

• Executing:

• And here is the graphical

result…

0 2 4 6 8 10 12 14 16

  • 5

0

5

x

y

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

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

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

-0.5 0 0.5 1 1.5 2

0

20

40

60

80

100

x

y

x=-0.5:0.05:2;

y=humps(x); plot(x,y), xlabel('x'), ylabel ('y')

Minimum

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)

-0.5 0 0.5 1 1.5 2

0

20

40

60

80

100

x

y

x=-0.5:0.05:2; y=humps(x); plot(x,y), xlabel('x'), ylabel('y')

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

y =

hold on plot(x,y,'ro')

NOTE: maxima of f(x) are

minima of -f(x)

NOTE: maxima of f(x) are

minima of -f(x)

A Note on How Arguments are Passed

  • When arguments are passed into a function:
    • only the reference to the argument variable is provided the function
    • the values themselves remain in their home workspace
    • this avoids moving large amounts of data (Slow!)
  • If your function modifies an argument…
    • Matlab will immediately copy the argument variable into the function workspace (the whole array)
    • HOWEVER: any changes you make will NEVER be seen in the calling workspace because it is never copied back there!
  • SOLUTION: if you need to make a change in an argument variable, you MUST include it in the list of returned variables to make it available to the calling workspace!

input

copy into function workspace and modify

return

Matlab ode45( ) Syntax

• [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( )

help ode

ODE45 Solve non-stiff differential equations, medium order method. [T,Y] = ODE45(ODEFUN,TSPAN,Y0) with TSPAN = [T0 TFINAL] inte grates 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 co lumn vector corresponding to f(t,y). Each row in the solution array Y co rresponds to a time returned in the column vector T. To obtain solutions at specific times T0,T1,...,TFINAL (all increasing or all decreasing), u se TSPAN = [T0 T1 ... TFINAL].

(truncated)

rhs( ) function for ode45( )

• m-function will compute f(t,y) for ode45( )

• returns the RHS column vector 1 2

2 ( )^22

y y

y g t^ ζy^ y

 (^) ′        =  ′ (^)  −^ −   

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 )

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…

• 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’)?

• 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’)?

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

tt 205x1 1640 double array yy 205x2 3280 double array

Grand total is 615 elements using 4920 bytes

plot(tt,yy(:,1))

See help ode

for more options

See help ode

for more options

You supply this

m-function…

You supply this

m-function…

A More Interesting RHS…

• Note how g(t) is

formed here

• Note how g(t) is

formed here

Result is familiar

square pulse with

ringing oscillations

Result is familiar

square pulse with

ringing oscillations

Optional: Problem Solving

• Compare the behavior of finely stored data with coarse

granularity and interpolation.

– investigate the use of the interpolation functions in

Matlab (MM Chapter 18)

– consider both 1D and 2D applications

• Calculate the mean error across a table lookup.

– assume a high resolution table with 100 entries for

airfoil lift versus air speed

– now assume a low resolution table with only 10

entries (keep every 10th^ from high res table)

• calc lift for all 100 velocities using linear interpolation

over the 10 entries in the low res table

• compute the average error

• compute the mean square error (square root of avg of

differences between the squares of values)

1 2

L = 2 ρv C SL