User-Defined Function in Matlab

Matlab → Built-In Functions → Scripts → User-Defined Functions

We studied Matlab built-in functions and Matlab statistical functions in chapter 1. Here we consider user-defined functions where we can build our own functions in Matlab, and then these functions can be used like a built-in function. Functions are normally used for large and complex programs, and in programs where we need to use a function within another function. A function groups a number of program statements into a unit. This unit can then be called from other parts of the program. Another important reason to use functions is conceptual organization of a program.

The first executable line (the first line other than comments) in a function must be the function definition line. Format of a function definition line is as follows.


For example, if we have two outputs and two inputs in a program, the functions definition line would be similar to


For one output and three inputs, it would be

function output1=functionName(input1,input2, input3)

Note that not brackets are required if there is only one input or output. In the next example, we calculate accumulated amount using continuous compound interest formula. This simple program shows the construction of a function and how it is executed.

Note that, to execute a function, we need to write the function name (for example, “Interest” in this case) in command window and all input values in the bracket. The next example shows the same program with comments and fprintf statement.

Note that in the above example, there is a semicolon (;) at the end of the statement

A = P*exp(r*t);

You should also try this program without using the semicolon. And remember that semicolon is used to halt display of that particular statement.