1 of 107

Script files, Functions, plotting

Chapter 2

2 of 107

3-2

Getting Help for Functions

You can use the lookfor command to find functions that are relevant to your application.

For example, type lookfor imaginary to get a list of the functions that deal with imaginary numbers. You will see listed:

imag Complex imaginary part

i Imaginary unit

j Imaginary unit

More? See pages 113-114.

3 of 107

3-3

Exponential

exp(x)

sqrt(x)

Logarithmic

log(x)

log10(x)

Exponential; e x

Square root; √x

Natural logarithm; ln x

Common (base 10) logarithm; log x = log10 x

(continued…)

Common mathematical functions: Table 3.1–1, page 114

4 of 107

Some common mathematical functions (continued)

Complex

abs(x)

angle(x)

conj(x)

imag(x)

real(x)

Absolute value.

Angle of a complex number.

Complex conjugate.

Imaginary part of a complex number.

Real part of a complex number.

(continued…)

3-4

5 of 107

Some common mathematical functions (continued)

Numeric

ceil(x)

fix(x)

floor(x)

round(x)

sign(x)

Round to nearest integer toward ∞.

Round to nearest integer toward zero.

Round to nearest integer toward -∞.

Round toward nearest integer.

Signum function:

+1 if x > 0; 0 if x = 0; -1 if x < 0.

3-5

6 of 107

3-6

The rectangular and polar representations of the complex number a + ib.

7 of 107

3-7

Operations with Complex Numbers

>>x = -3 + 4i;

>>y = 6 - 8i;

>>mag_x = abs(x)

mag_x =

5.0000

>>mag_y = abs(y)

mag_y =

10.0000

>>mag_product = abs(x*y)

50.0000

(continued …)

8 of 107

3-8

Operations with Complex Numbers (continued)

>>angle_x = angle(x)

angle_x =

2.2143

>>angle_y = angle(y)

angle_y =

-0.9273

>>sum_angles = angle_x + angle_y

sum_angles =

1.2870

>>angle_product = angle(x*y)

angle_product =

1.2870

9 of 107

3-9

Operations on Arrays

MATLAB will treat a variable as an array automatically. For example, to compute the square roots of 5, 7, and 15, type

>>x = [5,7,15];

>>y = sqrt(x)

y =

2.2361 2.6358 3.8730

10 of 107

3-10

Expressing Function Arguments

We can write sin 2 in text, but MATLAB requires parentheses surrounding the 2 (which is called the function argument or parameter).

Thus to evaluate sin 2 in MATLAB, we type sin(2). The MATLAB function name must be followed by a pair of parentheses that surround the argument.

To express in text the sine of the second element of the array x, we would type sin[x(2)]. However, in MATLAB you cannot use square brackets or braces in this way, and you must type sin(x(2)).

(continued …)

11 of 107

3-11

Expressing Function Arguments (continued)

To evaluate sin(x 2 + 5), you type sin(x.^2 + 5).

To evaluate sin(√x+1), you type sin(sqrt(x)+1).

Using a function as an argument of another function is called function composition. Be sure to check the order of precedence and the number and placement of parentheses when typing such expressions.

Every left-facing parenthesis requires a right-facing mate. However, this condition does not guarantee that the expression is correct!

12 of 107

3-12

Expressing Function Arguments (continued)

Another common mistake involves expressions like sin2 x, which means (sin x)2.

In MATLAB we write this expression as (sin(x))^2, not as sin^2(x), sin^2x, sin(x^2), or sin(x)^2!

13 of 107

3-13

Expressing Function Arguments (continued)

The MATLAB trigonometric functions operate in radian mode. Thus sin(5) computes the sine of 5 rad, not the sine of 5°.

To convert between degrees and radians, use the relation qradians = (p /180)qdegrees.

14 of 107

3-14

cos(x)

cot(x)

csc(x)

sec(x)

sin(x)

tan(x)

Cosine; cos x.

Cotangent; cot x.

Cosecant; csc x.

Secant; sec x.

Sine; sin x.

Tangent; tan x.

Trigonometric functions: Table 3.1–2, page 116

15 of 107

Inverse Trigonometric functions: Table 3.1–2�

acos(x)

acot(x)

acsc(x)

asec(x)

asin(x)

atan(x)

atan2(y,x)

Inverse cosine; arccos x.

Inverse cotangent; arccot x.

Inverse cosecant; arccsc x.

Inverse secant; arcsec x.

Inverse sine; arcsin x .

Inverse tangent; arctan x .

Four-quadrant inverse tangent.

3-15

16 of 107

3-16

Hyperbolic cosine

Hyperbolic cotangent.

Hyperbolic cosecant

Hyperbolic secant

Hyperbolic sine

Hyperbolic tangent

cosh(x)

coth(x)

csch(x)

sech(x)

sinh(x)

tanh(x)

Hyperbolic functions: Table 3.1–3, page 119

17 of 107

Inverse Hyperbolic functions: Table 3.1–3

acosh(x)

acoth(x)

acsch(x)

asech(x)

asinh(x)

atanh(x)

Inverse hyperbolic cosine

Inverse hyperbolic cotangent

Inverse hyperbolic cosecant

Inverse hyperbolic secant

Inverse hyperbolic sine

Inverse hyperbolic tangent;

3-17

18 of 107

3-18

User-Defined Functions

The first line in a function file must begin with a function definition line that has a list of inputs and outputs. This line distinguishes a function M-file from a script M-file. Its syntax is as follows:

function [output variables] = name(input variables)

Note that the output variables are enclosed in square brackets, while the input variables must be enclosed with parentheses. The function name (here, name) should be the same as the file name in which it is saved (with the .m extension).

More? See pages 119-123.

19 of 107

3-19

User-Defined Functions: Example

function z = fun(x,y)

u = 3*x;

z = u + 6*y.^2;

Note the use of a semicolon at the end of the lines. This prevents the values of u and z from being displayed.

Note also the use of the array exponentiation operator (.^). This enables the function to accept y as an array.

(continued …)

20 of 107

3-20

User-Defined Functions: Example (continued)

Call this function with its output argument:

>>z = fun(3,7)

z =

303

The function uses x = 3 and y = 7 to compute z.

(continued …)

21 of 107

3-21

User-Defined Functions: Example (continued)

Call this function without its output argument and try to access its value. You will see an error message.

>>fun(3,7)

ans =

303

>>z

??? Undefined function or variable ’z’.

(continued …)

22 of 107

3-22

User-Defined Functions: Example (continued)

Assign the output argument to another variable:

>>q = fun(3,7)

q =

303

You can suppress the output by putting a semicolon after the function call.

For example, if you type q = fun(3,7); the value of q will be computed but not displayed (because of the semicolon).

23 of 107

3-23

Local Variables: The variables x and y are local to the function fun, so unless you pass their values by naming them x and y, their values will not be available in the workspace outside the function. The variable u is also local to the function. For example,

>>x = 3;y = 7;

>>q = fun(x,y);

>>x

x =

3

>>y

y =

7

>>u

??? Undefined function or variable ’u’.

24 of 107

3-24

Only the order of the arguments is important, not the names of the arguments:

>>x = 7;y = 3;

>>z = fun(y,x)

z =

303

The second line is equivalent to z = fun(3,7).

25 of 107

3-25

You can use arrays as input arguments:

>>r = fun(2:4,7:9)

r =

300 393 498

26 of 107

3-26

A function may have more than one output. These are enclosed in square brackets.

For example, the function circle computes the area A and circumference C of a circle, given its radius as an input argument.

function [A, C] = circle(r)

A = pi*r.^2;

C = 2*pi*r;

27 of 107

The function is called as follows, if the radius is 4.

>>[A, C] = circle(4)

A =

50.2655

C =

25.1327

3-27

28 of 107

A function may have no input arguments and no output list.

For example, the function show_date clears all variables, clears the screen, computes and stores the date in the variable today, and then displays the value of today.

function show_date

clear

clc

today = date

3-28

29 of 107

3-29

  1. One input, one output:

function [area_square] = square(side)

2. Brackets are optional for one input, one output:

function area_square = square(side)

