Got a repetitive task that occurs in multiple locations in your script? Well, then functions may be the answer for you! But, which type of function because there are a few different types? Fear not, for we will learn of them all!
The first type of function that we will learn about is internal functions. Internal functions are functions that are stored at the bottom of MATLAB scripts to be called back at various points throughout the code. Rather than typing the same thing over and over again, functions allow us to make our code cleaner, faster, and easier to keep track of when changes are made. Let's take a look at how to define a function.
matlab
% Add one to input
function sum = increment(a)
sum = a + 1;
end
% Multiply both inputs
function product = multiply(a,b)
product = a * b;
end
To define a function, we first start out by writing 'function'; this preps MATLAB to store your function properly for retrieval. We then list the output, or outputs... wink wink, that we would like to retrieve from the function. This is followed by the function handle (what you will use to call the function later on) and the input or inputs to the function. If there are multiple inputs, then they should be separated by a comma.
If there are multiple outputs to a function, then we can do the following to write our function.
matlab
function [sum, multi] = addMulti(a,b)
sum = a + b;
multi = a * b;
end
We list out both outputs in a square bracket. This is needed because we are grouping the outputs together in an array to be outputted. Speaking of outputting...
To call a function, internal and external, we can do the following. Let's use the function above, addMulti().
matlab
[s,m] = addMulti(3,2);
function [sum, multi] = addMulti(a,b)
sum = a + b;
multi = a * b;
end
From the code above, s will equal the sum of our inputs, 2 and 3, so s = 5, and m will equal 2*3, so m = 6. Now, what if we only listed one output? What do you think will happen?
matlab
s = addMulti(3,2);
function [sum, multi] = addMulti(a,b)
sum = a + b;
multi = a * b;
end
Well, since we only listed one output variable, then we will only get the output for the first variable defined in our function; this variable is 'sum'. Cool, huh!