I want to turn on/off dependency of two class properties based on the third property.
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
lazymatlab
am 12 Feb. 2023
Bearbeitet: lazymatlab
am 14 Feb. 2023
I made a class "rect" for rectangle, with independent properties width, height and fix_aspect_ratio.
What I want to do is:
- If fix_aspect_ratio is 0, width and height are independently modifiable.
- If fix_aspect_ratio is 1, height/width should be maintained. When I change width, height should be modified to keep the ratio, and vise versa.
What I wrote:
classdef rect < handle
properties
width (1,1) double {mustBePositive} = 1
height (1,1) double {mustBePositive} = 1
fix_aspect_ratio (1,1) logical = 0
end
methods
function obj = rect(width, height, fix_aspect_ratio)
arguments
width (1,1) double {mustBePositive} = 3
height (1,1) double {mustBePositive} = 4
fix_aspect_ratio (1,1) logical = 0
end
obj.width = width;
obj.height = height;
obj.fix_aspect_ratio = fix_aspect_ratio;
end
function set.width(obj, width)
if obj.fix_aspect_ratio
obj.height = obj.height * width/obj.width;
end
obj.width = width;
end
function set.height(obj, height)
if obj.fix_aspect_ratio
obj.width = obj.width * height/obj.height;
end
obj.height = height;
end
end
end
Problem:
- When I try to change width, set.height is called, in which set.width is called, ... I get Maximum recursion error
- When I try to change height, same thing.
Can I get any solution?
Thank you.
Kang.
0 Kommentare
Akzeptierte Antwort
chrisw23
am 13 Feb. 2023
Try to use Observed Properties
Save the listener handles as private properties and use the listeners 'Enabled' property to turn on/off the dependency as needed.
i.e.
obj.listenerObservedProp = addlistener(obj,'ObservedProp'...
obj.listenerObservedProp.Enabled = false
3 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Software Development Tools finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!