adgteq
adgteq

Reputation: 83

overloading the "dot" operator in MATLAB

I have written a simple class in MATLAB to manage a set of key-value pairs. I would like to be able to access the keys using a dot after the object name like:

params.maxIterations

instead of:

params.get('maxIterations')

Is it possible to override the dot operator so that it calls my get() method?

I have tried to override the subsasgn() method as suggested here but I couldn't figure out how I should write it.

Upvotes: 3

Views: 285

Answers (1)

Rody Oldenhuis
Rody Oldenhuis

Reputation: 38032

You could use dynamic properties. Then instead of adding a list of strings, you add a new property for each 'key'. Get all keys with properties(MyClass) (of just fieldnames(MyClass)

However, I think it's indeed best to overload subsref, but note that doing that properly can eat away the majority of a work week if you do it for the first time...It's not that it's really difficult, it's just that the () operator does so much :)

Luckily, you don't have to. Here's how:

classdef MyClass < handle

    methods

        function result = subsref(obj, S)

            %// Properly overloading the () operator is *DIFFICULT*!!
            %// Therefore, delegate everything to the built-in function, 
            %// except for 1 isolated case:

            try
                if ~strcmp(S.type, '()') || ...
                   ~all(cellfun('isclass', S.subs, 'char'))

                    result = builtin('subsref', obj, S);

                else                    
                    keys = S.subs %// Note: cellstring; 
                                  %// could contain multiple keys

                    %// ...and do whatever you want with it

                end

            catch ME
                %// (this construction makes it less apparent that the
                %// operator was overloaded)
                throwAsCaller(ME);   

            end

        end % subsref method

    end % methods

end % class

Upvotes: 5

Related Questions