passing function handle to separate function m-file error

1 回表示 (過去 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.
  1 件のコメント
Rogge Zheng
Rogge Zheng 2020 年 10 月 4 日
Thank you, great explanation, solved my problem!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeJust for fun についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by