Scripts and Functions
A function file celsius_to_fahrenheit.m must contain a function with the same name.
Concept
Scripts vs Functions File starts with function [outputs] = name(inputs) Shares the caller's (base) workspace Its own local workspace Arguments and return values Designed for reuse and testing
A function file celsius_to_fahrenheit.m must contain a function with the same name. MATLAB finds it through the current folder and the search path (addpath, path).
Anatomy of a Function Multiple outputs: [a, b] = f(x); ignore some with ~: [~, idx] = max(v).
nargin / nargout: how many inputs/outputs the caller used — for default values and optional work.
Input validation: validateattributes, assert, or (MATLAB R2019b+) an arguments block.
Local functions: extra functions after the main one in the same file, visible only there. In scripts, MATLAB (R2016b+) allows local functions at the *end* of the file; Octave requires them *before* use — so this course keeps helpers in their own files, which works everywhere.
Nested functions share variables with their parent function (MATLAB).
persistent variables keep their value between calls; global variables are shared everywhere (avoid).
Recursion is allowed (default limit 500 levels in MATLAB, max_recursion_depth in Octave).
Function Files Used in This Module
function [out1, out2] = name(in1, in2)
%NAME One-line summary (the H1 line, shown by lookfor).
% Longer help text, shown by "help name".
...
endfunction f = celsius_to_fahrenheit(c)
%CELSIUS_TO_FAHRENHEIT Convert temperatures from degrees Celsius to Fahrenheit.
% F = CELSIUS_TO_FAHRENHEIT(C) works element-wise on arrays.
f = c * 9 / 5 + 32;
endfunction [mn, mx, avg, rmsv] = signal_stats(x)
%SIGNAL_STATS Minimum, maximum, mean and RMS of a signal vector.
mn = min(x);
mx = max(x);
avg = mean(x);
if nargout > 3 % only compute what the caller asked for
rmsv = sqrt(mean(x .^ 2));
end
endfunction y = scale_signal(raw, factor, offset)
%SCALE_SIGNAL physical = raw * factor + offset, with defaults factor = 1, offset = 0.
if nargin < 2 || isempty(factor), factor = 1; end
if nargin < 3, offset = 0; end
validateattributes(raw, {'numeric'}, {'nonnegative'});
y = double(raw) * factor + offset;
endfunction n = count_calls()
%COUNT_CALLS Demonstrates a persistent variable: remembers its value between calls.
persistent calls
if isempty(calls), calls = 0; end
calls = calls + 1;
n = calls;
endfunction r = factorial_rec(n)
%FACTORIAL_REC Recursive factorial (for teaching; use factorial(n) in real code).
if n <= 1
r = 1;
else
r = n * factorial_rec(n - 1);
end
endWhy It Matters
Functions turn one-off scripts into tested, reusable tools — the difference between a calculation and a maintainable engineering toolkit.
Syntax
function y = f(x) % one output
function [m, s] = stats(x) % two outputs
function varargout = g(varargin) % variable numbers of arguments
if nargin < 2, factor = 1; end % default valueExample
11.1 Calling functions with one or several outputs, defaults, persistent state, recursion and help
fprintf('25 C = %g F\n', celsius_to_fahrenheit(25))
fprintf('vector input: %s\n', mat2str(celsius_to_fahrenheit([-40 0 100])))
x = [12.4 12.6 11.9 12.5];
[lo, hi] = signal_stats(x); % ask for two outputs only
fprintf('min %.1f, max %.1f\n', lo, hi)
[lo, hi, avg, r] = signal_stats(x);
fprintf('mean %.3f, rms %.4f\n', avg, r)
[~, ~, avg] = signal_stats(x); % ~ ignores outputs
fprintf('mean only: %.3f\n', avg)
fprintf('scale_signal(8000, 0.125) = %g, with offset -40: %g, defaults: %g\n', ...
scale_signal(8000, 0.125), scale_signal(130, 1, -40), scale_signal(7))
for k = 1:3, n = count_calls(); end
fprintf('count_calls was called %d times (persistent variable)\n', n)
fprintf('factorial_rec(6) = %d\n', factorial_rec(6))
help celsius_to_fahrenheitExpected Result
signal_stats computed the RMS only when a fourth output was requested (nargout > 3). help printed the comment block of the function file — that is why the first comment line matters. (Octave appends a few lines of its own boilerplate about where the function is defined; MATLAB prints only the comment block.)
25 C = 77 F
vector input: [-40 32 212]
min 11.9, max 12.6
mean 12.350, rms 12.3529
mean only: 12.350
scale_signal(8000, 0.125) = 1000, with offset -40: 90, defaults: 7
count_calls was called 3 times (persistent variable)
factorial_rec(6) = 720
'celsius_to_fahrenheit' is a function from the file celsius_to_fahrenheit.m
CELSIUS_TO_FAHRENHEIT Convert temperatures from degrees Celsius to Fahrenheit.
F = CELSIUS_TO_FAHRENHEIT(C) works element-wise on arrays.
Additional help for built-in functions and operators is
available in the online version of the manual. Use the command
'doc <topic>' to search the manual index.
Help and information about Octave is also available on the WWW
at https://www.octave.org and https://octave.discourse.group/c/help/Common Mistakes
File name and function name differ (MATLAB uses the file name).
Expecting a function to see variables from the script that called it (it can't; pass them as arguments).
Forgetting to assign an output variable on every path ("Output argument not assigned").
Overusing global variables.
Best Practices
One public function per file, with an H1 help line and documented inputs/outputs.
Validate inputs at the top; fail early with clear messages.
Keep functions small and side-effect free; return results instead of printing them.
Interview Relevance
High: "script vs function?", "how do you return multiple values?", "what are nargin/nargout?", "what is a persistent variable?", "local vs nested function?".
Practice Questions
Write area = circle_area(r) that works for a vector of radii.
Write [q, r] = divmod(a, b) returning the quotient and remainder.
Add a default tolerance of 1e-6 to a function with nargin.
Write a recursive function for the n-th Fibonacci number and compare its speed with a loop.
Quick Quiz
Q1. (Multiple choice) Which variable tells a function how many inputs were passed? A) nargout B) nargin C) numel D) varargin Answer: B.
Q2. (Predict the output) [~, ~, avg] = signal_stats([12.4 12.6 11.9 12.5]) — what is avg?
Answer: 12.350 (verified).
Q3. (True/False) A function can read the variables of the script that called it.
Answer: False. Functions have their own workspace.
Q4. (Find the bug) File convert.m contains function y = toFahrenheit(c), and toFahrenheit(20) fails.
Answer: MATLAB looks functions up by file name; call convert(20) or rename the file to toFahrenheit.m.
Coding Challenge
Write a function file [area, perimeter] = rect_props(w, h) that works element-wise on arrays and returns both values, then call it from a script for widths [2 3] and heights [4 5].
% rect_props.m
function [area, perimeter] = rect_props(w, h)
%RECT_PROPS Area and perimeter of rectangles (element-wise).
area = w .* h;
perimeter = 2 * (w + h);
end% script
[a, p] = rect_props([2 3], [4 5]);
fprintf('areas %s, perimeters %s\n', mat2str(a), mat2str(p))