3. Two inputs, one output:

function [volume_box] = box(height,width,length)

4. One input, two outputs:

function [area_circle,circumf] = circle(radius)

5. No named output: function sqplot(side)

Examples of Function Definition Lines

30 of 107

Function Example

function [dist,vel] = drop(g,vO,t);

% Computes the distance travelled and the

% velocity of a dropped object,

% as functions of g,

% the initial velocity vO, and

% the time t.

vel = g*t + vO;

dist = 0.5*g*t.^2 + vO*t;

3-30

(continued …)

31 of 107

Function Example (continued)

1. The variable names used in the function definition may, but need not, be used when the function is called:

>>a = 32.2;

>>initial_speed = 10;

>>time = 5;

>>[feet_dropped,speed] = . . . drop(a,initial_speed,time)

3-31

(continued …)

32 of 107

Function Example (continued)

2. The input variables need not be assigned values outside the function prior to the function call:

[feet_dropped,speed] = drop(32.2,10,5)

3. The inputs and outputs may be arrays:

[feet_dropped,speed]=drop(32.2,10,0:1:5)

This function call produces the arrays feet_dropped and speed, each with six values corresponding to the six values of time in the array time.

3-32

33 of 107

Local Variables

The names of the input variables given in the function definition line are local to that function.

This means that other variable names can be used when you call the function.

All variables inside a function are erased after the function finishes executing, except when the same variable names appear in the output variable list used in the function call.

3-33

34 of 107

Global Variables

The global command declares certain variables global, and therefore their values are available to the basic workspace and to other functions that declare these variables global.

The syntax to declare the variables a, x, and q is

global a x q

Any assignment to those variables, in any function or in the base workspace, is available to all the other functions declaring them global.

3-34

More? See pages 124.

35 of 107

3-35

Function Handles

You can create a function handle to any function by using the at sign, @, before the function name. You can then use the handle to reference the function. To create a handle to the function y = x + 2ex 3, define the following function file:

function y = f1(x)

y = x + 2*exp(-x) - 3;

You can pass the function as an argument to another function. For example, we can plot the function over 0 x 6 as follows:

>>plot(0:0.01:6,@f1)

36 of 107

Finding Zeros of a Function

You can use the fzero function to find the zero of a function of a single variable, which is denoted by x. One form of its syntax is

fzero(@function, x0)

where @function is the function handle for the function function, and x0 is a user-supplied guess for the zero.

The fzero function returns a value of x that is near x0.

It identifies only points where the function crosses the x-axis, not points where the function just touches the axis.

For example, fzero(@cos,2) returns the value 1.5708.

3-36

37 of 107

Using fzero with User-Defined Functions

To use the fzero function to find the zeros of more complicated functions, it is more convenient to define the function in a function file.

For example, if y = x + 2ex 3, define the following function file:

function y = f1(x)

y = x + 2*exp(-x) - 3;

3-37

(continued …)

38 of 107

Example (continued)

To find a more precise value of the zero near x = -0.5, type

>>x = fzero(@f1,-0.5)

The answer is x = -0.5881.

3-39

More? See pages 125-126.

39 of 107

Finding the Minimum of a Function

The fminbnd function finds the minimum of a function of a single variable, which is denoted by x. One form of its syntax is

fminbnd(@function, x1, x2)

where @function is the function handle for the function. The fminbnd function returns a value of x that minimizes the function in the interval x1 ≤ x ≤ x2.

For example, fminbnd(@cos,0,4) returns the value 3.1416.

3-40

40 of 107

When using fminbnd it is more convenient to define the function in a function file. For example, if y = 1 xe x , define the following function file:

function y = f2(x)

y = 1-x.*exp(-x);

To find the value of x that gives a minimum of y for 0 x 5, type

>>x = fminbnd(@f2,0,5)

The answer is x = 1. To find the minimum value of y, type y = f2(x). The result is y = 0.6321.

3-41

41 of 107

A function can have one or more local minima and a global minimum.

If the specified range of the independent variable does not enclose the global minimum, fminbnd will not find the global minimum.

fminbnd will find a minimum that occurs on a boundary.

3-42

