Versions Compared

Key

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

...

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.

Before we start doing this bring up the help file for creating functions in MATLAB. You can find it in the directory specified belowBring up the following page in the Help navigator:

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

Look at Simple Function Example: The average function This page has a simple example: a function called average  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.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 As you can see the correct syntax for creating a funcion function is:

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

...

code...

return_value = value

In MATLAB you {{return_value }}is the only data that gets passed back to the main code. 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 type  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.

...