필터 지우기
필터 지우기

function handle does not work

조회 수: 2 (최근 30일)
Stefan
Stefan 2011년 9월 27일
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일
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일
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.

카테고리

Help CenterFile Exchange에서 Graphics Performance에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by