# MATLAB: Error creating a function handle using str2func in a function

dynamic programmingfunction handleMATLABstr2func

I have been having trouble using STR2FUNC to make a function handle for a string name in a function. It works properly if I add a break point and evaluate the same portion of code at the command line.
This problem comes about because I have created a number of different folders and generate functions of the same name in each folder (i.e FreeEnergy-> COg.m,CO2g.m ; Enthalpy-> COg.m, CO2g.m; Entropy-> COg.m, CO2g.m).
Each function each folder has different code, so I am trying to make a function handle to each and store it in a structure. I first switch the directory to the proper directory and use STR2FUNC to generate the function handle.
Example Code (in function file): cdir = pwd; …
cd([cdir 'FreeEnergy'])res(i).G=str2func(name);functions(res(i).G)
Example Output:
 function: 'COg' type: 'simple' file: ''
However, if I was to highlight "res(i).G=str2func(name); functions(res(i).G)" and evaluate it at the command line then it adds in the proper file path
 Example Output: function: 'COg' type: 'simple' file: 'C:Users\Joe\Documents\Matlab\FreeEnergy\COg.m'
The second is the proper output and does not generate unless I evaluate at the command line. I have no idea why this is happening. Is it a bug? If I was to run the same function again then it will also work properly, but involves a lot of time overhead for creating the individual function code from their symbolic variables. Any suggestions would be appreciated.

function gencodef=fopen('newcode.m','w');fprintf(f,'function newcode\n');fclose(f);hf1=@newcode;exist('newcode','file');hf2=@newcode;functions(hf1)functions(hf2)delete newcode.m
>> gencode
    function: 'newcode'        type: 'simple'        file: ''
    function: 'newcode'        type: 'simple'        file: 'h:\temp\newcode.m'