| MATLAB® | ![]() |
| On this page… |
|---|
Passing Certain Argument Types Passing Arguments in Structures or Cell Arrays Checking the Number of Input Arguments Passing Variable Numbers of Arguments Parsing Inputs with inputParser |
When calling a function, the caller provides the function with any data it needs by passing the data in an argument list. Data that needs to be returned to the caller is passed back in a list of return values.
Semantically speaking, the MATLAB® software always passes argument data by value. (Internally, MATLAB optimizes away any unnecessary copy operations.)
If you pass data to a function that then modifies this data, you will need to update your own copy of the data. You can do this by having the function return the updated value as an output argument.
This section explains how to pass the following types of data in a function call:
When using the function syntax to pass a string literal to a function, you must enclose the string in single quotes, ('string'). For example, to create a new directory called myapptests, use
mkdir('myapptests')
On the other hand, variables that contain strings do not need to be enclosed in quotes:
dirname = 'myapptests'; mkdir(dirname)
You can specify a filename argument using the MATLAB command or function syntax. For example, either of the following are acceptable. (The .mat file extension is optional for save and load):
load mydata.mat % Command syntax
load('mydata.mat') % Function syntax
If you assign the output to a variable, you must use the function syntax:
savedData = load('mydata.mat')
Specify ASCII files as shown here. In this case, the file extension is required:
load mydata.dat -ascii % Command syntax
load('mydata.dat','-ascii') % Function syntaxDetermining Filenames at Run-Time. There are several ways that your function code can work on specific files without your having to hardcode their filenames into the program. You can
Pass the filename as an argument:
function myfun(datafile)
Prompt for the filename using the input function:
filename = input('Enter name of file: ', 's');
Browse for the file using the uigetfile function:
[filename, pathname] = uigetfile('*.mat', 'Select MAT-file');The MATLAB function handle has several uses, the most common being a means of immediate access to the function it represents. You can pass function handles in argument lists to other functions, enabling the receiving function to make calls by means of the handle.
To pass a function handle, include its variable name in the argument list of the call:
fhandle = @humps; x = fminbnd(fhandle, 0.3, 1);
The receiving function invokes the function being passed using the usual MATLAB calling syntax:
function [xf, fval, exitflag, output] = ...
fminbnd(fhandle, ax, bx, options, varargin)
.
.
.
113 fx = fhandle(x, varargin{:});Instead of requiring an additional argument for every value you want to pass in a function call, you can package them in a MATLAB structure or cell array.
Make each input you want to pass a separate field in the structure argument, using descriptive names for the fields. Structures allow you to change the number, contents, or order of the arguments without having to modify the function. They can also be useful when you have a number of functions that need similar information.
This example updates weather statistics from information in the following chart.
City | Temp. | Heat Index | Wind Speed | Wind Chill |
|---|---|---|---|---|
Boston | 43 | 32 | 8 | 37 |
Chicago | 34 | 27 | 3 | 30 |
Lincoln | 25 | 17 | 11 | 16 |
Denver | 15 | -5 | 9 | 0 |
Las Vegas | 31 | 22 | 4 | 35 |
San Francisco | 52 | 47 | 18 | 42 |
The information is stored in structure W. The structure has one field for each column of data:
W = struct('city', {'Bos','Chi','Lin','Dnv','Vgs','SFr'}, ...
'temp', {43, 34, 25, 15, 31, 52}, ...
'heatix', {32, 27, 17, -5, 22, 47}, ...
'wspeed', {8, 3, 11, 9, 4, 18}, ...
'wchill', {37, 30, 16, 0, 35, 42});To update the data base, you can pass the entire structure, or just one field with its associated data. In the call shown here, W.wchill is a comma-separated list:
updateStats(W.wchill);
You can also group arguments into cell arrays. The advantage over structures is that cell arrays are referenced by index, allowing you to loop through a cell array and access each argument passed in or out of the function. The disadvantage is that you don't have field names to describe each variable.
This example passes several attribute-value arguments to the plot function:
X = -pi:pi/10:pi;
Y = tan(sin(X)) - sin(tan(X));
C{1,1} = 'LineWidth'; C{2,1} = 2;
C{1,2} = 'MarkerEdgeColor'; C{2,2} = 'k';
C{1,3} = 'MarkerFaceColor'; C{2,3} = 'g';
plot(X, Y, '--rs', C{:})Use the syntax shown here to store any values that are returned by the function you are calling. To store one output, put the variable that is to hold that output to the left of the equal sign:
vout = myfun(vin1, vin2, ...);
To store more than one output, list the output variables inside square brackets and separate them with commas or spaces:
[vout1 vout2 ...] = myfun(vin1, vin2, ...);
The number of output variables in your function call statement does not have to match the number of return values declared in the function being called. For a function that declares N return values, you can specify anywhere from zero to N output variables in the call statement. Any return values that you do not have an output variable for are discarded.
Functions return output values in the order in which the corresponding output variables appear in the function definition line within the M-file. This function returns 100 first, then x * y, and lastly x.^2:
function [a b c] = myfun(x, y) b = x * y; a = 100; c = x.^2;
If called with only one output variable in the call statement, the function returns only 100 and discards the values of b and c. If called with no outputs, the functions returns 100 in the MATLAB default variable ans.
The section Passing Variable Numbers of Arguments describes the method of returning optional outputs in a cell array called varargout. A function that uses varargout to return optional values has a function definition line that looks like one of the following:
function varargout = myfun(vin1, vin2, ...) function [vout1 vout2 ... varargout] = myfun(vin1, vin2, ...)
The code within the function builds the varargout cell array. The content and order of elements in the cell array determines how MATLAB assigns optional return values to output variables in the function call.
In the case where varargout is the only variable shown to the left of the equal sign in the function definition line, MATLAB assigns varargout{1} to the first output variable, varargout{2} to the second, and so on. If there are other outputs declared in the function definition line, then MATLAB assigns those outputs to the leftmost output variables in the call statement, and then assigns outputs taken from the varargout array to the remaining output variables in the order just described.
This function builds the varargout array using descending rows of a 5-by-5 matrix. The function is capable of returning up to six outputs:
function varargout = byRow(a)
varargout{1} = ' With VARARGOUT constructed by row ...';
for k = 1:5
row = 5 - (k-1); % Reverse row order
varargout{k+1} = a(row,:);
endCall the function, assigning outputs to four variables. MATLAB returns varargout{1:4}, with rows of the matrix in varargout{2:4} and in the order in which they were stored by the function:
[text r1 r2 r3] = byRow(magic(5))
text =
With VARARGOUT constructed by row ...
r1 =
11 18 25 2 9
r2 =
10 12 19 21 3
r3 =
4 6 13 20 22A similar function builds the varargout array using diagonals of a 5-by-5 matrix:
function varargout = byDiag(a)
varargout{1} = ' With VARARGOUT constructed by diagonal ...';
for k = -4:4
varargout{k + 6} = diag(a, k);
endCall the function with five output variables. Again, MATLAB assigns elements of varargout according to the manner in which it was constructed within the function:
[text d1 d2 d3 d4] = byDiag(magic(5))
text =
With VARARGOUT constructed by diagonal ...
d1 =
11
d2 =
10
18
d3 =
4
12
25
d4 =
23
6
19
2The nargin and nargout functions enable you to determine how many input and output arguments a function is called with. You can then use conditional statements to perform different tasks depending on the number of arguments. For example,
function c = testarg1(a, b)
if (nargin == 1)
c = a .^ 2;
elseif (nargin == 2)
c = a + b;
end
Given a single input argument, this function squares the input value. Given two inputs, it adds them together.
Here is a more advanced example that finds the first token in a character string. A token is a set of characters delimited by white space or some other character. Given one input, the function assumes a default delimiter of white space; given two, it lets you specify another delimiter if desired. It also allows for two possible output argument lists:
function [token, remainder] = strtok(string, delimiters)
% Function requires at least one input argument
if nargin < 1
error('Not enough input arguments.');
end
token = []; remainder = [];
len = length(string);
if len == 0
return
end
% If one input, use white space delimiter
if (nargin == 1)
delimiters = [9:13 32]; % White space characters
end
i = 1;
% Determine where nondelimiter characters begin
while (any(string(i) == delimiters))
i = i + 1;
if (i > len), return, end
end
% Find where token ends
start = i;
while (~any(string(i) == delimiters))
i = i + 1;
if (i > len), break, end
end
finish = i - 1;
token = string(start:finish);
% For two output arguments, count characters after
% first delimiter (remainder)
if (nargout == 2)
remainder = string(finish+1:end);
end
The strtok function is a MATLAB M-file in the strfun directory.
The varargin and varargout functions let you pass any number of inputs or return any number of outputs to a function. This section describes how to use these functions and also covers
MATLAB packs all specified input arguments into a cell array, a special kind of MATLAB array that consists of cells instead of array elements. Each cell can hold any size or kind of data — one might hold a vector of numeric data, another in the same array might hold an array of string data, and so on. For output arguments, your function code must pack them into a cell array so that MATLAB can return the arguments to the caller.
Here is an example function that accepts any number of two-element vectors and draws a line to connect them:
function testvar(varargin)
for k = 1:length(varargin)
x(k) = varargin{k}(1); % Cell array indexing
y(k) = varargin{k}(2);
end
xmin = min(0,min(x));
ymin = min(0,min(y));
axis([xmin fix(max(x))+3 ymin fix(max(y))+3])
plot(x,y)
Coded this way, the testvar function works with various input lists; for example,
testvar([2 3],[1 5],[4 8],[6 5],[4 2],[2 3]) testvar([-1 0],[3 -5],[4 2],[1 1])
Because varargin contains all the input arguments in a cell array, it's necessary to use cell array indexing to extract the data. For example,
y(n) = varargin{n}(2);
Cell array indexing has two subscript components:
The indices within curly braces {} specify which cell to get the contents of.
The indices within parentheses () specify a particular element of that cell.
In the preceding code, the indexing expression {i} accesses the nth cell of varargin. The expression (2) represents the second element of the cell contents.
When allowing a variable number of output arguments, you must pack all of the output into the varargout cell array. Use nargout to determine how many output arguments the function is called with. For example, this code accepts a two-column input array, where the first column represents a set of x coordinates and the second represents y coordinates. It breaks the array into separate [xi yi] vectors that you can pass into the testvar function shown at the beginning of the section on Passing Variable Numbers of Arguments:
function [varargout] = testvar2(arrayin)
for k = 1:nargout
varargout{k} = arrayin(k,:); % Cell array assignment
end
The assignment statement inside the for loop uses cell array assignment syntax. The left side of the statement, the cell array, is indexed using curly braces to indicate that the data goes inside a cell. For complete information on cell array assignment, see Cell Arrays.
To call testvar2, type
a = [1 2; 3 4; 5 6; 7 8; 9 0];
[p1, p2, p3, p4, p5] = testvar2(a)
p1 =
1 2
p2 =
3 4
p3 =
5 6
p4 =
7 8
p5 =
9 0
varargin or varargout must appear last in the argument list, following any required input or output variables. That is, the function call must specify the required arguments first. For example, these function declaration lines show the correct placement of varargin and varargout:
function [out1,out2] = example1(a,b,varargin) function [i,j,varargout] = example2(x1,y1,x2,y2,flag)
MATLAB provides a class called inputParser to handle the different types of arguments passed into an M-file function. Using inputParser, you create a schema that both represents and verifies the content of the entire list of input arguments passed on a call to the function. When used in all of your code development, this schema offers a consistent and thorough means of managing and validating the input information.
This section covers the following topics
To illustrate how to use the inputParser class, the documentation in this section develops a new M-file program called publish_ip, (based on the MATLAB publish function). There are three calling syntaxes for this function:
publish_ip('scriptfile')
publish_ip('scriptfile', 'format')
publish_ip('scriptfile', options)There is one required argument (scriptfile), one optional argument (format), and a number of optional arguments that are specified as parameter-value pairs (options).
Most programs have a block of code toward the beginning that parses the values in the input argument list and checks these values against what is expected. The inputParser class provides the following methods with which you can specify what the inputs are and whether they are required, optional, or to be specified using the parameter-value syntax:
addRequired — Add a required parameter to the schema
addOptional — Add an optional parameter to the schema
addParamValue — Add an optional parameter-value pair to the schema
Creating the inputParser Object. Call the class constructor for inputParser to create an instance of the class. This class instance, or object, gives you access to all of the methods and properties of the class.
Begin writing the example publish_ip M-file by entering the following two statements:
function x = publish_ip(scriptfile, varargin) p = inputParser; % Create an instance of the class.
After calling the constructor, use the addRequired, addOptional, and addParamValue methods to add arguments to the schema.
Note The constructor and all methods and properties of the inputParser class are case sensitive. |
Adding Arguments to the Schema. Add any required arguments to the schema using the addRequired method. This method takes two inputs: the name of the required parameter, and an optional handle to a function that validates the parameter:
addRequired(name, validator);
Put an addRequired statement at the end of your publish_ip code. The two arguments for addRequired in this case are a parameter name script to represent the filename input, and a handle to a function that will validate the filename, ischar. After adding the addRequired statement, your publish_ip function should now look like this:
function x = publish_ip(scriptfile, varargin)
p = inputParser; % Create an instance of the class.
p.addRequired('script', @ischar);Use the addOptional method to add any arguments that are not required. The syntax for addOptional is similar to that of addRequired except that you also need to specify a default value to be used whenever the optional argument is not passed:
addOptional(name, default, validator);
In this case, the validator input is a handle to an anonymous function:
p.addOptional('format', 'html', ...
@(x)any(strcmpi(x,{'html','ppt','xml','latex'})));Use addParamValue to specify any arguments that use a parameter-value format. The syntax is
addParamValue(name, default, validator);
For example,
p.addParamValue('outputDir', pwd, @ischar);
p.addParamValue('maxHeight', [], @(x)x>0 && mod(x,1)==0);
p.addParamValue('maxWidth', [], @(x)x>0 && mod(x,1)==0);
Listing the Parameters. At this point, the schema is complete. Here is the file publish_ip.m:
function x = publish_ip(scriptfile, varargin)
p = inputParser; % Create an instance of the class.
p.addRequired('script', @ischar);
p.addOptional('format', 'html', ...
@(x)any(strcmpi(x,{'html','ppt','xml','latex'})));p.
p.addParamValue('outputDir', pwd, @ischar);
p.addParamValue('maxHeight', [], @(x)x>0 && mod(x,1)==0);
p.addParamValue('maxWidth', [], @(x)x>0 && mod(x,1)==0);
When you call the program, MATLAB stores the name of each argument in the Parameters property of object p. Add the following two lines to your publish_ip M-file to display p.Parameters:
sprintf('%s\n %s\n %s\n %s\n %s\n %s', ...
'The input parameters for this program are:', ...
p.Parameters{:})
Save the M-file, and then run it as shown here:
publish_ip('ipscript.m', 'ppt', 'outputDir', ...
'C:/matlab/test', 'maxWidth', 500, 'maxHeight', 300);
The output is
The input parameters for this program are: format maxHeight maxWidth outputDir script
Once you have constructed a schema that represents all possible inputs to the function, the next task is to write the code that parses and verifies these arguments whenever the function is called. The parse method of the inputParser class reads and validates the required scriptfile argument and any optional arguments that follow it in the argument list:
p.parse(scriptfile, varargin{:});Execution of the parse method validates each argument and also builds a structure from the input arguments. The name of the structure is Results, which is accessible as a property of the object. To get the value of all arguments, type
p.Results
To get the value of any single input argument, type
p.Results.argname
where argname is the name of the argument. Continue with the publish_ip exercise started earlier in this section by removing the sprintf statement that was inserted in the last section, and then adding the following lines:
% Parse and validate all input arguments.
p.parse(scriptfile, varargin{:});
% Display the value of a specific argument.
disp(' ')
disp(sprintf('\nThe maximum height is %d.', ...
p.Results.maxHeight))
% Display all arguments.
disp(' ')
disp 'List of all arguments:'
disp(p.Results)Now save and execute the M-file, passing the required script file argument, the optional format argument, as well as several parameter-value arguments. MATLAB assigns those values you pass in the argument list to the appropriate fields of the Results structure:
publish_ip('ipscript.m', 'ppt', 'outputDir', ...
'C:/matlab/test', 'maxWidth', 500, 'maxHeight', 300);
The maximum height is 300.
List of all arguments:
format: 'ppt'
maxHeight: 300
maxWidth: 500
outputDir: 'C:/matlab/test'
script: 'ipscript.m'
By setting the StructExpand property of the inputParser object to true, you can pass arguments to your function in the form of a structure instead of individually in the argument list. This property must be set prior to calling the parse method.
StructExpand defaults to the true state, so you don't have to make any changes to your test program to run this example.
Put all of the input arguments into a structure:
s.format = 'xml'; s.outputDir = 'C:/matlab/test'; s.maxWidth = 200; s.maxHeight = 150;
Now call the function, passing the filename and input structure:
publish_ip('ipscript.m', s);
The maximum height is 150.
List of all arguments:
format: 'xml'
maxHeight: 150
maxWidth: 200
outputDir: 'C:/matlab/test'
script: 'ipscript.m'
To disable struct expansion, include the following statement somewhere in your program code before the p.parse statement:
p.StructExpand = false;
Overriding the Input Structure. If you want to pass your argument list in a structure, as described in the previous section, but you also want to alter the value of one or more of these arguments without having to modify the structure, you can do so by passing both the structure and the modified argument:
publish_ip('ipscript.m', s, ...
'outputDir', 'C:/matlab/R2007a/temp');
List of all arguments:
format: 'xml'
maxHeight: 150
maxWidth: 200
outputDir: 'C:/matlab/R2007a/temp'
script: 'ipscript.m'
Any arguments that you do not include in a call to your function are given their default values by MATLAB. You defined these default values when you created your schema using the addOptional and addParamValue methods. The UsingDefaults property is actually a structure that contains the names of any arguments that were not passed in the function call, and thus were assigned default values.
Add the following to your M-file:
% Show which arguments were not specified in the call.
disp(' ')
disp 'List of arguments given default values:'
for k=1:numel(p.UsingDefaults)
field = char(p.UsingDefaults(k));
value = p.Results.(field);
if isempty(value), value = '[]'; end
disp(sprintf(' ''%s'' defaults to %s', field, value))
end
Save the M-file and run it without specifying the format, outputDir, or maxHeight arguments:
publish_ip('ipscript.m', 'maxWidth', 500);
List of arguments given default values:
'format' defaults to html
'outputDir' defaults to D:\work_r14
'maxHeight' defaults to []
When you call your function, MATLAB checks any arguments for which you have specified a validator function. If the validator finds an error, MATLAB displays an error message and aborts the function. In the publish function example, the outputDir argument validates the value passed in using @ischar.
Pass a number instead of a string for the outputDir argument:
publish_ip('ipscript.m', 'outputDir', 5);
??? Argument 'outputDir' failed validation ischar.
Error in ==> publish_ip at 14
p.parse(varargin{:});Handling Unmatched Arguments. MATLAB throws an error if you call your function with any arguments that are not part of the inputParser schema. You can disable this error by setting the KeepUnmatched property to true. When KeepUnmatched is in the true state, MATLAB does not throw an error, but instead stores any arguments that are not in the schema in a cell array of strings accessible through the Unmatched property of the object. KeepUnmatched defaults to false.
At some point in your publish_ip M-file before executing the parse method, set the KeepUnmatched property to true, and following the parse statement, examine the Unmatched property:
p.KeepUnmatched = true;
% Parse and validate all input arguments.
p.parse(scriptfile, varargin{:});
disp(' ')
disp 'List of unmatched arguments:'
p.Unmatched
Save and run the function, passing two arguments that are not defined in the schema:
publish_ip('ipscript.m', s, ...
'outputDir', 'C:/matlab/R2007a/temp', ...
'colorSpace', 'CMYK', 'density', 200);
List of unmatched arguments:
colorSpace: 'CMYK'
density: 200Enabling Case-Sensitive Matching. When you pass optional arguments in the function call, MATLAB compares these arguments with the names of parameter-value argument names in the schema. By default, MATLAB does not use case sensitivity in this comparison. So, an argument name entered into the schema (using addParamValue) as maxHeight will match an argument passed as MAXHeight in the function call. You can override the default and make these comparisons case sensitive by setting the CaseSensitive property of the object to true. MATLAB does not error on a case mismatch, however, unless the KeepUnmatched property is set to false: its default state.
At some point in your publish_ip M-file before executing the parse method, set KeepUnmatched to false and CaseSensitive to true, and then execute the publish_ip function using MAXHeight as the name of the argument for specifying maximum height:
p.KeepUnmatched = false;
p.CaseSensitive = true;
% Parse and validate all input arguments.
p.parse(scriptfile, varargin{:});
Save and run the function, using MAXHeight as the name of the argument for specifying maximum height:
publish_ip('ipscript.m', 'ppt', 'outputDir', ...
'C:/matlab/test', 'maxWidth', 500, 'MAXHeight', 300);
??? Argument 'MAXHeight' did not match any valid parameter of
the parser.
Error in ==> publish_ip at 17Adding the Function Name to Error Messages. Use the FunctionName property to include the name of your function in error messages thrown by the validating function:
At some point in your publish_ip M-file before executing the parse method, set the FunctionName property to PUBLISH_IP, and then run the function:
p.FunctionName = 'PUBLISH_IP';
% Parse and validate all input arguments.
p.parse(scriptfile, varargin{:});
Save and run the function and observe text of the error message:
publish_ip('ipscript.m', 'ppt', 'outputDir', 5, ...
'maxWidth', 500, 'maxHeight', 300);
??? Argument 'outputDir' failed validation ischar in PUBLISH_IP.The createCopy method enables you to make a copy of an existing schema. Because the inputParser class uses handle semantics, you cannot make a copy of the object using an assignment statement.
The following statement creates an inputParser object s that is a copy of p:
s = p.createCopy
| Method | Description |
|---|---|
| addOptional | Add an optional argument to the schema |
| addParamValue | Add a parameter-value pair argument to the schema |
| addRequired | Add a required argument to the schema |
| createCopy | Create a copy of the inputParser object |
| parse | Parse and validate the named inputs |
| Property | Description |
|---|---|
| CaseSensitivity | Enable or disable case-sensitive matching of argument names. Defaults to false. |
| FunctionName | Function name to be included in error messages. Defaults to an empty string. |
| KeepUnmatched | Enable or disable errors on unmatched arguments. Defaults to false. |
| StructExpand | Enable or disable passing arguments in a structure. Defaults to true. |
| Property | Description |
|---|---|
| Parameters | Names of arguments defined in inputParser schema. |
| Results | Names and values of arguments passed in function call that are in the schema for this function. |
| Unmatched | Names and values of arguments passed in function call that are not in the schema for this function. |
| UsingDefaults | Names of arguments not passed in function call that are given default values. |
You can use optional input and output arguments with nested functions, but you should be aware of how MATLAB interprets varargin, varargout, nargin, and nargout under those circumstances.
varargin and varargout are variables and, as such, they follow exactly the same scoping rules as any other MATLAB variable. Because nested functions share the workspaces of all outer functions, varargin and varargout used in a nested function can refer to optional arguments passed to or from the nested function, or passed to or from one of its outer functions.
nargin and nargout, on the other hand, are functions and when called within a nested function, always return the number of arguments passed to or from the nested function itself.
varargin or varargout used in a nested function can refer to optional arguments passed to or from that function, or to optional arguments passed to or from an outer function.
If a nested function includes varargin or varargout in its function declaration line, then the use of varargin or varargout within that function returns optional arguments passed to or from that function.
If varargin or varargout are not in the nested function declaration but are in the declaration of an outer function, then the use of varargin or varargout within the nested function returns optional arguments passed to the outer function.
In the example below, function C is nested within function B, and function B is nested within function A. The term varargin{1} in function B refers to the second input passed to the primary function A, while varargin{1} in function C refers to the first argument, z, passed from function B:
function x = A(y, varargin) % Primary function A
B(nargin, y * rand(4))
function B(argsIn, z) % Nested function B
if argsIn >= 2
C(z, varargin{1}, 4.512, 1.729)
end
function C(varargin) % Nested function C
if nargin >= 2
x = varargin{1}
end
end % End nested function C
end % End nested function B
end % End primary function A
When nargin or nargout appears in a nested function, it refers to the number of inputs or outputs passed to that particular function, regardless of whether or not it is nested.
In the example shown above, nargin in function A is the number of inputs passed to A, and nargin in function C is the number of inputs passed to C. If a nested function needs the value of nargin or nargout from an outer function, you can pass this value in as a separate argument, as done in function B.
This example references the primary function's varargin cell array from each of two nested functions. (Because the workspace of an outer function is shared with all functions nested within it, there is no need to pass varargin to the nested functions.)
Both nested functions make use of the nargin value that applies to the primary function. Calling nargin from the nested function would return the number of inputs passed to that nested function, and not those that had been passed to the primary. For this reason, the primary function must pass its nargin value to the nested functions.
function meters = convert2meters(miles, varargin)
% Converts MILES (plus optional FEET and INCHES input)
% values to METERS.
if nargin < 1 || nargin > 3
error('1 to 3 input arguments are required');
end
function feet = convert2Feet(argsIn)
% Nested function that converts miles to feet and adds in
% optional FEET argument.
feet = miles .* 5280;
if argsIn >= 2
feet = feet + varargin{1};
end
end % End nested function convert2Feet
function inches = convert2Inches(argsIn)
% Nested function that converts feet to inches and adds in
% optional INCHES argument.
inches = feet .* 12;
if argsIn == 3
inches = inches + varargin{2};
end
end % End nested function convert2Inches
feet = convert2Feet(nargin);
inches = convert2Inches(nargin);
meters = inches .* 2.54 ./ 100;
end % End primary function convert2meters
convert2meters(5) ans = 8.0467e+003
convert2meters(5, 2000, 4.7) ans = 8.6564e+003
If you pass any input variables that the function can modify, you will need to include the same variables as output arguments so that the caller receives the updated value.
For example, if the function readText, shown below, reads one line of a file each time is it called, then it must keep track of the offset into the file. But when readText terminates, its copy of the offset variable is cleared from memory. To keep the offset value from being lost, readText must return this value to the caller:
function [text, offset] = readText(filestart, offset)
![]() | Calling Functions | Types of Functions | ![]() |
| © 1984-2008- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |