I want a read-only field that I can access as fv=object.field
, but where the value that is
returned is computed from other fields of the object (i.e. the return value satisfies fv==f(object.field2)
).
The desired functionality is the same as for the property
function/decorator in Python.
I recall seeing a reference that this is possible by setting the parameters of the properties
block, but the Matlab OOP documentation is so scattered that I can't find it again.
To assign a value to a property from within the class constructor, refer to the object that the constructor returns (the output variable obj ) and the property name using dot notation. When you assign a value to a property in the class constructor, MATLAB evaluates the assignment statement for each object you create.
To create an object, first, we need to create a class, using ' classdef ' we create a class, in class we take some properties and end the class and then we take methods some methods using function statements after all these lastly we end the class with an end statement.
classdef Syntax Class definitions are blocks of code that are delineated by the classdef keyword at the beginning and the end keyword at the end. Files can contain only one class definition. The following diagram shows the syntax of a classdef block. Only comments and blank lines can precede the classdef keyword.
Dependent properties do not store data. The value of a dependent property depends on some other value, such as the value of a nondependent property. Dependent properties must define get-access methods ( get. PropertyName ) to determine a value for the property when the property is queried.
This is called a "dependent" property. A quick example of a class using a derived property is below:
classdef dependent_properties_example < handle %Note: Deriving from handle is not required for this example. It's just how I always use classes.
properties (Dependent = true, SetAccess = private)
derivedProp
end
properties (SetAccess = public, GetAccess = public)
normalProp1 = 0;
normalProp2 = 0;
end
methods
function out = get.derivedProp(self)
out = self.normalProp1 + self.normalProp2;
end
end
end
With this class defined, we can now run:
>> x = dependent_properties_example;
>> x.normalProp1 = 3;
>> x.normalProp2 = 10;
>> x
x =
dependent_properties_example handle
Properties:
derivedProp: 13
normalProp1: 3
normalProp2: 10
You can use the property access methods: http://www.mathworks.co.uk/help/matlab/matlab_oop/property-access-methods.html
To define get/set functions - the get function should allow you to return values computed from other members. The section "When to Use Set Methods with Dependent Properties" in the link above gives an example for this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With