Wize Engineering Computation Textbook > MATLAB Programming

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


y=f(x1,x2).y = f(x_1,x_2).


The corresponding MATLAB declaration has this structure:


MATLAB
function y = calculation(x1,x2)
    y = x1 + x2;
end


The 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:


MATLAB
function [first,second] = calculation(x1,x2)
    first = x1 + x2;
    second = x1 - x2;
end


Inputs 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:


MATLAB
function P = resistorPower(I,R)
% RESISTORPOWER Power in W for scalar I in A and R in ohms.
    P = I^2*R;
end


For a resistor, the calculation implements


P=I2R.P = I^2R.


A call supplies values rather than repeating the declaration:


MATLAB
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 WP=(2\ \text{A})^2(6\ \Omega)=24\ \text{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.


Input values pass from a caller into a separate function workspace and an output value returns to 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


C=mc,Q=CΔT,C=mc,\qquad Q=C\Delta T,


where mm is mass in kg, cc is specific heat capacity in J/(kg·K), CC is sample heat capacity in J/K, and QQ is transferred energy in J. The sample has m=0.750 kgm=0.750\ \text{kg}, c=900 J/(kg⋅K)c=900\ \text{J/(kg·K)}, and temperature rise ΔT=18.0 K\Delta T=18.0\ \text{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:


MATLAB
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:


MATLAB
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;
end


The unit products agree with the documented outputs:


C=(0.750 kg)(900 J/(kg⋅K))=675 J/K,Q=(675 J/K)(18.0 K)=12150 J.\begin{aligned} C&=(0.750\ \text{kg})(900\ \text{J/(kg}\cdot\text{K)}) =675\ \text{J/K},\\ Q&=(675\ \text{J/K})(18.0\ \text{K}) =12150\ \text{J}. \end{aligned}


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.


MATLAB
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:


energy=12150 J,capacity=675 J/K.\text{energy}=12150\ \text{J},\qquad \text{capacity}=675\ \text{J/K}.


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 is creating meanSpeed.m. Its main function must accept scalar distance d in metres and elapsed time t in seconds, in that order, and return speed v in metres per second. Which declaration specifies this interface?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

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.


MATLAB
function speed = tipSpeed(rpm, radius)
    omega = angularSpeed(rpm);
    speed = omega * radius;
end

function omega = angularSpeed(rpm)
    omega = 2*pi*rpm/60;
end


Save 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: .

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

The file springState.m contains the following function. Its inputs are scalar stiffness k in N/m and extension x in m.


MATLAB
function [force,extension] = springState(k,x)
    force = k*x;
    extension = x;
end


An engineer executes:


MATLAB
[x,F] = springState(300,0.020);


What numerical values are stored in the caller's variables x and F?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice