MATLAB Programming/Portable Functions

Functions in MATLAB
A function is a group of sequential expression statements (a.k.a pseudo-algorithm) that are formed together perform a task. In MATLAB, functions are defined in separate files. The name of the file and of the function MUST be the same. Functions operate on variables within their own workspace, which is also called the local workspace, separate from the workspace you access at the MATLAB command prompt which is called the base workspace.

Functions can accept more than one input arguments and may return more than one output arguments.

The sntax of functions as followed

function [y1,...,yN] = myfunc(x1,...,xM)

where syntax declares a function named myfunc that accepts inputs x1,...,xM and returns outputs y1,...,yN. This declaration statement must be the first executable line of the function. Valid function names begin with an alphabetic character, and can contain letters, numbers, or underscores.

Create Functions in Separate Files
To create a new function, at "Home" tab, click on "New" ---> "Functions" It will create a template looks like the following:

Declare a function
To demonstrate a function usefulness, we are going to take a hypothetical situations , ''Recently, in your class there are some exchange students from America whom are consistently complaining the weather is hot outside, when they check on their weather app, they exclaimed the weather is 100 degrees outside. But as to the people who never uses the imperial units before, you might wonder, what is the temperature outside right now ?''

So, to solve the question, it might be a good time to create a custom functions to convert from Fahrenheit to Celsius. First of all, we must know the conversion formula from Fahrenheit to Celsius which is given as: $$C^o = (F^o-32)*\frac{5}{9}$$

At "Home" tab, click on "New" ---> "Functions"

Click on save button to save the functions as convertTemp.m file Note: The filename MUST be same as function name or else it won't work !

Later, on the Current Folder Panel, select the directory where you save the function files just now.

Calling a function
To call the newly created function, do the following: On the Command Window Panel, type this command as shown

Hence, the weather outside is almost 38 Celsius degrees.

Benefits of functions
Why this is beneficial, you might ask ?

Well, from this exercise, you can see that you can just type function name to execute the calculation especially for repetitive tasks. Just imagine for example above, it will be a real time saver to just type function convertTemp instead of manually typing formula each tims.

Type of functions
The type of functions includes such as:
 * Anonymous Functions
 * Local Functions
 * Nested Functions
 * Private Functions
 * Inline function (Phased out in future version)

Anonymous Functions
Anonymous functions allow you to define a function without creating a program file, as long as the function consists of a single statement. A common application of anonymous functions is to define a mathematical expression without creating a separate files.

Here is how the anonymous syntax looks like output = @(arguments) expression where, output = output to be returned arguments = required inputs to be passed expression = a single formula/logic

It can accept multiple inputs and return one output. They can contain only a single executable statement.

Here, we have an examples of converting Fahrenheit to Celsius.

Another example here is using anonymous function to convert minute to seconds (NOTE: 1 minute is equal to 60 seconds)

Local functions
Sometimes in mathematics, you might be encountering an issue where you might find a use case where function that are better to be calculated within it's own function. Rather than running separate functions to get one output, you just need to run just one function to get the multiple output. This is where local functions comes in. To clarify further, in a function file, the first function in the file is called the main or parent function. Additional functions within the file are called local functions, and they can occur in any order after the main function. Local functions are only visible to other functions in the same file. These are equivalent to subroutines in other programming languages, and are sometimes called sub-functions.

The application for this local functions is in a complex function, it would be easier to be broken down to smaller piece of functions and we are certain that the functions are going to be used in same functions and not at other functions.

Examples of local functions
To illustrate an examples, we will create a function statistik which will take in a series of number and return an output of basic function of statistic such as max, min, average and standard deviation. We will give it just a sting of random numbers and it will produce all the usual statistic results.

First of all, we need to create a function named statistik, follow the instruction here at Create Functions in Separate Files

After creating function statistik in a separate file, we generate a random set of number inside the Command Window using randi function

We call the function statistik as followed inside the Command Window: [maximum,minimum,average,stdeviation]=statistik(V)

Although you cannot call a local function from the command line or from functions in other files, you can access its help using the help function. Specify names of both the file and the local function, separating them with a > character.

