Search code examples
matlabanonymous-functionsymbolic-mathfunction-handle

matlabFunction removes input arguments


I want to calculate the differentiation of a function of two variables. For example:

ax^2 + by^2 + cxy

So I do this:

a = 1
b = 1
c = 1

syms x y f
f = a*x^2 + b*y^2 + c*x*y
df = matlabFunction(diff(f,'x'))

which returns:

df = 
    @(x,y)x.*2.0+y

And it's ok. But if c is zero then it returns this:

df = 
    @(x)x.*2.0

and I can't call it with two arguments anymore but I need to pass two arguments even y is not in the definition anymore since c is not always zero. How can I fix this?


Solution

  • The 'vars' argument to matlabFunction lets you specify the input variables of the generated function:

    >> df = matlabFunction(diff(f,'x'),'vars',[x y])
    
    df = 
    
        @(x,y)x.*2.0