0
votes

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?

1
I don't get your question. What is the set_x method in your second exemple code ? - Ratbert
@Ratbert , there was a mistake in first code, its updated now, tnx for comment :), set_x is my implementation of a set method for my value_class. but when i call this method using a.set_x(3) , it doesnt make any change on "a" itself, but it create a copy of a and change the copy version. - Hadi

1 Answers

0
votes

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)