Programming Previous page   Next Page

Passing Arguments in Structures or Cell Arrays

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.

Passing Arguments in a Structure

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:

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:

Passing Arguments in a Cell Array

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:


Previous page  Passing Certain Argument Types Calling External Functions Next page

© 1994-2005 The MathWorks, Inc.