function handle does not work

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

回答 (2 件)

Jan
Jan 2011 年 9 月 27 日

0 投票

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 2011 年 9 月 27 日

0 投票

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.

カテゴリ

ヘルプ センター および File ExchangeGet Started with MATLAB についてさらに検索

質問済み:

2011 年 9 月 27 日

Community Treasure Hunt

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

Start Hunting!

Translated by