Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 381
adgteq Avatar asked Jun 11 '26 13:06

adgteq


1 Answers

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
like image 76
Rody Oldenhuis Avatar answered Jun 14 '26 15:06

Rody Oldenhuis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!