Search code examples
stringmatlabderivative

derivative function in string in matlab


I want to derivative a function that has given to me in a sting format in MATLAB. for example the input f = 'x^2' is given to me. how can I derivative f to get the answer '2*x' ? note : I am using MATLAB 2015a.


Solution

  • If you have the Symbolic Math Toolbox, it's very simple:

    f=sym('x^2');
    df=diff(f)
    

    Output:

    >>  diff(sym('x^2'))
    
        ans =
    
        2*x
    

    This will work as long as your symbolic function has a single non-numeric variable in it.

    If you don't have symbolic math, then it's a quite different situation...