How do I specify an absolute pathname for a function when using STR2FUNC to capture its handle?

I want to create and use function handles for some of the functions that I have created. These functions are present in several folders and I don't want to add these folders to the MATLAB path. Rather, I wish to use STR2FUNC to capture the handle of the function by specifying its absolute path as follows:
hf = str2func('C:\mFiles\ProjectA1\foo.m');
Although STR2FUNC does create a handle, it does not correctly reference the function and does not evaluate anything.

 Respuesta aceptada

The ability to use absolute path names with STR2FUNC to capture function handles is not available in MATLAB. This is because STR2FUNC requires a valid function name as an input argument and MATLAB does not recognize a path name (absolute or relative) as any kind of a function name.
For example, you cannot execute the HEX2DEC function with arguments by providing the complete path to this function as follows:
>> D:\Applications\MATLAB\R2006a\toolbox\matlab\strfun\hex2dec('8000')
 
??? D:\Applications\MATLAB\R2006a\toolbox\matlab\strfun\hex2dec.m('8000')
|
Error: Unexpected MATLAB operator.
More information is also available in the MATLAB Documentation at the following location:
Create Function Handle
To work around this issue without adding the directory to the path, you can write a simple script that will first change into the directory in which the function is present, using the CD function, and then use STR2FUNC to capture the function handle. Now, if you change out of this directory, the function handle is still valid although the directory is not in the MATLAB path. This is because STR2FUNC captures the absolute location of the function. This is illustrated below in an example in which 'name' is the name of the function (no extension) and 'dirname' is the directory in which this function is present.
oldDir = pwd;
cd(dirname);
h = str2func(name);
cd(oldDir);

Más respuestas (0)

Categorías

Más información sobre Search Path en Centro de ayuda y File Exchange.

Productos

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by