Functions ca be defined inline in the same script from where they are called.
Programming a function is demonstrated in the following example of a function examples(x), which multiplies its argument by 2. After the definition it can be used like any other function.
Following the keyword function is the prototype with a return variable y. This replaces the construct return y of other programming languages.
Here is a more standard way to format a function:
which multiplies the value 10 by 2 and print it.
If functions are to be reused later, they should be written to a text file and saved somewhere in search path. The filename must be the function name extended by ”.m”, in the present example ttwo.m. In subsequent sessions the function ttwo can be used without separately loading the file. Several installed functions are provided using this mechanism.
You can list all functions which come with the program executing this statement:
It print all modules and functions. Functions typically ends with ”.m” (MatLab scripts) or ”.java” (Java-implemented functions). You can get help and examples on a particular function as: You can add a new directory with your ”.m” files using addpath methods.
where “acosh” is the name of the function. This will generate a dialog which shows how to use this function.
Exercise: Try to see what “help” function is doing by replacing “acosd” with “help”
Functions can be created in the same macro, and can be passed to other functions as arguments
In this example we pass the function “fit” to the function “newtest”. Note we use the symbol ”@” to tell the program that the type is “user function”. Then we evaluated the function using 3 parameters and one argument x=10.