42 of 107

To find the minimum of a function of more than one variable, use the fminsearch function. One form of its syntax is

fminsearch(@function, x0)

where @function is the function handle of the function in question. The vector x0 is a guess that must be supplied by the user.

3-44

43 of 107

To minimize the function f = xex2 y2 , we first define it in an M-file, using the vector x whose elements are x(1) = x and x(2) = y.

function f = f4(x)

f = x(1).*exp(-x(1).^2-x(2).^2);

Suppose we guess that the minimum is near x = y = 0. The session is

>>fminsearch(@f4,[0,0])

ans =

-0.7071 0.000

Thus the minimum occurs at x = 0.7071, y = 0.

3-45

44 of 107

Methods for Calling Functions

There are four ways to invoke, or “call,” a function into action. These are:

  1. As a character string identifying the appropriate function M-file,

2. As a function handle,

3. As an “inline” function object, or

4. As a string expression.

Examples of these ways follow for the fzero function used with the user-defined function fun1, which computes y = x2 4.

3-46

(continued …)

45 of 107

Methods for Calling Functions (continued)

1. As a character string identifying the appropriate function M-file, which is

function y = fun1(x)

y = x.^24;

The function may be called as follows, to compute the zero over the range 0 x 3:

>>[x, value] = fzero(’fun1’,[0, 3])

3-47

(continued …)

46 of 107

Methods for Calling Functions (continued)

2. As a function handle to an existing function M-file:

>>[x, value] = fzero(@fun1,[0, 3])

3. As an “inline” function object:

>>fun1 = ’x.^24’;

>>fun_inline = inline(fun1);

>>[x, value] = fzero(fun_inline,[0, 3])

3-48

(continued …)

47 of 107

Methods for Calling Functions (continued)

4. As a string expression:

>>fun1 = ’x.^2-4’;

>>[x, value] = fzero(fun1,[0, 3])

or as

>>[x, value] = fzero(’x.^2-4’,[0, 3])

3-49

(continued …)

48 of 107

Methods for Calling Functions (continued)

The function handle method (method 2) is the fastest method, followed by method 1.

In addition to speed improvement, another advantage of using a function handle is that it provides access to subfunctions, which are normally not visible outside of their defining M-file.

3-50

More? See pages 130-131.

49 of 107

Types of User-Defined Functions

The following types of user-defined functions can be created in MATLAB.

• The primary function is the first function in an M-file and typically contains the main program. Following the primary function in the same file can be any number of subfunctions, which can serve as subroutines to the primary function.

3-51

(continued …)

50 of 107

Types of User-Defined Functions (continued)

Usually the primary function is the only function in an M-file that you can call from the MATLAB command line or from another M-file function.

You invoke this function using the name of the M-file in which it is defined.

We normally use the same name for the function and its file, but if the function name differs from the file name, you must use the file name to invoke the function.

(continued …)

3-52

51 of 107

Types of User-Defined Functions (continued)

Anonymous functions enable you to create a simple function without needing to create an M-file for it. You can construct an anonymous function either at the MATLAB command line or from within another function or script. Thus, anonymous functions provide a quick way of making a function from any MATLAB expression without the need to create, name, and save a file.

3-53

(continued …)

52 of 107

Types of User-Defined Functions (continued)

Subfunctions are placed in the primary function and are called by the primary function. You can use multiple functions within a single primary function M-file.

3-54

(continued …)

53 of 107

Types of User-Defined Functions (continued)

Nested functions are functions defined within another function. They can help to improve the readability of your program and also give you more flexible access to variables in the M-file.

The difference between nested functions and subfunctions is that subfunctions normally cannot be accessed outside of their primary function file.

3-55

(continued …)

54 of 107

Types of User-Defined Functions (continued)

Overloaded functions are functions that respond differently to different types of input arguments. They are similar to overloaded functions in any object-oriented language.

For example, an overloaded function can be created to treat integer inputs differently than inputs of class double.

3-56

(continued …)

55 of 107

Types of User-Defined Functions (continued)

Private functions enable you to restrict access to a function. They can be called only from an M-file function in the parent directory.

3-57

