Kahibaro
Discord Login Register

Creating Simple Functions

Why Create Your Own Functions

In MATLAB, a function is a reusable piece of code that accepts inputs, performs some operations, and returns outputs. Functions are stored in their own files and can be called from the Command Window, scripts, or other functions. Creating simple functions helps you avoid repeating code, keep your scripts shorter, and organize your work into clear steps.

Functions are different from scripts. In this chapter, you will focus only on how to create and use basic function files, without yet going into all details about inputs, outputs, or advanced organization.

Basic Function File Structure

A simple MATLAB function lives in a file whose name matches the function name. The file must be a plain text file with extension .m. The most important part of the file is the first line, called the function definition line.

The general form of a very simple function that takes one input and returns one output is
$$
\text{function } \text{output} = \text{name}(\text{input})
$$

In MATLAB code, that looks like:

function y = squareNumber(x)
    y = x.^2;
end

Here, squareNumber is the function name and must be the same as the file name. You must save this code in a file called squareNumber.m in a folder that MATLAB can see. When you call squareNumber(5) in the Command Window, MATLAB opens squareNumber.m, runs the code with x = 5, and returns the squared value.

Every function file should end with the keyword end. For simple functions, the body of the function is everything between the function line and end.

Creating Your First Function in the Editor

To create a simple function, you usually work in the MATLAB Editor, not directly in the Command Window.

Open a new function file by choosing to create a new function from the toolstrip, or by opening a new script and typing a function definition line at the top. For example, type:

function c = celsiusToFahrenheit(t)
    c = (9/5)*t + 32;
end

Then save the file as celsiusToFahrenheit.m. As soon as you save, MATLAB recognizes this file as a function file. You can then go to the Command Window and type:

celsiusToFahrenheit(0)
celsiusToFahrenheit(100)

MATLAB will run the code inside the function for each input you provide.

The function body can contain any valid MATLAB statements. For very simple functions, this may be only one line that computes c from t, but it can also be several intermediate steps before assigning the final output.

Naming Rules and Good Simple Names

For a simple function to work correctly, its file name and the primary function name must match exactly, including capitalization on systems where that matters. If your function definition line is:

function y = doubleValue(x)

then you must save the file as doubleValue.m. If you save it with a different name, for example myDouble.m, you must also change the function name in the definition line to myDouble.

Function names must begin with a letter and can contain letters, numbers, and underscores. Avoid using spaces or special characters. Do not use names that are already built in to MATLAB, such as sum, mean, or plot, for your own function files, because this can hide or shadow the built in functions.

Choose simple and descriptive names for your first functions. For example, addTax, circleArea, or hypotenuse make it easy to guess what the function does.

Simple Functions with One Input and One Output

Many beginner functions involve a single input value and a single output value. The pattern is always the same.

You declare the function:

function out = functionName(in)
    % computations
    out = ...;   % assign something to out
end

Here is a basic example that computes the area of a circle from its radius:

function a = circleArea(r)
    a = pi * r.^2;
end

After saving this as circleArea.m, you can call it with:

area1 = circleArea(1);
area2 = circleArea(2.5);

Inside the function, r is a variable that exists only while the function runs, and a is the value that the function returns. For simple functions, always make sure that the output variable on the first line is assigned a value before end. If you forget to assign it, MATLAB will return an empty result.

Writing and Using Simple Functions Without Inputs

You can also write functions that do not need any input arguments. Their function line has empty parentheses. For example:

function today = getTodayDate()
    today = datetime('today');
end

Save this as getTodayDate.m. You call it without arguments:

d = getTodayDate();

A function without inputs can still perform calculations, display information, or create plots. In this chapter, focus on the simple pattern that the function returns something through its output variable.

You can even write a function without inputs and without outputs. Such a function performs actions for their side effects, such as plotting. For example:

function showWelcomeMessage()
    disp('Welcome to my program.');
end

Save it as showWelcomeMessage.m and call it as:

showWelcomeMessage();

In this case the function name does not appear on the left side of an assignment, since there is no output to store.

Simple Functions with No Explicit Output

Sometimes you want a function that performs an operation but you do not care about its return value. You can still define an output, but ignore it when you call the function. For instance:

function t = printTriple(x)
    t = 3 * x;
    disp(t);
end

If this is saved as printTriple.m, you can call:

printTriple(4);

MATLAB will display 12 and return a value, but if you do not assign it to a variable, the value is not saved in your workspace. This is different from a function that really has no output in its definition line. For very simple functions, it is usually clearer either to define an output and assign it to a variable when you call the function, or to write a function with no output and only side effects.

Commenting and Help Text for Simple Functions

For any new function, especially simple ones you will use later, it is useful to add a short explanation at the top of the file. This is called the help text. It appears directly below the function definition line and begins with % so that MATLAB treats it as a comment.

For example:

function y = cube(x)
% CUBE Compute the cube of the input.
%   Y = CUBE(X) returns X.^3.
    y = x.^3;
end

The first comment line, here CUBE Compute the cube of the input., gives a single sentence summary. The next lines provide a simple description of how to call the function. When you later type help cube in the Command Window, MATLAB shows these lines as documentation.

Even for simple functions, writing a brief comment at the top helps you and others remember what the function does and how to use it.

Testing Simple Functions

After you create a function file and save it, always test it with a few simple calls from the Command Window or a script. Use small, easy values where you know what the answer should be.

For example, after writing:

function f = fahrenheitToCelsius(t)
    f = (t - 32) * 5/9;
end

save it as fahrenheitToCelsius.m, then test it:

fahrenheitToCelsius(32)    % expected result is 0
fahrenheitToCelsius(212)   % expected result is 100

If the results are not what you expect, you can reopen the file in the Editor, fix the code, save it, and test again. For very simple functions, this quick cycle of editing, saving, and testing is usually enough to find mistakes.

If MATLAB says that the function is undefined, check that the file name and the function name are the same, and that the file is stored in the current folder or a folder on the search path.

Important points to remember:
Function code must start with a function definition line and end with end.
The function name and the .m file name must match.
Use simple, descriptive names and avoid built in function names.
Add short comments at the top of the file so help shows useful information.
Always save and then test your function with easy values you can predict.

Views: 4

Comments

Please login to add a comment.

Don't have an account? Register now!