2

I use 16a. I found overloading subsref makes any function calls to an object call (). I am not sure if this is the correct use of subsref. For example,

classdef A < handle
    methods
        function obj = A(varargin)
        end

        function v = subsref(obj, S) %#ok<STOUT,INUSD>
            assert(false);
        end

        function c = foo(obj) %#ok<MANU>
            c = 1;
        end 
    end 
end

Then I god the following errors when using foo.

>> a = A()

a = 

  A with no properties.

>> a.foo()
Error using A/subsref (line 6)
Assertion failed.

8               assert(false);

If I removed subsref, it works fine. In terms of

http://www.mathworks.com/help/matlab/ref/subsref.html

subsref is called only when A{i}, A(i) or A.field. Since foo is a method, why is subsref still called?

Joe C
  • 2,757
  • 2
  • 26
  • 46

1 Answers1

4

This is completely expected behavior, because to MATLAB, A.field and A.method both use the dot referencing and therefore are processed by subsref. The typical way of getting around this is to instead call your class methods using the standard function call rather than a dot referenced method call.

method(A)

%// Rather than
A.method()

This usage is also superior as it can operate on arrays of objects rather than only scalars. Also, it is more performant.

Community
  • 1
  • 1
Suever
  • 64,497
  • 14
  • 82
  • 101
  • Can users implement a data structure like containers.Map? It has A(i) and A(i) =, and also A.length(), A.isKey(), ... – Joe C Apr 25 '16 at 08:06
  • 1
    @JoeC Yes. You would have to check the inputs to `subsref` to determine if it is a method call or property access – Suever Apr 25 '16 at 13:20