Common get and set methods for dynamic properties in user defined classes

3 Ansichten (letzte 30 Tage)
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?

Antworten (1)

Paras Gupta
Paras Gupta am 16 Okt. 2023
Bearbeitet: Paras Gupta am 16 Okt. 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.

Kategorien

Mehr zu Guidance, Navigation, and Control (GNC) finden Sie in Help Center und File Exchange

Tags

Produkte


Version

R2020b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by