You are a guest. Restricted access. Read more

User functions

Inline functions

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.

function y=example(x) y=2*x; end
printf('%f',example(3.123) )

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:

function y=test1(x) 


which multiplies the value 10 by 2 and print it.

Functions in files

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”

Passing functions to other functions

Functions can be created in the same macro, and can be passed to other functions as arguments

function y=fit(a,x) % build function to fit data
y=a(1)*exp(-(x-a(2)).^2/a(3)^2); end;

d=fit([1 4 5],5) % testing function

% this is another function which can take any function as argument
function y=newtest(ff,a,x)

a = newtest(@fit,[10,20,30],10)
a = newtest(@fit,[20,2,30],10)

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.

jmathlab/functions/user.txt · Last modified: 2015/05/10 17:18 (external edit)
Back to top
CC Attribution-Share Alike 3.0 Unported = chi`s home Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0