Author: Rajesh Bhaskaran, Cornell University Problem Specification |
Let's create a function to calculate the bending stress that outputs σx given (M, ri, ro ). Functions are really useful to break down your code into modules.
Let's first pick MATLAB's brain on how to create functions in MATLAB. Bring up the following page in the Help navigator:
Help > Contents > MATLAB > Programming > M-File Programming > M-File Scripts and Functions > M-File Functions.
This page has a simple example: a function called average that calculates the average of the elements in a vector. Take a minute to peruse this example. MATLAB has extensive documentation on the use of functions; however, one has to poke around a bit before finding the most useful information. I personally go for the examples first.
The correct syntax for creating a function is:
function return_value = function_name(parameter_1, parameter_2,...)
%function description - MUST be in a comment
code...
return_value = value
A few noteworthy points to ponder:
help function_name
in the Command Window.We will start by creating the bending stress function that outputs σx given (M, ri, ro ). Create a new page in the editor. Type in the following statements into the new page (yeah, yeah, yeah ... go ahead and copy-and-paste):
Save this as bending_stress.m, which is the name that MATLAB automatically assigns the file. Notice is the same name as the function name. Make a copy of beam4.m using Save As ... and call the new file beam5.m
In this file comment out the lines below
Now we will need to call the function bending_press
we just created to obtain the value for σx that is needed to create the plot. Do this by typing:
Run the file beam4.m and check the output You should get the same plot you got in the file beam3.m
Before we part, let's remind ourselves of some important programming guidelines that we have followed in this tour: