Graphics Programs Reference
In-Depth Information
The last row needs special treatment (see what happens when you let
the loop run to i=N ). On my computer this code took 2.1 seconds to
execute, compared to 2.9 seconds for the simple for loop implementation
given on page 177. We have saved nearly one second: not much, but if
you have to repeat the calculation 10,000 times it becomes worthwhile.
38.2 M-File Subfunctions
matlab allows you to put more than one function in a file. If you put
more than one function in a file, the second and subsequent functions are
subfunctions; the first is the main function, or primary function. The
idea is to have a file with the following structure:
function dinner = cook(entree,maincourse,dessert)
% Get matlab to cook a meal.
E = prepare(entree);
M = prepare(maincourse);
D = prepare(dessert);
dinner = [E M D];
function output = prepare(course)
switch iscourse(course)
case 'entree'
output = makeentree;
case 'maincourse'
output = makemaincourse;
case 'dessert'
output = makedessert;
disp('Unknown course: do you really want to eat this?')
In this example prepare is the subfunction of the cook function. When
matlab encounters the call to prepare , it checks to see if there is a
subfunction called prepare in the same file before looking along the
search path for an m-file called prepare . (Actually before looking along
the path, it checks for the existence of a private subdirectory first. See
the helpdesk if this intrigues you.) This means that you can give a
subfunction the same name as an existing matlab function. The main
function will use the subfunction and any other function will use the
other existing function. As is true for single-file functions, subfunctions
cannot “see” variables unless you pass them as arguments or declare
them global. Subfunctions are invisible to help , which sees only the
main function.
Search WWH ::

Custom Search