Wichita State University Logo

M451: Computational Mathematics

2.6 Local Functions in MATLAB


2.6.1 Named Procedures

In the MATLAB programming language a local function is a function defined outside of any other function structure and within an M-file , an ascii text file with the ".m" file extension. So we may have several local functions defined in an M-file.

Example 1

function y = AnimateVectorProduct(x)

 end

 function z = VectorProduct(x, y)

 end

 function h = PlotGraphics

 end

Here we give an example of declaring three different local functions in an M-file.

A Named Procedure includes both MATLAB scripts and special MATLAB local functions. So there are two kinds of M-files:

  1. M-files whose first executable MATLAB statement uses the function keyword to declare a function. The function name must match the filename (without the .m extension). This match is case sensitive.

This kind of local function is a named procedure because any MATLAB statement in any M-file, the command line environment, or code in a mixed language application may invoke (call) this function by its function name. This M-file that shares this name must be in the path of the MATLAB environment or operating system environment so that the M-file can be located in the file system.

  1. M-files whose first executable MATLAB statement does not use the function keyword. This M-file defines a MATLAB script.

If the declarations in example 1 reside in the M-file "AnimateVectorProduct.m", then the local function AnimateVectorProduct is a local function that is also a named procedure, and the other two local functions VectorProduct and PlotGraphics have file scope . They can only be invoked by a MATLAB statement in this file.

Local functions all have their own workspace. The other functions do not have access to any local variables defined in the input argument list, output argument list, or their function code block.

2.6.2 Nested Functions

A Nested Function is a function defined within the code block of another function.

Example 2

function y = AnimateVectorProduct(x)

     function z = VectorProduct(x, y)

     end

     function h = PlotGraphics

     end
 end

In example 2, functions VectorProduct and PlotGraphics are nested functions and they have function scope . These two functions can only be invoked by MATLAB statement in the AnimateVectorProduct function code block.

The work space of a nested function resides within the work space of the function in which it is defined. That means that function VectorProduct and PlotGraphics have access to any variables or labels in the workspace allocated for the local function AnimateVectorProduct . However nested functions also enjoy their own workspace within their parent's work space. Any local variables defined in VectorProduct are invisible to MATLAB statements outside of its function code block.

MATLAB scripts also use the workspace of the function or environment of the MATLAB statement that invokes it. Like a nested function, if a MATLAB statement invokes a script, the script uses the work space of the function where the MATLAB statement resides. Unlike nested functions any variables or labels created in a script will continue to exist in the work space of the calling function after the script execution terminates.

2.6.3 The Global Work Space

MATLAB procedures (scripts and functions) can also create labels and variables in the Global Work Space . The global work space is available to all MATLAB procedures. To access a variable in the global work space one must declare the variable to be global using the persistent keyword.

persistent ErrorCode;

if isempty(ErrorCode)
    ErrorCode = 0;      % No current error condition!
end

When a persistent variable is declared when does not already exist in the global workspace, the MATLAB interpreter creates the variable in the global work space and initializes it to [] , the empty array. You code should always check to make sure that a global variable exists and has a well-defined value before using it. The MATLAB condition structure above checks to see if the global variable isempty ; that is equal to [] . If it is empty, the condition code block initializes the global variable to zero.

Since 2022, the global work space and the base work space are different* !

In [14]:
fill([0 3 3 0],[0 0 1 1],'r',[0 3 3 0],[1 1 2 2],'g',[0 3 3 0],[2 2 3 3],'w')
title('Bulgaria')
axis off

       

2.6.4 Filling Rectangles

The MATLAB built-in function fill fills a rectangle with color in a plot. We can create the Bulgarian flag using the fill command and three rectangles. Notice that in this plot we remove the axes from the plot since they would only distract from the image we want to create. Notice that we give the plot a title using the MATLAB built-in function title .

The MATLAB function fill requires the vertices of our rectangle and the necessary color to draw within the rectangle. The first rectangle has vertices

$$ (0,0), (3,0), (3,1) and (0,1) $$
Like the plot MATLAB built-in function we specify the $x$-coordinates in a vector and the corresponding $y$-coordinates in a second vector

