function handle does not work
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hello,
I started to work with function handles. But now I need some help to fix the problem in order to run the following code:
%Test for fhandle
for iTest = 1:3
%Create m-function
functionName = ['fHandleTest_',num2str(iTest),'.m'];
[fid,message] = fopen(functionName,'w');
fprintf(fid, 'function Output = Test(x)\n');
fprintf(fid, 'Output = x; \n');
fclose(fid);
%Execute function
fhandle = str2func(functionName(1:end-2));
out = fhandle(iTest)
end;
The following error occurs when I was running that code:
Undefined function 'fHandleTest_1' for input arguments of type 'double'.
Error in fHandleTest (line 14)
out = fhandle(iTest)
Besgt regards Stefan
0 commentaires
Réponses (2)
Jan
le 27 Sep 2011
The dynamic creation of M-files is not trivial, because MATLAB does not parse the folders during execution automatically. So you have to triggfer this time-consuming procedure manually:
% Test for fhandle
for iTest = 1:3
%Create m-function
functionName = ['fHandleTest_', num2str(iTest), '.m'];
[fid,message] = fopen(functionName,'w');
fprintf(fid, 'function Output = Test(x)\n');
fprintf(fid, 'Output = x; \n');
fclose(fid);
%Execute function
fhandle = str2func(functionName(1:end-2));
rehash; % <==
% Faster alternative:
% clear(functionName(1:end-2))
out = fhandle(iTest)
end
0 commentaires
Bjorn Gustavsson
le 27 Sep 2011
For clarity and reduced confusion I suggest that you also name the funtion with the same name as the file. That is change:
fprintf(fid, 'function Output = Test(x)\n');
to:
fprintf(fid, 'function Output = fHandleTest_', num2str(iTest),'(x)\n');
Whenever I've taken shortcuts like that I've been bitten by it later.
0 commentaires
Voir également
Catégories
En savoir plus sur Graphics Performance dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!