필터 지우기
필터 지우기

passing function handle to separate function m-file error

조회 수: 3 (최근 30일)
James506
James506 2016년 10월 27일
댓글: Rogge Zheng 2020년 10월 4일
Hi,
I have a function (function-1) which passes a function handle of the form:
fhandle = @fun; % step-1
to a function in a separate m-file (function-2). I invoke this function handle in function-2 using:
res = feval(fhandle, ...); % step-2
where the function in 'fhandle' is defined as a separate non-nested function within the function-2 m-file (function-2-1). However, this gives the following error:
"Undefined function 'fun' for input arguments of type 'double'."
I have also tried invoking the function handle directly, which also gives the same error:
res = fhandle(...); % step-2-v.2
This is odd, as if I go into function-2 in debug mode and re-enter the code in step-1 again, and then re-run step-2 and step-2-v.2, it seems to evaluate the function just fine. A work-around I have found is by defining the function handle as a string:
fhandle = 'fun'; % step-1-v.2
which seems to work fine. However, I have read that it is better practice to use the function handle form @, rather than passing a string. Could this be a bug or am I missing something?
Thanks

채택된 답변

Jan
Jan 2016년 10월 27일
편집: Jan 2016년 10월 27일
Thjis is the expected behavior. "fhandle = @fun" runs inside the function 1. There the functions, which are defined inside function 2, are unknown and therefore @fun is invalid. Of course @fun is valid, when you run the debugger and are inside function 2 already.
Summary: You can create function handles only to functions, which are currently visible.
Solution: Use another method to tell function 2 which subfunction should be used:
function [out] = function2(Fcn, Data)
% Fun: String to specify the subfunction:
switch lower(Fcn)
case 'fcn1'
fhandle = @fcn1;
case 'fcn2'
fhandle = @fcn2;
otherwise
error('Unknown function: %s', Fcn);
end
plot(1:10, fhandle(1:10));
end
function y = fcn1(x)
y = sin(x);
end
function y = fcn2(x)
y = cos(x);
end
Alternatively:
Create M-files for the sub-functions. Then their handles are visible from anywhere.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Graph and Network Algorithms에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by