Calling sub-function (local function) from another file on Matlab
33 次查看(过去 30 天)
显示 更早的评论
I'm trying to figure out how to properly call a sub function from another .m file. I've searched for documentation, and only found the way of using function handles (as can be seen here: https://www.mathworks.com/help/matlab/matlab_prog/call-local-functions-using-function-handles.html)
The thing is that I think I've managed to find a way to it without using function handles, and want to know what am i doing and how does it works:
on main.m file:
function main
%function main...
end
function z = sub_function(x,y)
%function sub_function...
end
on outside.m file:
function call_to_local_function_from_outside
z = main('sub_function', x,y);
end
Appernalty, this is working, but why?
8 个评论
Adam Danz
2020-9-13
Here's an approach recommended by the documentation,
Oli Fairfax
2024-5-29
Adam, thank you. This worked for me so well. Please put this as an answer so we can vote it.
回答(1 个)
Jan
2019-9-3
This would work:
% main.m file: -----------
function out = main(Command, varargin)
switch Command
case 'sub_function'
out = sub_function(varargin{:});
...
end
end
function z = sub_function(x,y)
z = x + y;
end
% outside.m file: -----------
function outside
x = rand
y = rand
z = main('sub_function', x, y);
end
Although this is working, it is an unnecessary indirection. This increases the level of complexity, because it forwards the local function to global calls. This means drilling a hole into the concept of local or private subfunction. It is leaner and cleaner to move sub_function() to an externally visible function in an own file, when you want to call it from the outside.
A real need to hide a subfunction can be a function name, which is used mutliple times. Then a "package" is usefull: the "+" in the folder name.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Debugging and Analysis 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!