0

As the title says I am setting a property with the constructor and would like to access the property later as a get function that is static. How would I do this in MATLAB?

classdef Wrapper
    
    properties(Access=public)
        dataStruct
    end
    
    methods
    
        function data = Wrapper(filePath)
            if nargin == 1
                data.dataStruct=load(filePath)
            end
            
        end
    end
        
    methods(Static)
        function platPosition = getPlatPosition()
            platPosition = dataStruct.someField
        end
    end
end

--------------------------
import pkg.Wrapper.*
test = Wrapper('sim.mat')
pos = test.getPlatPosition
Steven
  • 139
  • 1
  • 9
  • It is surprising that you want to access a dynamic property from a static method. What is the need to keep the method static ? You can of course pass the object as first argument as Praveen suggested but in this case, what is the difference with a dynamic method ? – Steens Aug 29 '22 at 07:19

1 Answers1

0

As far as I know MATLAB doesn't have static properties like other OOP languages [ref]. Only static properties can be used inside the static methods. The closest you can get in MATLAB classes to static property is Constant property. The downside is the constant property has to be initialized and is read-only. Inside the static method, You can access read-only/constant property with class name.

classdef Wrapper
    
    properties(Constant=true)
        dataStruct=load('\path\to\sim.mat');
    end
    
    methods
        function data = Wrapper()   
            %do something with object
        end
    end
        
    methods(Static=true)
        function platPosition = getPlatPosition()
            platPosition = Wrapper.dataStruct.Fieldname;
        end
    end
end

In your case, you could accept object as an input argument of your static method.

classdef Wrapper
    
    properties(Access=public)
        dataStruct
    end
    
    methods
    
        function data = Wrapper(filePath)
            if nargin == 1
                data.dataStruct=load(filePath)
            end
            
        end
    end
        
    methods(Static)
        function platPosition = getPlatPosition(obj)
            platPosition = obj.dataStruct.someField
        end
    end
end
--------------------------
import pkg.Wrapper.*
test = Wrapper('sim.mat')
pos = test.getPlatPosition(test);
Praveen
  • 158
  • 2
  • 6