User Defined Functions and Function Files
MATLAB Function Files
MATLAB Function Files let you package a calculation so that you can reuse it with different data. Instead of editing numerical values inside a file each time, you supply inputs when you call the function and capture its outputs. In engineering calculations, this makes the required quantities, their units, and the returned results easier to check.
Define the calculation's interface
A function's interface specifies its name, inputs, and outputs. For a calculation with two inputs and one output, the governing relationship is
The corresponding MATLAB declaration has this structure:
function y = calculation(x1,x2)
y = x1 + x2;
endThe declaration introduces the function; the body computes the result. Assign a value to each output that the caller requests. For several outputs, use square brackets:
function [first,second] = calculation(x1,x2)
first = x1 + x2;
second = x1 - x2;
endInputs appear in parentheses and outputs appear before the equals sign. Their positions determine how values are transferred. The names describe their roles inside the function; they need not match the caller's variable names.
Save and call the function
Save a function file with the same name as its first function, followed by .m. For example, save this function as resistorPower.m in the current folder or a folder on MATLAB's search path:
function P = resistorPower(I,R)
% RESISTORPOWER Power in W for scalar I in A and R in ohms.
P = I^2*R;
endFor a resistor, the calculation implements
A call supplies values rather than repeating the declaration:
power = resistorPower(2,6);The first argument becomes I, the second becomes R, and the returned value is stored in power. Here, P=(2 A)2(6 Ω)=24 W. MATLAB's ordinary numeric variables do not attach these physical units automatically, so document the expected units and supply consistent values.
Keep workspaces separate
A function workspace is the collection of variables belonging to one function call. An ordinary function in its own file receives values through its inputs; it does not automatically read variables from the base workspace. Its temporary variables also do not automatically appear in the caller.
For ordinary numeric inputs, changing a parameter inside the function does not change the caller's variable. To keep a computed value, return it and capture it explicitly.
For a declaration beginning function [a,b] = results(x), the call [u,v] = results(data) stores a in u and b in v. Requesting just u = results(data) captures the first output, even if you intended to keep the second.
Organize functions and check the interface
A function file can contain a main function followed by local helper functions. Each ordinary local function has its own workspace, so pass it the information it needs.
Function location | How you use it |
|---|---|
First function in a function file | Call it from the Command Window or another file when MATLAB can find its file. |
Local function after the main function | Call it from functions in the same file. |
Before reusing a function, compare one call with a calculation you can check independently. Confirm the input order, output order, expected units, and file name.
What to remember
- Match the main function name and its .m file name.
- Match input and output values by position.
- Assign requested outputs inside the function and capture them in the caller.
- Pass needed values explicitly between separate function workspaces.
Example: Package a heating calculation
An engineering laboratory estimates the energy needed to warm an aluminium sample. Assume constant specific heat capacity and no heat loss. Use
where m is mass in kg, c is specific heat capacity in J/(kg·K), C is sample heat capacity in J/K, and Q is transferred energy in J. The sample has m=0.750 kg, c=900 J/(kg⋅K), and temperature rise ΔT=18.0 K.
Create a function named thermalEnergy that accepts m, c, and dT in that order and returns Q followed by C.
a) Choose the file name and write the function declaration.
The main function and file should have matching names, so save the function as thermalEnergy.m. The interface needs ________ ordered inputs and ________ ordered outputs:
function [Q,C] = thermalEnergy(m,c,dT)The square brackets identify the two outputs. Their order means that the first receiving variable in a call will get energy in J and the second will get heat capacity in J/K.
b) Write the complete function file, including a comment documenting units.
Compute heat capacity before energy because the energy expression uses the computed value of C. Assign both declared outputs explicitly:
function [Q,C] = thermalEnergy(m,c,dT)
% THERMALENERGY Scalar inputs: m in kg, c in J/(kg K), dT in K.
% Outputs: Q in J and C in J/K.
C = m*c;
Q = C*dT;
endThe unit products agree with the documented outputs:
Semicolons suppress intermediate display. They do not stop Q and C from being returned.
c) The caller executes the following code. Find the final values of energy, capacity, m, and C.
m = 5;
C = -1;
[energy,capacity] = thermalEnergy(0.750,900,18.0);The numerical arguments in the call supply the function's inputs directly. Its local m receives ________, even though the caller has a variable named m containing 5. Inside the function, the calculations give C = 675 and Q = 12150.
The declared output order is [Q,C], so the first receiving variable gets Q and the second gets C:
The caller's m remains 5 and its C remains -1. The function uses a separate workspace, and the receiving list stores its outputs in energy and capacity, rather than in the caller's variables with matching internal names.
An engineer writes the following MATLAB code to calculate a fan blade's tip speed. The inputs are rotational speed in revolutions per minute and radius in metres; the output is speed in metres per second.
function speed = tipSpeed(rpm, radius)
omega = angularSpeed(rpm);
speed = omega * radius;
end
function omega = angularSpeed(rpm)
omega = 2*pi*rpm/60;
endSave the code in the current folder using a filename that matches the first function. No separate file or workspace variable named angularSpeed exists, and no function handles are created.
The complete filename, including its extension, should be . Can you call angularSpeed directly by name from the Command Window? Write yes or no: .
The file springState.m contains the following function. Its inputs are scalar stiffness k in N/m and extension x in m.
function [force,extension] = springState(k,x)
force = k*x;
extension = x;
endAn engineer executes:
[x,F] = springState(300,0.020);What numerical values are stored in the caller's variables x and F?