Context
Transcription
MATLAB includes thousands of ready-to-use functions that perform a variety of common
tasks.
But what if we need a custom function for our application?
We can write our own MATLAB function.
Let's see how.
A MATLAB function consists of two parts: the declaration, and the body.
The declaration begins with the keyword, FUNCTION, followed by how we will use, or call, the
function.
This means we provide the output variables, the function name, and the input variables.
In the function body, we provide the set of commands to be executed each time the function
is called.
We use other MATLAB functions in combination with the inputs to create the output variables.
Finally, we mark the end of the function with the keyword, END.
That covers the syntax, but how do we use a custom function?
Let's see how by doing an example.
Suppose we need to sum the first n terms of a geometric series, which is given by this
formula.
The function only has a single output variable, s, which corresponds to the sum.
The brackets are required when there are multiple outputs, but since we only have one output
we can remove them.
Function names follow the same conventions as the naming of MATLAB variables and should
not overlap with existing function names.
Let's call ours geoSum.
To complete the declaration, we'll provide the list of input variables needed to compute
a geometric sum: the common ratio, r, and the number of terms to sum, n.
Next, we include the instructions for computing s in terms of r and n inside the function
body.
It's also good practice to provide comments below the function declaration for our future
reference, or to communicate the intent to others.
Now let's put this function to use.
We can do this two different ways.
If the function will be used in a single code file, we move the definition to the bottom
of the script, and then call geoSum in the code above.
When we run the script, our function is used to calculate the geometric sum.
But what happens if we need our function in other code files or at the command prompt?
Uh oh, red text usually isn't good.
This error occurred because geoSum is currently a local function, meaning we can only use
it in the script where it's defined.
In this case, we need to create a separate code file that contains only the function
definition.
So let's delete the code above.
Lastly, we save our file in the Current Folder, making sure that file name matches the function
name.
Now when we call geoSum at the command prompt, the two input values are passed to the function,
the function body is executed, and the value of the output variable is returned.
And just like that, there's one more function we can call.
Hello, geoSum?
I'd like the sum for r equals one-half and n equals infinity please.
<sigh> Yes, I'll hold.