6. Function M-files

fplot, fzero, fminbnd, quadL

Functions operating on functions: fplot, fzero, fminbnd, quadL

Suppose a function y = func(x) has been defined in a function M-file func.m. Then

  • fplot(@func,[a b]) or fplot(’func(x)’,[a b]) plots the function for a ≤ x ≤ b without requiring you to set up arrays
  • fzero(@func,[a b]) or fzero(’func(x)’,[a b]) finds a root of the equation func(x) = 0 inside the interval [a, b] providing func(a) and func(b) have opposite signs. fzero(@func,c) or fzero(’func(x)’,c) finds a root of the equation func(x) = 0 by commencing a search at x = c. 
  • fminbnd(@func,a,b) or fminbnd(’func(x)’,a,b) finds the coordinates of a minimum point for a ≤ x ≤ b.
  • quadL(@func,a,b) or quadL(’func(x)’,a,b) finds an accurate value for the integral from a to be of func(x) dx.

Note: quadL uses arrays in its calculations. Hence the M-file func.m must use the array dot notation in the definition of func(x). This is not required for fplot, fzero or fminbnd.

Example: Consider the function f1(x) = x − cos x / 2 + x2 . Define it in the function M-file f1.m.

function y=f1(x)

% use dots as quadL(@f1,a,b) occurs in calling M-file

y=(x-cos(x))./(2+x.^2); % ";" to avoid printing inside f1.m

Now construct and execute the following M-file. This will graph the function for −10 ≤ x ≤ 10, find its zero (from the graph, between 0 and 1), find the x and y coordinates of the minimum and integrate the function from the x-intercept to x = 10.

clear all

fplot(@f1,[-10 10])

hold on

plot([-10 10],[0 0],’k’) % adds x-axis

hold off

x_intercept=fzero(@f1,[0 1])

[xmin,ymin]=fminbnd(@f1,-3,3) % finds both the x-coordinate

% and y-coordinate of minimum

accurate_integral=quadL(@f1,x_intercept,10)

As well as the graph, the following output should result:

x_intercept = 0.7391

xmin = -0.4562

ymin = -0.6132

accurate_integral = 1.8910

Exercise 1: Consider the output OP(t) = 1 − 4e−t sin t for t ≥ 0. Define this function in an M-file and then use fplot to graph it for 0 ≤ t ≤ 5, find the two zeros, find its minimum value and evaluate the integral from 0 to 5 OP(t) dt.

Exercise 2: Knowing that tan x has a vertical asymptote at x = π/2, see what occurs if you enter after the prompt fplot(@tan,[1 2]). Remember that tan x is already stored in tan.m. Knowing that √x only exists for x ≥ 0, see what occurs if you enter fplot(@sqrt,[-1 4]).