Is it possible to declare a anonymous function globally?
16 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Stephen23
2017-5-3
编辑:Stephen23
2017-5-3
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 个评论
Stephen23
2017-5-3
编辑:Stephen23
2017-5-3
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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Function Creation 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!