More? See pages 131-138.

56 of 107

The term function function is not a separate function type but refers to any function that accepts another function as an input argument, such as the function fzero.

You can pass a function to another function using a function handle.

3-58

57 of 107

Anonymous Functions

Anonymous functions enable you to create a simple function without needing to create an M-file for it. You can construct an anonymous function either at the MATLAB command line or from within another function or script. The syntax for creating an anonymous function from an expression is

fhandle = @(arglist) expr

where arglist is a comma-separated list of input arguments to be passed to the function, and expr is any single, valid MATLAB expression.

3-59

(continued …)

58 of 107

Anonymous Functions (continued)

To create a simple function called sq to calculate the square of a number, type

>>sq = @(x) x.^2;

To improve readability, you may enclose the expression in parentheses, as sq = @(x) (x.^2);. To execute the function, type the name of the function handle, followed by any input arguments enclosed in parentheses. For example,

>>sq([5,7])

ans =

25 49

3-60

(continued …)

59 of 107

Anonymous Functions (continued)

You might think that this particular anonymous function will not save you any work because typing sq([5,7]) requires nine keystrokes, one more than is required to type [5,7].^2.

Here, however, the anonymous function protects you from forgetting to type the period (.) required for array exponentiation.

Anonymous functions are useful, however, for more complicated functions involving numerous keystrokes.

3-61

(continued …)

60 of 107

Anonymous Functions (continued)

You can pass the handle of an anonymous function to other functions. For example, to find the minimum of the polynomial 4x2 50x + 5 over the interval [10, 10], you type

>>poly1 = @(x) 4*x.^2 - 50*x + 5;

>>fminbnd(poly1, -10, 10)

ans =

6.2500

If you are not going to use that polynomial again, you can omit the handle definition line and type instead

>>fminbnd(@(x) 4*x.^2 - 50*x + 5, -10, 10)

3-62

61 of 107

Multiple Input Arguments

You can create anonymous functions having more than one input. For example, to define the function

√(x 2 + y 2), type

>>sqrtsum = @(x,y) sqrt(x.^2 + y.^2);

Then type

>>sqrtsum(3, 4)

ans =

5

3-63

62 of 107

As another example, consider the function defining a plane, z = Ax + By. The scalar variables A and B must be assigned values before you create the function handle. For example,

>>A = 6; B = 4:

>>plane = @(x,y) A*x + B*y;

>>z = plane(2,8)

z =

44

3-64

63 of 107

Calling One Function within Another

One anonymous function can call another to implement function composition. Consider the function 5 sin(x 3). It is composed of the functions g(y) = 5 sin(y) and f (x) = x 3. In the following session the function whose handle is h calls the functions whose handles are f and g.

>>f = @(x) x.^3;

>>g = @(x) 5*sin(x);

>>h = @(x) g(f(x));

>>h(2)

ans =

4.9468

3-65

64 of 107

Variables and Anonymous Functions

Variables can appear in anonymous functions in two ways:

• As variables specified in the argument list, as for example f = @(x) x.^3;, and

3-66

(continued …)

65 of 107

Variables and Anonymous Functions (continued)

• As variables specified in the body of the expression, as for example with the variables A and B in plane = @(x,y) A*x + B*y.

When the function is created MATLAB captures the values of these variables and retains those values for the lifetime of the function handle. If the values of A or B are changed after the handle is created, their values associated with the handle do not change.

This feature has both advantages and disadvantages, so you must keep it in mind.

3-67

More? See pages 132-134.

66 of 107

Subfunctions

A function M-file may contain more than one user-defined function. The first defined function in the file is called the primary function, whose name is the same as the M-file name. All other functions in the file are called subfunctions.

Subfunctions are normally “visible” only to the primary function and other subfunctions in the same file; that is, they normally cannot be called by programs or functions outside the file. However, this limitation can be removed with the use of function handles.

3-68

(continued …)

67 of 107

Subfunctions (continued)

Create the primary function first with a function definition line and its defining code, and name the file with this function name as usual.

Then create each subfunction with its own function definition line and defining code.

The order of the subfunctions does not matter, but function names must be unique within the M-file.

