passing function handle to separate function m-file error
1 view (last 30 days)
Show older comments
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
0 Comments
Accepted Answer
Jan
on 27 Oct 2016
Edited: Jan
on 27 Oct 2016
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 Comment
More Answers (0)
See Also
Categories
Find more on Graph and Network Algorithms in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!