Skip to content

Instantly share code, notes, and snippets.

@andymass
Created October 19, 2016 17:14
Show Gist options
  • Save andymass/3f424c8792de82d433742063d9da6a84 to your computer and use it in GitHub Desktop.
Save andymass/3f424c8792de82d433742063d9da6a84 to your computer and use it in GitHub Desktop.
function h = absolute_handle(s)
% ABSOLUTE_HANDLE Get function handle to a file, not necessarily on path
% H = ABSOLUTE_HANDLE(S) get handle to function or script in file S
[p,n,e] = fileparts(s);
o = cd();
if ~isempty(p)
fu = onCleanup(@() clean(o));
cd(p);
end
f = [fullfile(cd(), n) e];
if ~( exist(f, 'file') == 2 ...
|| (isempty(e) && exist([f '.m'], 'file') == 2) )
error('Could not find file %s', s);
end
h = str2func(n);
try
nargin(h);
catch ME
if ~strcmp(ME.identifier, 'MATLAB:nargin:isScript')
error(ME.message);
end
end
end
function clean(o)
cd(o);
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment