I tried coding up a function in a Matlab .m file:
function returnValue = someFunction(x, y)
returnValue = x * y + 3
end
However, Matlab noted that I was not allowed to simply declare a function in the middle of my script. I tried moving the function to the top of the file, but Matlab forced me to rename my function to the name of the file.
I soon realized that Matlab functions must match the name of their files. How do I modularize my Matlab code within a single file? Is there a way I could just define a function in the middle of my script?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With