Suppose I have a function f()
and I want to use it in my_file.m
, which is a script.
- Is it possible to have the function defined in
my_file.m
? - If not, suppose I have it defined in
f.m
. How do I call it inmy_file.m
?
I read the online documentation, but it wasn't clear what is the best way to do this.
You can do something like this (assuming your file is named
my_file.m
):If you click the run button the function
my_file
will be executed as default.As of R2016b, you can define local functions within a script.
The way I get around this limitation, is to turn my scripts into functions that take no arguments (if I need variables from the global namespace, I either explicitly pass them in the function, or use "evalin" to grab them.)
Then you can define all the additional functions you need in the "script." It's a hack, but I have found it to be quite powerful in those cases where I need several non-trivial functions.
EDIT: Here's a simplistic example. All this can reside in a single file.
You can have many functions in a sample file. But only the first one can act as a main function, when you run the file. Others can be used merely in this file. For some situation you want to define a big function. You can separate it into smaller functions and define below it.
However, the most simple way to find the answer is having a try~
I have implemented the solution by John, and I found it useful. But there are a couple of caveats (in Octave; Matlab possibly behaves similarly):
If code inside your main function contains
clear all
prior to using the auxiliary function, it will not work. In filetest3.m
, commenting/uncommentingclear all
makes code work/not work.From It seems like upon running a script, there is a first pass where code outside functions is executed (in this case, there is no such code), and functions defined (in this case,
test3
andmyfunc
) are added to the workspace. A second pass would execute the main function, which would not findmyfunc
ifclear all
is active.As pointed out by chessofnerd, out-of-the-box the variables in your main function do not go to the workspace.
As of release R2016b, you can have local functions in scripts, like so:
Prior to release R2016b, the only type of function that could be defined inside a MATLAB script was an anonymous function. For example:
Note that anonymous functions are better suited to simple operations, since they have to be defined in a single expression. For more complicated functions, you will have to define them in their own files, place them somewhere on the MATLAB path to make them accessible to your script, and then call them from your script as you would any other function.