12.07.2015 Views

Basics of MATLAB and Beyond

Basics of MATLAB and Beyond

Basics of MATLAB and Beyond

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

The last row needs special treatment (see what happens when you letthe loop run to i = N). On my computer this code took 2.1 seconds toexecute, compared to 2.9 seconds for the simple for loop implementationgiven on page 177. We have saved nearly one second: not much, but ifyou have to repeat the calculation 10,000 times it becomes worthwhile.38.2 M-File Subfunctionsmatlab allows you to put more than one function in a file. If you putmore than one function in a file, the second <strong>and</strong> subsequent functions aresubfunctions; the first is the main function, or primary function. Theidea 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;otherwisedisp(’Unknown course: do you really want to eat this?’)endIn this example prepare is the subfunction <strong>of</strong> the cook function. Whenmatlab encounters the call to prepare, it checks to see if there is asubfunction called prepare in the same file before looking along thesearch path for an m-file called prepare. (Actually before looking alongthe path, it checks for the existence <strong>of</strong> a private subdirectory first. Seethe helpdesk if this intrigues you.) This means that you can give asubfunction the same name as an existing matlab function. The mainfunction will use the subfunction <strong>and</strong> any other function will use theother existing function. As is true for single-file functions, subfunctionscannot “see” variables unless you pass them as arguments or declarethem global. Subfunctions are invisible to help, which sees only themain function.c○ 2000 by CRC Press LLC

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!