function handle does not work
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(2 个)
Jan
2011-9-27
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 个评论
Bjorn Gustavsson
2011-9-27
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Line Plots 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!