Function arguments in MATLAB are essential components that allow data to be passed into and out of functions. They enable flexible and reusable code by parameterizing function behavior.
Input arguments are variables that a function receives when it is called. They provide the necessary data for the function to perform its operations.
function [output1, output2] = functionName(input1, input2, input3)
% Function body
end
In this syntax, input1
, input2
, and input3
are the input arguments.
function result = addNumbers(a, b)
result = a + b;
end
sum = addNumbers(5, 3); % sum will be 8
Output arguments are the values that a function returns after execution. They allow functions to provide results back to the calling code.
MATLAB functions can return multiple output arguments, which is particularly useful for complex operations.
function [sum, difference] = mathOperations(a, b)
sum = a + b;
difference = a - b;
end
[s, d] = mathOperations(10, 7); % s will be 17, d will be 3
MATLAB allows for optional function arguments, providing default values when an argument is not specified.
function result = powerOf(base, exponent)
if nargin < 2
exponent = 2; % Default exponent is 2 if not provided
end
result = base ^ exponent;
end
square = powerOf(5); % Returns 25 (5^2)
cube = powerOf(5, 3); % Returns 125 (5^3)
The nargin
function is used to check the number of input arguments provided.
For functions that need to handle a varying number of inputs, MATLAB provides the varargin
cell array.
function result = sumAll(varargin)
result = sum([varargin{:}]);
end
total = sumAll(1, 2, 3, 4, 5); % Returns 15
inputParser
for complex input validation in larger functions.To further enhance your understanding of MATLAB functions and their arguments, explore these related topics:
Mastering function arguments in MATLAB is crucial for writing efficient, reusable, and maintainable code. Practice creating functions with various argument configurations to solidify your understanding.