Reputation: 39
I need to create a function f
with another function, g
, as argument (g
is defined in a .m
file, not inline
). In the body of f
, I need to use feval
to evaluate g
on multiple values; something like:
function y = f(a,b,c,g)
z=feval(g,a,b,c);
y=...
end
What is the syntax ? I tried to use handles, but I got error messages.
Upvotes: 1
Views: 103
Reputation: 112759
You can do it this way:
Define f
in an m-file:
function y = f(a,b,c,g)
y = feval(g,a,b,c);
end
Define g
in an m-file:
function r = g(a,b,c)
r = a+b*c;
end
Call f
with a handle to g
:
>> f(1,2,3,@g)
ans =
7
Upvotes: 2
Reputation: 73444
If you do not want to change the body of add
, then you could do that:
function s = add_two(a)
s = a + 2;
end
function s = add_three(a)
s = a + 3;
end
function s = add(a, fhandle1, fhandle2)
s = feval(fhandle1, a);
s = s + feval(fhandle2, s);
end
a = 10;
fhandle1 = @add_two; // function handler
fhandle2 = @add_three;
a = add(a, fhandle1, fhandle2);
a
Upvotes: 1