Chapter 7

User-Defined Functions and Function Files

A simple function in mathematics, f(x), associates a unique number to each value of x. The function can be expressed in the form y = f(x), where f(x) is usually a mathematical expression in terms of x. A value of y (output) is obtained when a value of x (input) is substituted in the expression. Many functions are programmed inside MATLAB as built-in functions, and can be used in mathematical expressions simply by typing their name with an argument (see Section 1.5); examples are sin(x), cos(x), sqrt(x), and exp(x). Frequently, in computer programs, there is a need to calculate the value of functions that are not built in. When a function expression is simple and needs to be calculated only once, it can be typed as part of the program. However, when a function needs to be evaluated many times for different values of arguments, it is convenient to create a “user-defined” function. Once a user-defined function is created (saved) it can be used just like the built-in functions.

A user-defined function is a MATLAB program that is created by the user, saved as a function file, and then used like a built-in function. The function can be a simple single mathematical expression or a complicated and involved series of calculations. In many cases it is actually a subprogram within a computer program. The main feature of a function file is that it has an input and an output. This means that the calculations in the function file are carried ...

Get MATLAB: An Introduction with Applications 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.