Storing functions in classdef files
9 次查看(过去 30 天)
显示 更早的评论
I have an object-oriented Matlab project with several classes. I store each class definition in a @-folder within a folder pathFolder (in Windows). For instance
pathFolder\@myClass\myClass.m
In the constructor of each class, I use custom-defined functions. For instance, here I would use myFunction to initialize a complicated property:
classdef myClass
properties
x;
y;
complicatedProperty;
end
methods
function obj = myClass(x,y)
obj.x = x;
obj.y = y;
obj.complicatedProperty = myFunction(x,y);
end
end
end
Right now myFunction is located in pathFolder along with the @-folder
pathFolder\@myClass\myClass.m
pathFolder\myFunction.m
That works. However, I only use myFunction within the constructor of myClass. To better organize my files, I would very much like to group myFunction.m with the class definition. However, I can't put it in the @-folder because .m files contained in the @-folder are not in the path and are automatically treated as methods of the class.
One option is to define myFunction as a static method of myClass, but I want to avoid that (it causes problems when I try to call superclass constructors in subclasses).
Another alternative is to define myFunction as a local function in myClass.m but I would also like to avoid that. I want to keep it in a separate file.
Is there a way to put the separate file myFunction.m in the @-folder so that it will be recognized in the Matlab path? I welcome suggestions.
0 个评论
采纳的回答
Guillaume
2019-5-28
Private functions are ideal for this. Store the functions in a folder called private inside the @ folder. Any function inside the private folder is only visible to m files in the containing folder, without needing to be added to the path.
更多回答(2 个)
Steven Lord
2019-5-28
Another alternative is to define myFunction as a local function in myClass.m but I would also like to avoid that. I want to keep it in a separate file.
Why do you want to avoid this? If only one class uses this function, why not make it local to the class? I would likely write this as a class-related function at the end of the classdef file, after the end that closes the classdef block.
2 个评论
Steven Lord
2019-5-28
There are tools that can help you navigate around your file. The "Go To Location in File" section of this documentation page lists many of these. I use bookmarks (set a bookmark in your current location and the helper, jump to the next bookmark to modify the class-related function, jump to the "next" bookmark which will wrap around) and the context menu "Open Selection" option to navigate around long class files quite a bit.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Class File Organization 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!