MATLAB - Function Arguments
MATLAB - Modern Function Arguments
Section titled “MATLAB - Modern Function Arguments”Functions are the building blocks of robust and reusable code. They receive data through input arguments and return results through output arguments. Modern MATLAB offers powerful and flexible ways to define and validate these arguments, making your code more reliable, easier to use, and self-documenting.
The Anatomy of a MATLAB Function
Section titled “The Anatomy of a MATLAB Function”Let’s start with the basic syntax:
function [output1, output2] = functionName(input1, input2) % Help text for the function (what it does, inputs, outputs) % This text is displayed when you type 'help functionName'
% Function body: Perform calculations using inputs output1 = input1 * 2; output2 = input2 + 5;endfunction: Keyword that begins a function definition.[output1, output2]: A comma-separated list of output arguments in square brackets.functionName: The name of your function. This must match the filename (e.g.,functionName.m).(input1, input2): A comma-separated list of required input arguments.end: Keyword that terminates the function.
The Modern Approach: The arguments Block
Section titled “The Modern Approach: The arguments Block”Introduced in R2019b, the arguments block is the recommended best practice for defining function inputs. It allows you to declare argument names, specify their size and class, set default values, and add custom validation rules, all in one clear, declarative block.
Syntax
Section titled “Syntax”function result = functionName(posArg1, posArg2) arguments posArg1 (1,1) double {mustBeNumeric} % Positional argument posArg2 (1,:) char {mustBeMember(posArg2, ['A','B'])}
% Name-Value arguments options.PlotStyle (1,1) string = "-" options.LineWidth (1,1) double {mustBePositive} = 1 end % ... function body ...endLet’s break down this syntax:
(1,1) double: A validation thatposArg1must be a 1x1 scalar of typedouble.{mustBeNumeric}: A validation function. MATLAB provides many (e.g.,mustBePositive,mustBeInteger), or you can write your own.options.PlotStyle (1,1) string = "-": This defines an optional Name-Value argument. If the user doesn’t provide aPlotStyle, it defaults to"-".
Practical Example: Advanced Data Plotting Function
Section titled “Practical Example: Advanced Data Plotting Function”Let’s create a robust function plotData.m that plots a vector y against an optional vector x. It will also accept Name-Value pairs to customize the plot.
function plotHandle = plotData(y, x, options)% PLOTDATA Plots a vector y with extensive customization options.% plotHandle = PLOTDATA(y) plots the data in y.% plotHandle = PLOTDATA(y, x) plots y versus x.% plotHandle = PLOTDATA(___, Name, Value) specifies plot options% using one or more Name, Value pair arguments.
arguments % Positional Arguments y (1,:) double {mustBeReal, mustBeFinite} % y is a required 1xN vector x (1,:) double {mustBeReal, mustBeFinite} = 1:length(y) % x is optional, defaults to 1, 2, 3...
% Name-Value Arguments in an 'options' struct options.LineColor (1,1) string = "blue" % Plot color options.LineWidth (1,1) double {mustBePositive} = 1.5 % Line thickness options.Marker (1,1) string = "o" % Marker style options.TitleText (1,1) string = "My Data Plot" % Plot title end
% Input validation: Ensure x and y have the same number of elements if length(x) ~= length(y) error('Inputs x and y must have the same number of elements.'); end
% --- Function Body --- figure; % Create a new figure window plotHandle = plot(x, y, ... 'Color', options.LineColor, ... 'LineWidth', options.LineWidth, ... 'Marker', options.Marker, ... 'LineStyle', '-');
grid on; title(options.TitleText); xlabel('X-axis'); ylabel('Y-axis'); legend('Data Series');
endCalling the Function
Section titled “Calling the Function”Now you can call this function in various ways from the Command Window:
% Generate some sample datasampleData = [10 15 13 18 20];
% 1. Simple call (x is defaulted)plotData(sampleData);
% 2. Provide custom x-axis valuestimeStamps = [0 0.1 0.2 0.3 0.4];plotData(sampleData, timeStamps);
% 3. Full customization with Name-Value pairsplotData(sampleData, timeStamps, LineColor="red", TitleText="Sensor Readings", LineWidth=2);Legacy Approach: varargin and nargin
Section titled “Legacy Approach: varargin and nargin”Before the arguments block, handling optional and Name-Value arguments required manually parsing varargin (a cell array of variable input arguments) and checking nargin (number of input arguments). While you will still see this in older code, the arguments block is superior for new code as it is less error-prone and more readable.