MATLAB: Abstract class using implemented methods

abstractclassMATLABoop

Hello,
I have a superclass:
classdef Dic
methods (Access = protected, Static = true, Abstract)
value = fun1(F,~)
value = fun2(~,G)
end
methods (Static = true)
function r = Calculation(F,G)
r = fun1(F) + fun2(G);
end
end
end
Which has the implemented Function Calculation and 2 abstract functions fun1 and fun2.
classdef Zsd < Dic
methods (Access = protected, Static = true, Abstract = false)
function value = fun1(F,~)
value = F - mean2(F);
end
function value = fun2(~,G)
value = G - mean2(G);
end
end
end
In the second class I implement fun1 and fun2, now if I call:
Zsd.Calculation(magic(4), magic(4))
I get the following error:
Undefined function or variable 'fun1'.
Can someone help me?

Best Answer

Your functions are all static so they have no object scope. To override base class functions and have the code call the version on the relevant derived class it needs to be a non-static function so that it takes the object as an argument to give it the scope for the function it is calling.
Also, to call a static function, even within a class, you have to give the class scope at the front. This is where your problem comes, because you are in your base class so you can't give the derived class scope for calling fun1 because the base class doesn't (or shouldn't) know about its derived classes and if it were to call this function with specific class scope from a derived class there would be no point having the function in the derived class - it might as well be in the base class.
Make your functions non-static so they take the object as an argument which will give it the scope it needs to know which versions of the functions to call. Also why do you have ~ in your function signatures? They don't seem to make any sense in this context.
classdef Dic
methods (Access = protected, Abstract)
value = fun1(obj,F)
value = fun2(obj,G)
end
methods
function r = Calculation(obj,F,G)
r = obj.fun1(F) + obj.fun2(G);
end
end
end
and
classdef Zsd < Dic
methods (Access = protected, Static = true, Abstract = false)
function value = fun1(obj,F)
value = F - mean2(F);
end
function value = fun2(obj,G)
value = G - mean2(G);
end
end
end
should work, although it was a quick edit so I may have made an error.
If you wish, you can replace the obj by ~ in the derived class fun1 and fun2 function signatures as this is unused within that function. It is required though for the above-mentioned reason, so that the call in Calculation knows where to call fun1.