MATLAB: A class to simulate missing arguments in function calls

classmissing argumentsoop

My goal is to design a class named "Unknown", that simulates missing arguments in function calls.
For example, this script
fun(Unknown)
function fun(a)
a %or any other line of code that includes the "a" variable

end
should produce an error in the same way this script does
fun()
function fun(a)
a %or any other line of code that includes the "a" variable
end
Is there any way of achieving this?
My current, hopeless ideas:
  • Overload some sort of "caller" function in the Unknown class to prevent any MATLAB function to be called on an Unknown object – if that "caller" function exists
  • Apply some strange property to the Unknown class that does what I want

Best Answer

Clearly, I would have to check for each input argument to be ~isempty(), or ~isnan(), which could be another technique. However, in this way, a 1-line function becomes a 5-lines function.
No, it would become at most a 2-line function. You would naturally write a separate check_for_unknowns.m mfunction that checks all the arguments for Unknowns and re-use that utility in every function that needs it:
fun(1, 2, Unknown, 4);
function x = fun(a, b, c, d)
check_for_unknowns(a,b,c,d)
x = a + b + c + d;
end
function check_for_unknowns(varargin)
map=cellfun(@(c)~isa(c,'Unknown'),varargin);
assert(all(map),'Unknown variable type entered');
end
Moreover, anonymous functions, which can only be one-line, would benefit from the usage of such "Unknown" class.
You can extend this idea to anonymous functions by writing the following additional utility mfile,
function varargout=myfeval(funHandle,varargin)
check_for_unknowns(varargin{:})
[varargout{1:nargout}]=feval(funHandle,varargin{:});
end
and now you can do 1-line things like,
>> fun=@(a,b,c,d) a+b+c+d;
>> x=myfeval(fun,1,Unknown,3,4);