> x = [ 0, 3, 3, 0 ]
> y = [ 0, 0, 3, 3 ]
> fill(x, y, 'r')

This block of code creates a red rectangle. We create the three necessary fields for the flag using a single fill command by listing the three sets of $x$-coordinates, $y$-coordinates, and color serially.

2.6.5 Subplot

One can create an grid of plots in a single figure using the subplot built-in MATLAB function. The built-in function subplot requires three arguments,

  • the number of rows in the grid of plots
  • the number of columns in the grid of plots
  • the index of the current plot

Unlike everything else in MATLAB, the elements of grid of plots is indexed row-wise instead of column-wise. For a $2\times 4$ grid of $8$ plots in our figure we set the first two arguments of the MATLAB command to $2$ and $4$. To create a plot in the first grid of the second row one needs to use the MATLAB statement

>     subplot(2,4,5)
In [13]:
N   = 7;
x   = linspace(-pi, pi, 1001);
fig = figure;
hold on;

subplot(2,4,1)
plot(x, ones(size(x)))
title('$\cos(0x)=1$','Interpreter','latex')

subplot(2,4,2)
plot(x, zeros(size(x)))
title('$\sin(0x)=0$', 'Interpreter', 'latex')

for k=2:N
    subplot(2,4,k+1)

    if mod(k,2)
        plot(x, sin((k-1)/2*x))
        title(sprintf('sin(%d x)', (k-1)/2))
    else
        plot(x, cos(k/2*x))
        title(sprintf('cos(%d x)', k/2))
    end
end

       

2.6.6 Exercises

1. euflags.m

Create a function euflags in file euflags.m that creates a 2×3 grid of some European flags. In order these flags are the flags of Bulgaria, Hungary, Lithuania, Ukraine, Netherlands and Luxembourg. Use the MATLAB function subplot to create the graphs of each flag using the fill function. Your function should return the figure handle of the figure it creates.

function fig = euflags()

    Title each flag with the name of its country.

You can make them look more like flags by changing the aspect ratio. Obtain the current position using the MATLAB statement

pos = get(fig, 'Position')

Then set the width pos(3) = 880, and height, pos(4) = 420; and set the position to the new width and height

pos(3) = 880; pos(4) = 420; set(fig, 'Position', pos)

Some EU Flags

figure 1

2. epicycloid.m

Create a function epicycloid in file epicycloid.m the plots an epicycloid based on two input parameters a and b , and an optional parameter max . The output of your function should be the figure handle of the MATLAB figure window your function creates.

function fig = epicycloid(a, b, max)

The equation of the epicycloid is given by

$$ \left.\begin{array}{rcl} x(t) &= (a + b)\cos(t) - b\cos\left(\left(\frac{a}{b} + 1\right)t\,\right) \\ y(t) &= (a + b)\sin(t) - b\sin\left(\left(\frac{a}{b} + 1\right)t\,\right) \end{array}\right\}\quad 0\le t\le10\pi $$

You should evaluate your epicycloid using an anonymous function f . The anonymous function should have three inputs a , b , and t . Anonymous function may only have one output so it should output an array with $2$ columns and length(t) columns. The first column should contain $x(t)$ and the second column should contain $y(t)$.

The MATLAB function sprintf returns a formatted string using a format specifier string in the first argument just like fprintf , but returning the created string instead of emitting it to a file or to the command window.

formatStr = sprintf('Epicycloid: a=%g, b=%g, max=%g', a, b, max)


will create a formatted string with the values of a , b and max embedded in the string. You can then pass this string to the title MATLAB function.

  1. Your function should test to see if there is a third argument and default to a value max=10*pi .

  2. Your function should create a new figure window using the MATLAB function figure

  3. Plot the curve using the default line specification, plot(x,y) .

  4. You will need to plot a LOT of small line segments to simulate a curve. Use the step size of .05 from 0 to max .

  5. Create a title for the figure. For example if a=12 , b=54 , and max=10*pi , the title should be

    'Epicycloid: a=12, b=5, max=62.8319'
    
  6. Set the aspect ratio of the figure to 1:1 using the MATLAB command axis equal .

  7. Display the grid lines using the MATLAB command grid on .

