Next: , Previous: , Up: Functions and Scripts   [Contents][Index]


11.7 Ignoring Arguments

In the formal argument list, it is possible to use the dummy placeholder ~ instead of a name. This indicates that the corresponding argument value should be ignored and not stored to any variable.

function val = pick2nd (~, arg2)
  val = arg2;
endfunction

The value of nargin is not affected by using this declaration.

Return arguments can also be ignored using the same syntax. For example, the sort function returns both the sorted values, and an index vector for the original input which will result in a sorted output. Ignoring the second output is simple—don’t request more than one output. But ignoring the first, and calculating just the second output, requires the use of the ~ placeholder.

x = [2, 3, 1];
[s, i] = sort (x)
⇒
s =

   1   2   3

i =

   3   1   2

[~, i] = sort (x)
⇒
i =

   3   1   2

When using the ~ placeholder, commas—not whitespace—must be used to separate output arguments. Otherwise, the interpreter will view ~ as the logical not operator.

[~ i] = sort (x)
parse error:

  invalid left hand side of assignment

Functions may take advantage of ignored outputs to reduce the number of calculations performed. To do so, use the isargout function to query whether the output argument is wanted. For example:

function [out1, out2] = long_function (x, y, z)
  if (isargout (1))
    ## Long calculation
    …
    out1 = result;
  endif
  …
endfunction
: tf = isargout (k)

Within a function, return a logical value indicating whether the argument k will be assigned to a variable on output.

If the result is false, the argument has been ignored during the function call through the use of the tilde (~) special output argument. Functions can use isargout to avoid performing unnecessary calculations for outputs which are unwanted.

If k is outside the range 1:max (nargout), the function returns false. k can also be an array, in which case the function works element-by-element and a logical array is returned. At the top level, isargout returns an error.

See also: nargout, varargout, nthargout.


Next: Default Arguments, Previous: Variable-length Argument Lists, Up: Functions and Scripts   [Contents][Index]