Reputation: 105
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
Upvotes: 0
Views: 1273
Reputation: 198
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);
Upvotes: 1