Epicycloid

figure 2

3. chebyshev.m

The Chebyshev polynoimials of the first kind are used to determine a spectral decomposition of the solution of a differential equation on the interval $[-1,1]$. They are very useful in STEM. The Chebyshev polynomial can be determined using one of two iterative methods:

1. The Trigonometric Definition

The formal definition of the Chebyshev polynomial of the first kind of order n is given by the equation

$$ T_n(x) = \cos\left(n\cdot\cos^{-1}(x)\right),\qquad |x|\le 1 $$

For example

$$ \begin{align*} T_0(x) &= \cos\left(0\cdot\cos^{-1}(x)\right) = \cos(0) = 1 \\ \\ T_1(x) &= \cos\left(1\cdot\cos^{-1}(x)\right) = x \end{align*} $$
So the Chebyshev polynomial of order zero is $T_0(x) = 1$, a constant function. The Chebyshev polynomial of order one is $T_1(x) = x$, the identity function. The Chebyshev polynomial of order $n$ is a polynomial of degree $n$ on the interval $[-1,1]$.

2. The Recursive Definition

The recursive definition defines the higher order Chebyshev polynomials in terms of the previous two.

$$ \begin{align*} T_0(x) &= 1 \\ \\ T_1(x) &= x \\ \\ T_n(x) &= 2x\,T_{n-1}(x) - T_{n-2}(x) \end{align*} $$
So the Chebyshev polynomials of order two, three, and four are given by

$$ \begin{align*} T_2(x) &= 2x\,T_1(x) - T_0(x) = 2x(x) - 1 = 2x^2 - 1 \\ \\ T_3(x) &= 2x\,T_2(x) - T_1(x) = 2x\left(2x^2 - 1\right) - x = 4x^3 - 3x \\ \\ T_4(x) &= 2x\,T_3(x) - T_2(x) = 2x\left(4x^3 - 3x\right) - \left(2x^2 - 1\right) = 8x^4 - 8x^2 + 1 \end{align*} $$

Create a function chebyshev in file chebyshev.m that plots the first N+1 Chebyshev polynomials, $T_0, T_1, T_2, \dots, T_N$ on the interval $[-1,1]$ based on the input N . The output of your function should be the figure handle of the MATLAB figure window your function creates.

In order the display text that looks like mathematics you must create your formatted string using the LaTeX interpreter. LaTeX is a document preparation specification and language used by STEM. For example, if chebyshev is called passing the value N=12 , then first you must create the format specification string and use your format string to create the title string.

titleStr = sprintf('Chebyshev: $T_0$ to $T_{%d}$', N);

creates the correct format string for the title using the correct LaTeX commands and the value of N . Then we create the title

title(titleStr, 'Interpreter', 'latex')
  1. Your function should create a new figure window using the MATLAB function figure

  2. Plot the curve using the default line specification, plot(x,y) .

  3. You will need to plot a LOT of small line segments to simulate a curve. Use the step size of .05 from -1 to 1 .

  4. Create a title for the figure. For example if N=12 , the title should be
    $$ \text{'Chebyshev Polynomials: $T_0$ to $T_{12}$'} $$

  5. Set the aspect ratio of the figure to 1:1 using the MATLAB command axis equal .

  6. If you use multiple plot commands you will need to use the MATLAB command hold on to make sure the plot will contain all of the plots.

Chebyshev Polynomials

figure 3

Creative Commons Logo - White


Your use of this self-initiated mediated course material is subject to our Creative Commons License .


Creative Commons Attribution-NonCommercial-ShareAlike 4.0

Creative Commons Logo - Black
Attribution
You must give appropriate credit, provide a link to the license, and indicate if changes were made. You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you or your use.

Creative Commons Logo - Black
Noncommercial
You may not use the material for commercial purposes.

Creative Commons Logo - Black
Share Alike
You are free to share, copy and redistribute the material in any medium or format. If you adapt, remix, transform, or build upon the material, you must distribute your contributions under the same license as the original.