3-69

More? See pages 168-170.

68 of 107

Plotting

69 of 107

5-10

The grid and axis Commands

The grid command displays gridlines at the tick marks corresponding to the tick labels. Type grid on to add gridlines; type grid off to stop plotting gridlines. When used by itself, grid toggles this feature on or off, but you might want to use grid on and grid off to be sure.

You can use the axis command to override the MATLAB selections for the axis limits. The basic syntax is axis([xmin xmax ymin ymax]). This command sets the scaling for the x- and y-axes to the minimum and maximum values indicated. Note that, unlike an array, this command does not use commas to separate the values.

More? See page 222.

70 of 107

5-15

Saving Figures

To save a figure that can be opened in subsequent MATLAB sessions, save it in a figure file with the .fig file name extension.

To do this, select Save from the Figure window File menu or click the Save button (the disk icon) on the toolbar.

If this is the first time you are saving the file, the Save As dialog box appears. Make sure that the type is MATLAB Figure (*.fig). Specify the name you want assigned to the figure file. Click OK.

71 of 107

5-16

Exporting Figures

To save the figure in a format that can be used by another application, such as the standard graphics file formats TIFF or EPS, perform these steps.

1. Select Export Setup from the File menu. This dialog lets you specify options for the output file, such as the figure size, fonts, line size and style, and output format.

2. Select Export from the Export Setup dialog. A standard Save As dialog appears.

3. Select the format from the list of formats in the Save As type menu. This selects the format of the exported file and adds the standard file name extension given to files of that type.

4. Enter the name you want to give the file, less the extension. Then click Save.

More? See pages 225-226.

72 of 107

5-17

On Windows systems, you can also copy a figure to the clipboard and then paste it into another application:

1. Select Copy Options from the Edit menu. The Copying Options page of the Preferences dialog box appears.

2. Complete the fields on the Copying Options page and click OK.

3. Select Copy Figure from the Edit menu.

73 of 107

5-21

Subplots

You can use the subplot command to obtain several smaller “subplots” in the same figure. The syntax is subplot(m,n,p). This command divides the Figure window into an array of rectangular panes with m rows and n columns. The variable p tells MATLAB to place the output of the plot command following the subplot command into the pth pane.

For example, subplot(3,2,5) creates an array of six panes, three panes deep and two panes across, and directs the next plot to appear in the fifth pane (in the bottom-left corner).

74 of 107

5-22

The following script file created Figure 5.2–1, which shows the plots of the functions y = e1.2x sin(10x + 5) for 0 x 5 and y = |x3 100| for 6 x 6.

x = 0:0.01:5;

y = exp(-1.2*x).*sin(10*x+5);

subplot(1,2,1)

plot(x,y),axis([0 5 -1 1])

x = -6:0.01:6;

y = abs(x.^3-100);

subplot(1,2,2)

plot(x,y),axis([-6 6 0 350])

The figure is shown on the next slide.

75 of 107

5-23

Application of the subplot command. Figure 5.2–1

76 of 107

5-24

Data Markers and Line Types

To plot y versus x with a solid line and u versus v with a dashed line, type plot(x,y,u,v,’--’), where the symbols ’--’ represent a dashed line.

Table 5.2–1 gives the symbols for other line types.

To plot y versus x with asterisks (*) connected with a dotted line, you must plot the data twice by typing plot(x,y,’*’,x,y,’:’).

77 of 107

5-25

To plot y versus x with green asterisks (*) connected with a red dashed line, you must plot the data twice by typing plot(x,y,’g*’,x,y,’r--’).

78 of 107

Specifiers for data markers, line types, and colors.

Table 5.2–1, page 228.

Data markers

Dot (.)

Asterisk (*)

Cross (×)

Circle ( )

Plus sign (+)

Square ( )

Diamond ( )

Five-pointed star (w)

.

*

×

+

s

d

p

Line types

Solid line

Dashed line

Dash-dotted line

Dotted line

––

– –

– .

….

Colors

Black

Blue

Cyan

Green

Magenta

Red

White

Yellow

k

b

c

g

m

r

w

y

