I have been searching an entire afternoon and have found no solution to call in matlab a function by specifying its path and not adding its directory to the path.
Th
function [varargout]=funeval(fun,varargin)
% INPUT:
% fun: (char) full path to function file
curdir=cd;
[fundir,funname]=fileparts(fun);
cd(fundir);
[varargout{1:nargout}] =feval(funname,varargin{:})
cd(curdir);
The run command can run a script file from any directory, but it can't call a function (with input and output arguments).
Neither feval
nor str2func
permit directory information in the function string.
I suggest writing your own wrapper for str2func
that:
Beware, however, that a handle to a function not in the path is likely to break, because the function will be unable to invoke any helper code stored in other files in its directory.
I've modified Thierry Dalon's code to avoid the use of feval, which I always feel uncomfortable with. Note this still doesn't get around cd-ing to the directory in question, but well, it happens behind the scenes, so pretend it doesn't happen :-) Also note what Ben Voigt pointed out above: calls to helper functions off the path will fail.
function [varargout]=funeval(FunctionHandle, FunctionPath, varargin)
% INPUT:
% FunctionHandle: handle to the function to be called; eg @MyFunction
% FunctionPath: the path to that function
% varargin: the arguments to be passed to Myfunction
curdir=cd;
cd(FunctionPath)
[varargout{1:nargout}] = FunctionHandle(varargin{:});
cd(curdir);
end
and calling it would look like
Output = funeval(@MyFunction, 'c:\SomeDirOffMatlabsPath\', InputArgToMyFunc)
The solution as noted in the comment 1 to create a function handle before calling the function is nicely implemented by @Rody Oldenhuis' FEX Contribution: http://www.mathworks.com/matlabcentral/fileexchange/45941-constructor-for-functionhandles
This is doable, but requires a bit of parsing, and a call to evalin
.
I added (many years ago!) a function to the MATLAB Central File Exchange called externalFcn
http://www.mathworks.com/matlabcentral/fileexchange/4361-externalfcn
that manages calls to off-path functions. For instance, I have a function called offpathFcn
that simply returns a structure with a success message, and the value of an input. Storing that function off my MATLAB path, I can call it using:
externalfcn('out = C:\MFILES_OffPath\offpathFcn(''this is a test'')');
This returns:
out =
success: 1
input: 'this is a test'
(Note that my implementation is limited, and improvable; you have to include an output with an equal sign for this to work. But it should show you how to achieve what you want.)
(MathWorks application engineer)