Cyclic dependency in OOP

4 ビュー (過去 30 日間)
Andrew Yuan
Andrew Yuan 2018 年 12 月 27 日
回答済み: Walter Roberson 2025 年 3 月 13 日
I'm new to OOP in MATLAB, but I would like to define properties a,b,c in a class in such a way that if one of the value changes, then so do the other 2. For example, suppose that we have the relation, b = a+1, c = b+1, a = c-2. Hence, if I set the value b = 2, then c = 2+1 =3 and a = c -2 = 1.

回答 (2 件)

colordepth
colordepth 2025 年 3 月 13 日
To implement interdependent properties in MATLAB where changing one updates the others, you can use property 'set' methods or property listeners. Both approaches allow you to define custom behavior when a property value changes.
  1. Property Set Methods: Define set.a, set.b, and set.c methods in your class. These methods execute whenever the corresponding property is assigned a value. Inside each setter, update the other properties based on your equations. You can refer to the documentation for more details: https://www.mathworks.com/help/matlab/matlab_oop/property-set-methods.html.
  2. Property Listeners: These are event-driven callbacks that trigger when a property value changes. You can implement a logic for the dependent property update inside this callback. For more guidance, refer to: https://www.mathworks.com/help/matlab/matlab_oop/listening-for-changes-to-property-values.html.

Walter Roberson
Walter Roberson 2025 年 3 月 13 日
You can use dependent properties, perhaps in conjunction with hidden properties.
In the example given, you could have a hidden master property, hidden_a with get.a = hidden_a, get.b = hidden_a + 1, get.c = hidden_a + 2. Then establish set.a, set.b, set.c that affect hidden_a in appropriate ways -- for example set.c would set hidden_a = VALUE - 2;

カテゴリ

Help Center および File ExchangeGet Started with MATLAB についてさらに検索

タグ

製品


リリース

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by