I have this
classdef what
properties ( ... )
...
end
methods (Access=public)
...
end
methods
function obj = what(...) ... end % constructor
function test = Test1() ... end
function test = Test2() ... end
end
The constructor has a lot of constraints in it such that when I create the what
it fails if the conditions are not met, the constraints are tested by calling Test1
and Test2
.
I have stored the test functions also under methods, and I want these to be hidden so that they don't show up outside the classdef
. but I get thrown an error for Test1
and Test2
.
I want these Test
functions to be private
, hidden
, and only related to this class but I also want it to be call-able when using the constructor function found in methods, My question is: what would be the 'correct' place and method to store these functions.
I am currently getting an error when I use the constructor function, however, if I add the functions in the bottom of the page outside the classdef then the functions work but I am not sure if this is good practice and why I can't have the test functions in the method section.
There are several ways to deal with this.
In general, private functions are placed inside a methods (Access = private)
block. Sometimes they can also be made static, if this makes sense. Private methods can also be placed in a separate folder.
classdef what
methods % no properties here
function obj = what(varargin) % constructor
...
out = obj.Test1(in); % object method calling example
...
end
end
methods (Access = private)
function tf = Test1(varargin)
...
end
% etc ...
end
If these functions are only ever used by the constructor, you can make them nested:
classdef what
methods % no properties here
function obj = what(varargin) % constructor
...
out = Test1(in); % no need for "obj" here
...
function tf = Test1(varargin)
...
end % Test1
end % constructor
end % methods
As mentioned by Cris, you can also put functions after the classdef
block:
classdef what
...
end
function tf = Test1(varargin)
end
The suggestions above should solve your problem. Now for some other comments:
what
, as this is a name of a builtin MATLAB function.private
method block to be Hidden
, this is generally not needed in order to "hide" private
methods, as these are not visible outside the class anyway.