suppose you have a value classes (and you want it to be a value class and not a handle class) the question is : how to implement a set property in this value class to to do some work in time of setting new value?
suppose we have the following code
classdef value_class
properties
x=0
end
methods
function obj=set_x(obj,v)
%do the stuff
if v>5
obj.x=v;
end
end
end
end
if you test this class, will see the following :
>a=value_class;
>a.x=2;
>a
a =
value_class with properties:
x: 2
which is correct (but our criteria of x>5 not checked) and then
>a.set_x(3);
> a
a =
value_class with properties:
x: 2
which is obviously has no effect on "a"!. in this case matlab sends a copy of "a" to function set_x() thus the actual "a" does not change.
so if you write your own set function to do some stuff before assigning a value to property of a value class then you can not use that function to change the value of its caller object!
then what is the true way of implementing a set function for a value class?
Matlab has a default set method which we can use as a set function for our value (or non value) classes
classdef value_class
properties
x=0
end
methods
function obj=set.x(obj,v)
%do the stuff
if v>5
obj.x=v;
end
end
end
end
then if we test this class:
> a=value_class
a =
value_class with properties:
x: 0
> a.x=2
a =
value_class with properties:
x: 0
> a.x=6
a =
value_class with properties:
x: 6
in this case when you try to set new value to a , its set function runs and check the value in our criteria. (to overloading other operators)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments