Programming |
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:
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:
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:
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{:})
Passing Certain Argument Types | Calling External Functions |
© 1994-2005 The MathWorks, Inc.