1
votes

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!

2

2 Answers

1
votes

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]
1
votes

the functions function and a quick regex can help you:

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

s = functions(fun) ;
strVar = strsplit( char( regexp(s.function, '\(([^\)]+)\)' , 'tokens' , 'once' )) ,',') ;
nInput = numel(strVar) ;

will get you:

>> strVar
strVar = 
    'x'    'y'    'z'    'w'
>> nInput
nInput =
     4

edit: Many thanks to Luis Mendo's comment.

You will need to add something like:

sym(strVar(:))

to declare them as symbolic variables, or directly:

jacobian(fun, sym(strVar))

to calculate your jacobian.