Property validation against another property
11 次查看(过去 30 天)
显示 更早的评论
Hello, I am using matlab system object in Simulink and set two of its properties via mask. I want to make sure that the value of property two (max_cmd) is greater than the value of property one (min_cmd):
properties(Access = public)
% min_cmd Minimum command
min_cmd (1,1){mustBeNonnegative} = 0
% max_cmd Maximum command
max_cmd (1,1){mustBeNonnegative, mustBeGreaterThan(max_cmd, min_cmd)} = 1000000
end
Unfortunately, I get the following error:
Validator arguments must be either 'max_cmd' or constant literal values.
Any ideas how to validate max_cmd > min_cmd? Thank you!
1 个评论
chrisw23
2023-2-20
have you tried ?
max_cmd (1,1){mustBeNonnegative, mustBeGreaterThan(max_cmd, obj.min_cmd)} = 1000000
回答(1 个)
David Szwer
2023-2-20
I don't think this is possible using a validation function. The help page says, "Additional arguments must be literal values and cannot reference variables. Literal values are nonsymbolic representations, such as numbers and text."
To do what you want, you could write a set method (enforcing the condition), and an explicit constructor for the object (also enforcing the condition). For example:
methods
function obj = set.max_cmd(obj,value)
if (value > obj.min_cmd)
obj.max_cmd = value;
else
error('Max command must be greater than min command.')
end
end
end
However, this will give you a warning that get/set methods should not access other properties. You may be able to ignore this warning if you are very careful; see:
Probably your best bet is to make those properties private, without validation, and create public methods like setLowerLimit(obj, min_cmd) that can enforce the conditions using both properties.
1 个评论
Giacomo Riva
2023-11-22
编辑:Giacomo Riva
2023-11-22
"Probably your best bet is to make those properties private, without validation, and create public methods like setLowerLimit(obj, min_cmd) that can enforce the conditions using both properties."
If we set the properties to private, then no access for getter or setter methods will be granted. But your approach seems to work if the properties are public and not initialised by the constructor.
In fact, I think it's even a use-case example of setter methods from the Matlab documentation:
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Argument Definitions 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!