Home > OS >  MATLAB forbid `end` as class method input
MATLAB forbid `end` as class method input

Time:09-09

classdef Dog
    methods
        function out = bark(obj, text)
%             disp(text)
            out = 1;
        end

        function ind = end(~, ~, ~)
            error("`end` forbidden")
        end
    end
end

d=Dog(), d(end) will error but d.bark(end) won't.

  • Uncommenting disp(text) instead errors as Not enough input arguments, but that's not same as forbidding end as input to bark.
  • d.bark(end, end) errors as Too many input arguments.

Can end be forbidden (or detected) as input to any method of d?

CodePudding user response:

It looks like d.bark(end) calls d.bark first, obtaining the output array out, then calls end(out,1,1). This end is not your overloaded function, it is the version for whatever type out is, which in your case is double. So this is the built-in out. This end returns 1. Finally, it calls d.bark(1).

I think this is a strange behavior. MATLAB only does this for class methods, not for free functions. For example sqrt(end) or eps(end) give the error "The end operator must be used within an array index expression.".

I don't think there is a way around this, it is built-in MATLAB behavior, it would require changing the interpreter to override the behavior.

  • Related