Other data markers are available. Search for “markers” in MATLAB help.

5-26

79 of 107

5-27

Use of data markers. Figure 5.2–2, page 229.

More? See pages 273-274.

80 of 107

5-28

Labeling Curves and Data

The legend command automatically obtains from the plot the line type used for each data set and displays a sample of this line type in the legend box next to the string you selected. The following script file produced the plot in Figure 5.2–3 (see next slide).

x = 0:0.01:2;

y = sinh(x);

z = tanh(x);

plot(x,y,x,z,’--’),xlabel(’x’), ...

ylabel(’Hyperbolic Sine and Tangent’), ...

legend(’sinh(x)’,’tanh(x)’)

81 of 107

5-29

Application of the legend command. Figure 5.2–3, page 230

82 of 107

5-30

Application of the hold command. Figure 5.2–4, page 231

83 of 107

5-31

Why use log scales? Rectilinear scales cannot properly display variations over wide ranges. Figure 5.2-5a, page 233.

84 of 107

5-32

A log-log plot can display wide variations in data values.

Figure 5.2-5b, page 233.

See pages 233-234.

85 of 107

5-33

Logarithmic Plots

It is important to remember the following points when using log scales:

1. You cannot plot negative numbers on a log scale, because the logarithm of a negative number is not defined as a real number.

2. You cannot plot the number 0 on a log scale, because log10 0 = ln 0 = −∞. You must choose an appropriately small number as the lower limit on the plot.

(continued…)

86 of 107

5-34

3. The tick-mark labels on a log scale are the actual values being plotted; they are not the logarithms of the numbers. For example, the range of x values in the plot in Figure 5.3–2 is from 101 = 0.1 to 102 = 100.

4. Gridlines and tick marks within a decade are unevenly spaced. If 8 gridlines or tick marks occur within the decade, they correspond to values equal to 2, 3, 4, . . . , 8, 9 times the value represented by the first gridline or tick mark of the decade.

Logarithmic Plots (continued)

(continued…)

87 of 107

5-35

  1. Equal distances on a log scale correspond to multiplication by the same constant (as opposed to addition of the same constant on a rectilinear scale).

For example, all numbers that differ by a factor of 10 are separated by the same distance on a log scale. That is, the distance between 0.3 and 3 is the same as the distance between 30 and 300. This separation is referred to as a decade or cycle.

The plot shown in Figure 5.3–2 covers three decades in x (from 0.1 to 100) and four decades in y and is thus called a four-by-three-cycle plot.

Logarithmic Plots (continued)

88 of 107

5-36

MATLAB has three commands for generating plots having log scales. The appropriate command depends on which axis must have a log scale.

  1. Use the loglog(x,y) command to have both scales logarithmic.

2. Use the semilogx(x,y) command to have the x scale logarithmic and the y scale rectilinear.

3. Use the semilogy(x,y) command to have the y scale logarithmic and the x scale rectilinear.

89 of 107

5-37

Command

bar(x,y)

plotyy(x1,y1,x2,y2)

polar(theta,r,’type’)

stairs(x,y)

stem(x,y)

Description

Creates a bar chart of y versus x.

Produces a plot with two y-axes, y1 on the left and y2 on the right.

Produces a polar plot from the polar coordinates theta and r, using the line type, data marker, and colors specified in the string type.

Produces a stairs plot of y versus x.

Produces a stem plot of y versus x.

Specialized plot commands. Table 5.2-3, page 236

90 of 107

Exponential and Power Functions Plotted on Log Scales (Figure 5.2-6, page 235)

5-38

The program is on pages 234-235.

91 of 107

5-39

A polar plot showing an orbit having an eccentricity of 0.5.

Figure 5.2–7, page 237.

See pages 236-237.

92 of 107

Error Plots, Figure 5.2-8, page 238.

5-40

The code is on page 238.

93 of 107

Publishing Reports Containing Graphics�See Pages 238-240.

5-41

94 of 107

5-42

Interactive Plotting in MATLAB

This interface can be advantageous in situations where:

You need to create a large number of different types of plots,

You must construct plots involving many data sets,

You want to add annotations such as rectangles and ellipses, or