Nested Function
Nested functions are functions that are nested entirely inside the main functions. The primary difference between nested functions and local functions is that nested functions can use variables defined in parent functions without explicitly passing those variables as arguments.

Requirements of nested functions
(a) To nest any function in a program file, all functions in that file must use an end statement. (b) A nested function can't be defined inside any of the program control statements, such as if/elseif/else, switch/case, for, while, or try/catch. (c) A nested function either directly by function name, or using a function handle that you created using the @ operator (refer to anonymous function). (d) All of the variables in nested functions or the functions that contain them must be explicitly defined. That is, you cannot call a function or script that assigns values to variables unless those variables already exist in the function workspace.

Examples of nested functions
We have a hypothetical situations where we need to estimate the weight of metal ingots which are in cylindrical shape. First, before we started on figuring out the metal ingots weight, we need to break down the problems into smaller piece. To figure out the weight of the metal, we need to figure out the density and before figuring out density we need to figure out volume of the metal.

To start off, before we start to know the volume of ingot, we first calculate the surface area of the cylinder base which is circle. Area of circles is defined as $$ A = \Pi r^{2} $$ ,r is radius of base circle

We can use the area of circle to calculate the volume of cylinder $$ V = A*h $$ ,h is height of cylinder. $$ V = ( \Pi r^{2} ) h $$

Lastly, we use the volume and density to calculate the weight $$ W = V * D $$ where D is density.

In MATLAB, we formulate the formula such as these. Note: For the nested functions beside main funtions, we need to indent the functions. Editor -> Indent.

Note:

When we calling ingot_calc function in the command window, it should display the values

Inline Functions
Inline functions are currently being phased out. Anonymous functions should be used instead. Inline functions are included here for information purposes.

>> convert_s_to_ms = inline('x*1000','x'); >> convert_s_to_ms(20) ans = 20000

Function Handles
Function handles are doubles serving as an abstract reference to the function. Handles allow an equation to be passed to another function for direct evaluation. Anonymous functions are useful for command-line evaluation or for multiple evaluations in the same m-file.

The ampersat returns the handle of a function either built into Matlab or defined in an M-file.

To illustrate example, we need to build a tent as shown on the picture but we need to figure out what is the amount of tarp that are needed to build the carnival tent. Therefore, we will create two separate functions which take the radius and slant height of cone (cone) plus radius and height of cylinder (cylinder).

To refresh the your memory, formula for cone surface (remember we focus slanting area and ignore the base area) is $$ \Pi r l $$ and cylinder surface (remember that one side of circle of cylinder is not calculated) is $$ 2 \Pi r h + \Pi r ^{2} $$ , where the r is the shared radius of cylinder and cone, l is the length of slanting height of cone and finally h is height of cylinder.

Follow steps in Create Functions in Separate Files to start create totalsurftent

We can know the surface area by typing following commands:

Function Handles in m-files
If you are not familiar with m-files, then skip this and come back.

A function handle passes an m-file function into another function. This of course lets you have more control over what's passed there, and makes your program more general as it lets you pass any m-file (as long as it meets other requirements like having the right number of input arguments and so on). The functionality is similar to that of function pointers in C++.

To pass an m-file to a function, you must first write the m-file, say something like this:

function xprime = f(t,x) xprime = x;

Save it as myfunc.m. To pass this to another function, say an ODE integrator, use the @ symbol as follows:

>> ode45(@myfunc, [0:15], 1)

One advantage of using function handles over anonymous functions is that you can evaluate more than one equation in the m-file, thus allowing you to do things like solve systems of ODEs rather than only one. Anonymous functions limit you to one equation.

How to write a function that accepts a function handle
Functions can accept function handles. To do this define them as variables in your header, and then call the handles as if they were functions:

% myadd adds two variables together function result = myfunc(func, a, b); result = func(a, b); [in a separate m-file] function sum = myadd(a, b) sum = a+b;

The command you send to myfunc looks like this:

>> result = myfunc(@myadd, 1, 2); result = 3