- 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
1 回表示 (過去 30 日間)
古いコメントを表示

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 件のコメント
回答 (1 件)
Paras Gupta
2023 年 10 月 16 日
編集済み: Paras Gupta
2023 年 10 月 16 日
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 件のコメント
参考
カテゴリ
Help Center および File Exchange で Guidance, Navigation, and Control (GNC) についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!