[MATLAB logo] Exploiting MATLAB's Data Structures

Problem #5 - Exploding m-files

A variable number of input or output arguments can be created using the varargin or varargout cell arrays. These are special cell array variables,which, if defined in the function declaration, automatically map to the input and output arguments to the function. varargin and varargout can follow normal "required" variables in the input and output declaration lists. In this case varargin or varargout map to any remaining input or output variables.

Example:

function s = add(varargin)
%ADD Add all the inputs.
%    S = ADD(A,B,C,D,...) produces the result S = A+B+C+D+ ...
s = 0;
for i=1:length(varargin)
	s = s + varargin{i};
end

Varargin, varargout and the comma-separated list

The comma separated list syntax is particularly useful for dealing with the varargin or varargout cell arrays. In particular, you can use the comma separated list expansion to send any optional parameters down in function-functions.

function result = run(fun,varargin)
%RUN Run an m-file.
result = feval(fun,varargin{:})

Goal: Create the function explode that breaks an N-element vector into N output arguments.

Key concepts: variable input and output arguments

Key functions: varargin, varargout

What to do

  1. Using the editor, create a function explode with the following syntax:
    [a1,a2, ..., aN] = explode(x)
    where N is length(x).
  2. Try your function on the following example
    [a,b,c] = explode(1:3)
    what are the values of a, b, c?

[hint] [Show me the solution]

Copyright © 1997 The MathWorks, Inc.
clay@mathworks.com
$Revision$ $Date$