Lesson 05: User-Defined Functions

Objective

  • Learn how to create and use your own MATLAB functions
  • Learn how to create and use anonymous functions

Background

A user-defined function is a MATLAB program that is created by the user and saves as a function file. It can be used like a built-in function. A function usually has input arguments (or parameters) and/or output variables (or parameters). Both parameters can be scalars, vectors, matrices of any size. In MATLAB, a function can has any number of input and output parameters, also including zero.

Questions

  1. Perhaps the most famous equation in physics is
    \(E=m{{c}^{2}}\)
    which relates energy E to mass m. The speed of light in a vacuum, c, is the property that links the two together. The speed of light in a vacuum is \(2.9979\times {{10}^{8}}\) m/s.
    1. Create a function called energy to find the energy corresponding to a given mass in kilograms. Your result will be in joules, since \(1\,kg{}^{{{m}^{2}}}\!\!\diagup\!\!{}_{{{s}^{2}}}\;=1\,J\).
    2. Use your function to find the energy corresponding to masses from 1 kg to 106 kg. Use the logspace function (consult help logspace) to create an appropriate mass vector.
  2. Create four anonymous functions to represent the function \(6{{e}^{3\cos {{x}^{2}}}}\), which is composed of the functions \(h(z)=6{{e}^{z}}\), \(g(y)=3\cos y\), and \(f(x)={{x}^{2}}\). Use the anonymous function to plot \(6{{e}^{3\cos {{x}^{2}}}}\) over the range 0 ≤ x ≤ 4.

© 2024 Air Supply Information Center (Air Supply BBS)