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.