Search code examples
matlabfunctionargumentshandle

How to get arglist from a function handle?


I have the following function handle

 fun = @(x,y,z)[x.^3+y.^2+z.^2,x.^2-y.^3+sin(z)]

And now I am using the function

jacobian(fun, [x,y,z])

which returns the jacobian of the function. To use this function I first need to define

syms x y z. 

If the function changes to

@(x,y,z,w)[x.^3+y.^2+z.^2+w,x.^2-y.^3+sin(z)+w] 

the jacobian is returned by

jacobian(fun, [x,y,z,w]). 

Now I don't want to change the second input argument of the jacobian manually. Is there a function in Matlab, that looks at the function handles and returns them, or returns how many there are?

Many thanks!


Solution

  • You can do it this way:

    str = func2str(fun); %// get fun's defining string
    str = regexp(str, '^@\([^\)]+\)', 'match'); %// keep only "@(...)" part
    vars = regexp(str{1}(3:end-1), ',', 'split'); %// remove "@(" and ")", and  split by commas
    jacobian(fun, sym(vars)); %// convert vars to sym and use it as input to jacobian
    

    Example:

    >> clear all
    >> syms r s t
    >> fun = @(r,s,t) [r*s^t r+s*t]
    fun = 
        @(r,s,t)[r*s^t,r+s*t]
    >> str = func2str(fun);
       str = regexp(str, '^@\([^\)]+\)', 'match');
       vars = regexp(str{1}(3:end-1), ',', 'split');
       jacobian(fun, sym(vars))
    ans =
    [ s^t, r*s^(t - 1)*t, r*s^t*log(s)]
    [   1,             t,            s]