Azzera filtri
Azzera filtri

function handle does not work

1 visualizzazione (ultimi 30 giorni)
Stefan
Stefan il 27 Set 2011
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

Risposte (2)

Jan
Jan il 27 Set 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

Bjorn Gustavsson
Bjorn Gustavsson il 27 Set 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.

Categorie

Scopri di più su Line Plots in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by