Search code examples
matlabsymbolic-mathevaluationderivativefunction-call

Evaluating a symbolic function


I want to find cos(5). Why is this expression invalid:

syms x
f=sin(x)
disp(diff(f)(5))

The error is

Line: 3 Column: 12
Indexing with parentheses '()' must appear as the last operation of a valid indexing expression.

Solution

  • Your error has nothing to do with symbolic variables.

    It is caused by the statement diff(f)(5) - which is not something MATLAB syntax allows (as of R2019b). MATLAB interprets this as the user trying to access the 5th element of some intermediate result. If you want to know the actual value of the derivative of f at x=5, you would have to substitute the desired value of x (using subs) and convert this to some numeric format (such as double):

    syms x
    f = sin(x)
    disp(double(subs(diff(f),x,5))) % substitute x and convert to double