- SetObservable, GetObservable - https://www.mathworks.com/help/matlab/matlab_oop/property-attributes.html
- addlistener - https://www.mathworks.com/help/matlab/ref/handle.addlistener.html
- Listen for Changes to Property Values - https://www.mathworks.com/help/matlab/matlab_oop/listening-for-changes-to-property-values.html
Common get and set methods for dynamic properties in user defined classes
3 views (last 30 days)
Show older comments
The matlab documentation shows how to define get and set functions for dynamic properties. Is it possible to defiine get and set methods that are common to several dynamic properties?
0 Comments
Answers (1)
Paras Gupta
on 16 Oct 2023
Edited: Paras Gupta
on 16 Oct 2023
Hi Rajmohan,
I understand that you are want to have common set and get methods for several dynamic properties in a MATLAB class.
You can use the 'addlistener' function along with the 'PostSet' event to define a common set method, and the 'addlistener' function with the 'PostGet' event to define a common get method.
The following example code illustrates how to achieve the same:
classdef Car1 < handle
% The properties need to be defined as SetObservable and GetObservable
properties (SetObservable, GetObservable)
Brand
Model
end
methods
function obj = Car1(brand, model)
obj.Brand = brand;
obj.Model = model;
addlistener(obj, 'Brand', 'PostSet', @obj.commonSetMethod);
addlistener(obj, 'Model', 'PostSet', @obj.commonSetMethod);
addlistener(obj, 'Brand', 'PostGet', @obj.commonGetMethod);
addlistener(obj, 'Model', 'PostGet', @obj.commonGetMethod);
end
function commonSetMethod(obj, ~, ~)
disp('Common set method called');
end
function commonGetMethod(obj, ~, ~)
disp('Common get method called')
end
end
end
You can try running the following commands to see that the 'commonSetMethod' and 'commonGetMethod' are being executed for both the properties 'Brand' and 'Model'.
car = Car1('Brand1', 'Model1');
car.Brand = 'Brand2';
car.Model = 'Model2'
disp(car.Brand);
disp(car.Model);
Please refer to the following documentation links for more information on the functions used in the code above:
Hope this resolves your query.
0 Comments
See Also
Categories
Find more on Guidance, Navigation, and Control (GNC) in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!