User1551892
User1551892

Reputation: 3364

How to use private methods inside public methods in matlab

I have couple methods in Matlab class. I am accessing few of them in some of these methods but somehow, in order to call those methods, I need to place "instaceName." in start of method names. I have c# background and does not feel comfortable. In C#, different level of visibility of methods can be defined.

classdef SampleClass
%UNTITLED2 Summary of this class goes here
%   Detailed explanation goes here

properties
    result ;
end

methods
    function method1 (obj, a , b) 
       obj.result = obj.method2 (a,b) ;
    end
end
methods (Access= private)
    function y = method3 ( a , b)
        y = a + b ; 
    end  

    end   

end

If I define methods as static which I want to use internally in that class then will it work. Is there a suggestion to deal this issue.

classdef SampleClass
    %UNTITLED2 Summary of this class goes here
    %   Detailed explanation goes here

    properties
        result ;
    end

    methods
        function method1 (obj, a , b) 
           obj.result = SampleClass.method2 (a,b) ;
        end      

    end

    methods (Static)
        function y = method2 ( a , b) 
            y = a + b ; 
        end      

    end

end

Upvotes: 1

Views: 3149

Answers (1)

gire
gire

Reputation: 1105

Unfortunately there is no workaround for the issue that you mention. Class method signatures must always pass the "instance" into itself:

function output = DoSomething(this, arg1, arg2)

There are several methods to call a class method (take for example the above method DoSomething from Class MyClass):

my_instance = MyClass(...);

% Call type 1
output = my_instance.DoSomething(arg1, arg2)

% Call type 2
output = DoSomething(my_instance, arg1, arg2)

The type 2 feels more intuitive and aligned with the function signature.

In your example, both the instance method and the static method are interchangeable because you are not using method properties. But that's not always the case: static methods cannot access the private/protected properties of the class.

Extra note: as far as I know, many OO languages do the same but behind the scenes (C++ and C# automatically add the instance argument to the method, but correct me if I am wrong). The only difference is that in Matlab you must do it explicitly.

C++ explanation.

Upvotes: 1

Related Questions