1

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.

2 Answers 2

2

You can do it this way:

  1. Define f in an m-file:

    function y = f(a,b,c,g)
        y = feval(g,a,b,c);
    end
    
  2. Define g in an m-file:

    function r = g(a,b,c)
        r = a+b*c;
    end
    
  3. Call f with a handle to g:

    >> f(1,2,3,@g)
    ans =
         7
    
Sign up to request clarification or add additional context in comments.

Comments

1

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

4 Comments

Ok, but then with your solution if I want to change the argument of add, I need to rewrite add.
@Gonzague, I included an example with eval and a function handler. Hope it helps.
Yes, for example if I want to use add_four and add_five instead of add_two and add_three, then I need to change acordingly in the body of add.
@Gonzague sorry for not getting that by the first moment, edited!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.