Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Please go through the subfunction page (or local function as MATLAB calls it) in its entirety before watching the following tutorial video. In the above example, there are three functions: the main function is called newsstats. Within this function, there are two subfunctions; one called mean and the other, median. The subfunction is defined the exact same way as the main function; but the difference is that the subfunction is available to functions in this M-file only - you cannot call your subfunctions in the command window. In the above example, the main function calls both of the subfunctions, making the code much shorter and simpler. For longer, more complex code, this can save you a lot of debugging time by breaking down your code into smaller pieces.
Open up beam5.m. We will use the subfunction concept to incorporate the main program (beam5.m) and the function bending_stress into one M-file. We are going to designate beam5.m as a function. So at the top of the code, include the following code:

function main_function

Click save as - and name the file main_function - the same as the function's name. Now, open up bending_stress.m and copy the entire code. Paste it below the main function. Close both functions with an end. What you have now should look like this:

Image Removed

Widget Connector
width600
urlhttps://www.youtube.com/watch?v=ld3Li5BAU78
height370

Your main_function file should look like this. 

Image AddedNow, run main_function in the command window. The result should be the same plot you saw when you ran beam3.m and beam5.m.

Subfunction workspace

The last paragraph of the Local Functions documentation page says that "All functions, including local functions, have their own workspace that are separate from the base workspace.  Local functions cannot access variables used by other functions unless you pass them as arguments" and vice-versa. The following video covers this very important concept. 

...