Is it possible to declare a anonymous function globally?
16 views (last 30 days)
Show older comments
Hello,
I have a main script-file and various subfunctions (in separate files). In the main script I have declared some anonymous functions like this (but more complex):
test = @(x, y) x * y - x;
test(5, 6)
= 25
How can I globalize these anonymous functions to use them within my separate subfunction-files?
Right now I have to setup all the anonymous functions in each subfunction-file again and again but whenever I adjust one of the anonymous functions, I have to do this for every file. This is quite annoying.
Thank you!
0 Comments
Accepted Answer
Stephen23
on 3 May 2017
Edited: Stephen23
on 3 May 2017
1) Put them each into their own Mfiles.
2) Put them into one cell array, and pass that cell array properly as a function argument:
>> C = {@sin,@cos,@sqrt}; % functions in cell array
>> C{2}(pi) % call second function
ans =
-1
3) Put the functions into one non-scalar structure, and pass that structure properly as a function argument
>> S(1).test = @sin;
>> S(2).test = @cos;
>> S(3).test = @sqrt;
>> S(2).test(pi) % call the second function
ans =
-1
4) (Walter Roberson's suggestion): Put them into the fields of a scalar structure:
>> T.sin = @sin;
>> T.cos = @cos;
>> T.sqrt = @sqrt;
>> T.cos(pi) % call the "cos" function
ans =
-1
4 Comments
Stephen23
on 3 May 2017
Edited: Stephen23
on 3 May 2017
If you put the functions into their own Mfiles then you will need to either
- pass all those arguments and return the calculated value, or
- return a function handle that accepts those arguments.
At the point when a function handle is created those variables either need to have a value, or be specified as an input argument (or be symbolic, but I would not recommend that for your case).
One convenient and simple way of passing many arguments is to put them into one scalar structure.
I do not understand what your question has to do with method #1, as your example uses an anonymous function and does not seem to use an Mfile.
More Answers (0)
See Also
Categories
Find more on Function Creation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!