function REAL_FN(varargin) %REAL_FN mark functions that should only output real numbers % % Example usage: % REAL_FN log log10 % or % REAL_FN('log', 'log10') % % Either of these lines of code will mean that calling log or log10 from the % current workspace will result in an error if non-real numbers result. This is % like doing: "log = @reallog", but can be applied to any function (there is no % "reallog10" built into Matlab). % % Simply clear the variables that this function produces to remove its effect % from builtins: % % clear log log10 % % This command can be applied to function handles as well as builtins. If % applied to function handles, keep a copy of the originals if you need to % reinstate them. % % This adds overhead to all calls of the affected functions. % It's intended for debugging only. % Iain Murray, November 2009 for ff = varargin fn_name = ff{1}; if ~ischar(fn_name) error(sprintf(['REAL_FN expects string arguments. Use one of:\n',... ' REAL_FN func1 func2 ...\n',... ' REAL_FN(''func1'', ''func2'', ...)'])); end if evalin('caller', ['exist(''', fn_name, ''', ''var'')']) % function is a function handle in the caller. fn = evalin('caller', fn_name); else % function in the caller is an m-file, mex-file, pcode, ... fn = evalin('caller', ['@', fn_name]); end assignin('caller', fn_name, @(varargin) real_checker(fn, fn_name, varargin{:})); end function varargout = real_checker(fn, fn_name, varargin) varargout = cell(1, max(1, nargout)); [varargout{:}] = fn(varargin{:}); for ii = 1:numel(varargout) if isnumeric(varargout{ii}) && ~isreal(varargout{ii}) error(['Unwanted complex result from ''', fn_name, ''' detected.']); end end