You want to change plot characteristics such as tick spacing, fonts, bolding, italics, and colors.

For details, see pages 241-246.

95 of 107

5-43

The interactive plotting environment in MATLAB is a set of tools for:

Creating different types of graphs,

Selecting variables to plot directly from the Workspace Browser,

Creating and editing subplots,

Adding annotations such as lines, arrows, text, rectangles, and ellipses, and

Editing properties of graphics objects, such as their color, line weight, and font.

96 of 107

5-44

The Figure toolbar displayed. Figure 5.3–1, page 241.

97 of 107

5-45

The Figure and Plot Edit toolbars displayed. Figure 5.3–2, page 243.

98 of 107

5-46

The Plot Tools interface includes the following three panels associated with a given figure.

The Figure Palette: Use this to create and arrange subplots, to view and plot workspace variables, and to add annotations.

The Plot Browser: Use this to select and control the visibility of the axes or graphics objects plotted in the figure, and to add data for plotting.

The Property Editor: Use this to set basic properties of the selected object and to obtain access to all properties through the Property Inspector.

99 of 107

The Figure window with the Plot Tools activated. Figure 5.3-3, page 244.

5-47

100 of 107

5-48

Three-Dimensional Line Plots:

The following program uses the plot3 function to generate the spiral curve shown in Figure 5.4–1, page 247.

>>t = 0:pi/50:10*pi;

>>plot3(exp(-0.05*t).*sin(t),...

exp(-0.05*t).*cos(t),t),...

xlabel(’x’),ylabel(’y’),zlabel(’z’),grid

See the next slide.

101 of 107

5-49

The curve x = e0.05t sin t, y = e0.05t cos t, z = t plotted with the plot3 function. Figure 5.4–1, page 247.

102 of 107

5-50

Surface Plots:

The following session shows how to generate the surface plot of the function z = xe[(xy2)2+y2], for 2 x 2 and 2 y 2, with a spacing of 0.1. This plot appears in Figure 5.4–2, page 248.

>>[X,Y] = meshgrid(-2:0.1:2);

>>Z = X.*exp(-((X-Y.^2).^2+Y.^2));

>>mesh(X,Y,Z),xlabel(’x’),ylabel(’y’),...

zlabel(’z’)

See the next slide.

103 of 107

5-51

A plot of the surface z = xe[(xy2)2+y2] created with the mesh function. Figure 5.8–2

104 of 107

5-52

The following session generates the contour plot of the function whose surface plot is shown in Figure 5.8–2; namely, z = xe[(xy2)2+y2], for 2 x 2 and 2 y 2, with a spacing of 0.1. This plot appears in Figure 5.4–3, page 249.

>>[X,Y] = meshgrid(-2:0.1:2);

>>Z = X.*exp(-((X- Y.^2).^2+Y.^2));

>>contour(X,Y,Z),xlabel(’x’),ylabel(’y’)

See the next slide.

105 of 107

5-53

A contour plot of the surface z = xe[(xy2)2+y2] created with the contour function. Figure 5.4–3

106 of 107

5-54

Function

contour(x,y,z)

mesh(x,y,z)

meshc(x,y,z)

meshz(x,y,z)

surf(x,y,z)

surfc(x,y,z)

[X,Y] = meshgrid(x,y)

[X,Y] = meshgrid(x)

waterfall(x,y,z)

Description

Creates a contour plot.

Creates a 3D mesh surface plot.

Same as mesh but draws contours under the surface.

Same as mesh but draws vertical reference lines under the surface.

Creates a shaded 3D mesh surface plot.

Same as surf but draws contours under the surface.

Creates the matrices X and Y from the vectors x and y to define a rectangular grid.

Same as [X,Y]= meshgrid(x,x).

Same as mesh but draws mesh lines in one direction only.

Three-dimensional plotting functions. Table 5.4–1, page 250.

107 of 107

5-55

Plots of the surface z = xe(x2+y2) created with the mesh function and its variant forms: meshc, meshz, and waterfall. a) mesh, b) meshc, c) meshz, d) waterfall.

Figure 5.4–4, page 250.