Dave
Dave

Reputation: 8090

How to define a derived property in object oriented Matlab

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.

Upvotes: 5

Views: 476

Answers (2)

Pursuit
Pursuit

Reputation: 12345

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

Upvotes: 5

Hugh Nolan
Hugh Nolan

Reputation: 2519

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.

Upvotes: 2

Related Questions