Functions
Why use Functions?
- Improve program structure & avoid errors
- Decompose a large program into smaller, simpler building blocks: improve structure and facilitate reading/debugging
- Each building block completes a well defined and self-contained task
- Reduce the places where logical errors are made
- Reuse code
- Several times in the same program
- Across several different programs (don’t re-invent the wheel every time!)
Functions
- Functions are “special” scripts that take one or more inputs and return one or more outputs
- MATLAB has many built-in (also called intrinsic) functions, e.g.
|
sin(arg) exp(arg)
plot(arg1,arg2) size(arg)
load(arg) load(arg1,arg2,…)
|
- Outputs are returned by assignment:
|
y = sin(x)
z = exp(x)
[rows,cols] = size(mat) % no. of rows and cols of array mat
|
- Just like scripts, functions are written/stored as .m files
- Writing your own functions is very easy: you just need the right header to let MATLAB know that your script is a function
- Start your script with

IMPORTANT: You MUST save your .m file using the same name as your function! In this example, you must use “functionName.m”
- The first line of the function is called the interface. It defines a function’s:
- Name: functionName
- Inputs: in1, in2, ...
- Outputs: out1, out2, ...
Example:
Let’s write a function that computes \( y(x) = a_1x^2 + a_2x + a_3 \)
|
function y = parabola(x,a)
%Function to calculate y=a1*x^2+a2*x+a3
%inputs: x – 1D array of length n
% a – 1x3 array with coefficients a1, a2, a3
%outputs:y – 1D array of length n
n = length(x);
for i = 1:n
y(i) = a(1)*x(i)^2 + a(2)*x(i) + a(3);
end
|
Tip!
Add comments to the beginning of your function to let users know what it does.
Running Functions
- Intrinsic functions like sin() can be called from anywhere.
- To call user-written functions you must:
a) Have stored them in current directory, or
b) Add their location to the MATLAB path
Let’s call our function parabola()
>> x = rand(1,20);
>> const = [1, 2, 3];
>> y = parabola(x,const);
>> plot(x,y,‘o’)
Comments in functions
- Functions should be commented just like all scripts
- Comments immediately under the function’s interface are the function’s help entry
For our parabola() function:
|
>> help parabola
Function to calculate y=a1*x^2+a2*x+a3
inputs: x - 1D array of length n
a - 1x3 array with coefficients a1, a2, a3
outputs: y - 1D array of length n
|