How to force matlab to call a regular function rather than class method when they are overloaded?

扶醉桌前 提交于 2019-11-29 14:07:10
Bee

There is no way to do this without making some changes either to the function's name or location. If you check Matlab's function precedence order, methods always run before normal external functions. Your only practical options are:

  1. Change the function's name.
  2. Move the function's body to the same script that is calling the function (item 4 on the list above)
  3. Move the function's .m file to a folder called private in the same folder as your script file (item 5 on the list)

UPDATE

Although not quite practical for smaller projects, you may also want to look into packaging your functions. A good discussion can be found in this SO post.

If your compute happens to be a MATLAB builtin, you can use

builtin('compute', ...)

otherwise, there's no way -- see Bee's answer.

If you desperately need this, then you can do something like the following. I strongly suggest that you don't, and stick with Bee's answer. However, sometimes one has no choice ...

The idea is to wrap your instance in another class so that MATLAB's function dispatching doesn't see the compute method. However, to your compute function, the wrapped instance must appear the same as the original instance. This is tricky to get right in some cases, but often the following is enough:

classdef Wrapper

    properties (Access = 'private', Hidden = true)
        core = [];
    end

    methods

        function this = Wrapper(core)
            this.core = core;
        end

        function varargout = subsref(this, S)
            if nargout > 0
                varargout = cell(1, nargout);
                [varargout{:}] = subsref(this.core, S);
            else
                subsref(this.core, S);
            end
        end

    end

end

This class wraps an instance of another class and delegates all read access to the wrapped instance.

For example, if you have a file called TestClass.m:

classdef TestClass

    properties
        name = '';
    end

    methods
        function this = TestClass(name)
            this.name = name;
        end

        function compute(this)
            fprintf('Instance method! My name is "%s".\n', this.name);
        end
    end

end

And a function compute.m:

function compute(x)
    fprintf('Regular function! My name is "%s".\n', x.name);
end

Then it works like this:

>> t = TestClass('t');
>> s = struct('name', 's');
>> compute(t)
Instance method! My name is "t".
>> compute(s)
Regular function! My name is "s".
>> w = Wrapper(t);
>> compute(w)
Regular function! My name is "t".

Depending on what the compute function does with your instance you might need to add further "special" functions to Wrapper (e.g. subsasgn). Also note that this will break if compute does some metaclass-magic.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!