Programming |
Outputs from Anonymous Functions
As with other MATLAB functions, the number of outputs returned by an anonymous function depends mainly on how many variables you specify to the left of the equals (=
) sign when you call the function.
For example, consider an anonymous function getPersInfo
that returns a person's address, home phone, business phone, and date of birth, in that order. To get someone's address, you can call the function specifying just one output:
To get more information, specify more outputs:
Of course, you cannot specify more outputs than the maximum number generated by the function, which is four in this case.
Example
The anonymous getXLSData
function shown here calls the MATLAB xlsread
function with a preset spreadsheet filename (records.xls
) and a variable worksheet name (worksheet
):
The records.xls
worksheet used in this example contains both numeric and text data. The numeric data is taken from instrument readings, and the text data describes the category that each numeric reading belongs to.
Because the MATLAB xlsread
function is defined to return up to three values (numeric, text, and raw data), getXLSData
can also return this same number of values, depending on how many output variables you specify to the left of the equals sign in the call. Call getXLSData
a first time, specifying only a single (numeric) output, dNum
:
Display the data that is returned using a for
loop. You have to use generic names (v1
, v2
, v3
) for the categories, due to the fact that the text of the real category names was not returned in the call:
for k = 1:length(dNum) disp(sprintf('%s v1: %2.2f v2: %d v3: %d', ... datestr(clock, 'HH:MM'), dNum(k,1), dNum(k,2), ... dNum(k,3))); end
Here is the output from the first call:
12:55 v1: 78.42 v2: 32 v3: 37 13:41 v1: 69.73 v2: 27 v3: 30 14:26 v1: 77.65 v2: 17 v3: 16 15:10 v1: 68.19 v2: 22 v3: 35
Now try this again, but this time specifying two outputs, numeric (dNum
) and text (dTxt
):
[dNum, dTxt] = getXLSData('Week 12'); for k = 1:length(dNum) disp(sprintf('%s %s: %2.2f %s: %d %s: %d', ... datestr(clock, 'HH:MM'), dTxt{1}, dNum(k,1), ... dTxt{2}, dNum(k,2), dTxt{3}, dNum(k,3))); end
This time, you can display the category names returned from the spreadsheet:
12:55 Temp: 78.42 HeatIndex: 32 WindChill: 37 13:41 Temp: 69.73 HeatIndex: 27 WindChill: 30 14:26 Temp: 77.65 HeatIndex: 17 WindChill: 16 15:10 Temp: 68.19 HeatIndex: 22 WindChill: 35
Arrays of Anonymous Functions | Variables Used in the Expression |
© 1994-2005 The MathWorks, Inc.