You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 11 Next »

Step 6: Plot σx vs. ri , Take 4: Functions

Let's create a function to calculate the bending stress that outputs σx given (M, ri, ro ).

Before we start doing this bring up the help file for creating functions in MATLAB. You can find it in the directory specified below:

Help > Contents > MATLAB > Programming > M-File Programming > M-File Scripts and Functions > M-File Functions.

Look at Simple Function Example: The average function that calculates the average of the elements in a vector. As you can see MATLAB has a very good help support system that you can use as a reference whenever you run into problems.

As you can see the correct syntax for creating a funcion is:

function return_value = function_name(parameter_1, parameter_2,...)

%function description - MUST  be in a comment

code...

return_value = value

In MATLAB you do not need to have a function description but it is good programming practice to add a comment on each function that describes what the function does. Also, if you add a description of the function MATLAB will be able to index it and return a description of your function if you type help function_name in the Command Window.

Once you have created a function you MUST name the .m file with the same name the function has. Otherwise you MATLAB will not be able to access your function when you call it.

We will start by creating the bending stress function that outputs σx given (M, ri, ro ).


 
Save this as bending_stress.m, which you can notice is the same name as the function name.  Make a copy of beam3.m using Save As ...  and call the new file beam4.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:

  • Develop code incrementally, testing obsessively at each stage. Develop a plan for how you are going to build your code before you sit at the computer.
  • Dig through the MATLAB help diligently to figure out how to use specific functions etc. Usually, the examples are the best place to start. This is a better strategy than desperately hunting for the TA every time you need help with your code.
  • Comment your program liberally.
  • No labels