I tried coding up a function in a Matlab .m file:
function returnValue = someFunction(x, y)
returnValue = x * y + 3
end
However, Matlab not
There is not way to declare multiple canonical functions in Matlab in a single file. However, using anonymous functions and functional programming techniques you may achieve some of your desired effect.
I recommend the series on functional program from Loren on the Art of Matlab - I use these techniques on a regular basis.
http://blogs.mathworks.com/loren/2013/01/10/introduction-to-functional-programming-with-anonymous-functions-part-1/
http://blogs.mathworks.com/loren/2013/01/24/introduction-to-functional-programming-with-anonymous-functions-part-2/
http://blogs.mathworks.com/loren/2013/02/07/introduction-to-functional-programming-with-anonymous-functions-part-3/
An M file must be one of:
If you do not start an M file with either a function or class declaration, then it is a script. In that case, no functions can follow, unless then are anonymous functions, which can be defined anywhere.
If the first line of the file starts with a function, then that is the function that is executed when the file is run in MATLAB. Multiple sub-functions can be defined in any order below the main function. On a side note, the functions can optionally be terminated with an end, but then must all be consistently defined either with or without the end.
Loren discusses the types of M files and some ways of programmatically identifying the type of an M file.
The M-LINT code checker will tell you to rename the function or the file name to match, but this has historically not been enforced.
Anonymous functions
For very small functions like the one in your example, you could simply define an anonymous function like this: f = @(x, y) x * y + 3
. You can define such functions even in the prompt of your workspace or in any script file.
Nested functions
If you turn your MATLAB script into a function, it will allow you to define nested functions:
function a = my_script(x)
y = 3;
function r = some_function(b)
r = b * y + 3;
end
a = some_function(x)
end
Note that the nested function can see the value of y
. This can be handy for example, when you optimize parameters of an ODE and the solver you use doesn't provide a means to modify parameter values.
Sub functions
You can also define a function with multiple local sub functions in one single file. Sub functions are defined below the "public" function. In your example some_function
could be a sub function in my_script.m
.
function a = my_script(x)
y = 3;
p = 42;
a = some_function(x, y) + p;
end
function r = some_function(x, y)
r = x * y + 3;
end
The end
keywords are optional here. In contrast to nested functions, sub functions are rather helpful to encapsulate pieces of an algorithm, as some_function
will not see the value of p
.