假设我有一个X
class对象MyClass
。MyClass
有一个方法compute
,当我调用时U = compute(X,...)
,matlab会自动调用类方法。但是,我真正想要的是调用另一个函数,它的参数也以对象compute
开头。MyClass
如何强制 matlab 调用这个常规函数而不是进入类方法?
3 回答
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:
- Change the function's name.
- Move the function's body to the same script that is calling the function (item 4 on the list above)
- 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.
如果您compute
恰好是 MATLAB 内置程序,则可以使用
builtin('compute', ...)
否则,没有办法 - 见蜜蜂的回答。
如果您迫切需要这个,那么您可以执行以下操作。我强烈建议您不要这样做,并坚持 Bee 的回答。然而,有时一个人别无选择...
这个想法是将您的实例包装在另一个类中,以便 MATLAB 的函数调度看不到该compute
方法。但是,对于您的compute
函数,包装的实例必须与原始实例相同。在某些情况下很难做到这一点,但通常以下内容就足够了:
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
此类包装另一个类的实例并将所有读取权限委托给包装的实例。
例如,如果您有一个名为的文件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
还有一个功能compute.m
:
function compute(x)
fprintf('Regular function! My name is "%s".\n', x.name);
end
然后它像这样工作:
>> 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".
根据compute
函数对您的实例的作用,您可能需要向Wrapper
(例如subsasgn
)添加更多“特殊”函数。另请注意,如果compute
执行一些元类魔法,这将中断。