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=mc2
    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×108 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 1kgm2s2=1J.
    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 6e3cosx2, which is composed of the functions h(z)=6ez, g(y)=3cosy, and f(x)=x2. Use the anonymous function to plot 6e3cosx2 over the range 0 ≤ x ≤ 4.

© 2025 Air Supply Information Center (Air Supply BBS)