4

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?

Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
soroosh.strife
  • 1,181
  • 4
  • 19
  • 45
  • Can't you define `a`, `b`, and `c` as `syms a b c` instead of numeric values? That way you have a general solution – Luis Mendo May 27 '14 at 16:52
  • You're right hadn't thought of that. But isn't there a way that doesn't need adding extra inputs to the function. I don't need those coefficients later on but this way I will have to keep them around every where I use this function handle (this function handle is the return value of another function) – soroosh.strife May 27 '14 at 16:56
  • I think I found a way. Plase see answer – Luis Mendo May 27 '14 at 16:58
  • 1
    Another way may be to evaluate the function using [subs](http://www.mathworks.se/help/symbolic/subs.html) as `df = diff(f,x); result = subs(df,{x,y},{7,2})` which should not fail if substituting variables no longer present in the symbolic function. Sadly I don't have matlab handy to check, but works in octave. – Joachim Isaksson May 27 '14 at 17:05

1 Answers1

4

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
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147