How to find derivatives using the diff command

5 views (last 30 days)
i need to find the derivative of a function fx and fy using the diff commmand wiht my current code i input the function and then just wrote diff(f) yet still getting error is this the correct way to do it where matlab would output the deravative
Find fx and fy using the diff command
Setting these to zero, solve the resulting system of
equations using the solve command
f=@(x,y) 2*x^3*y - y^2 - 3*x*y;
Incorrect number or types of inputs or outputs for function 'diff'.

Answers (3)

Cris LaPierre
Cris LaPierre on 26 Mar 2023
I think this is the page you want:

John D'Errico
John D'Errico on 26 Mar 2023
Edited: John D'Errico on 26 Mar 2023
There are two versions of diff in MATLAB. One operates on numeric vectors and arrays. It simply subtracts each number from the one that follows it. But the numerical diff can be used to approximate a derivative, if you then divide by the stride between numbers. Essentially, you can form an APPROXIMATION to a derivative by dividing a difference in y with a difference in x.
As well, there is a symbolic version of diff. It does compute a derivative, but only of symboic expressions.
However, f is a function handle. Is it either of those two options? Clearly not. It may look vaguely like something you might want to differentiate, but it is not either of those alternatives. Yes, I'll admit it is a subtle difference, but an important one.
The error message generated tells you that a function handle is not an acceptable argument for diff.
As well, even if it was something in symbolic form, would you expect MATLAB to know you want to differentiate with respect to x? Or to y? Which one?
I would suggest you need to form the expression in symbolic form. Then you would compute the pair of derivatives, WRT first x and y, and then do as directed.

Walter Roberson
Walter Roberson on 26 Mar 2023
Edited: Walter Roberson on 26 Mar 2023
It is possible to apply symbolic diff() to a function handle of an anonymous function -- but you have to specifically mention a symbolic variable in the parameters so that MATLAB knows to use symbolic diff() instead of numeric diff()
f=@(x,y) 2*x^3*y - y^2 - 3*x*y;
syms x y
G = [diff(f,x); diff(f, y)]
G = 
Note that this only works for anonymous functions:
diff(@sin, x)
Error using sym>funchandle2ref
Only anonymous functions and functions without arguments can be converted to sym.

Error in sym>tomupad (line 1471)
x = funchandle2ref(x);

Error in sym (line 249)
S.s = tomupad(x);

Error in sym/privResolveArgs (line 1041)
argout{k} = sym(arg);

Error in sym/diff (line 29)
args = privResolveArgs(S, invars{:});


Find more on Mathematics in Help Center and File Exchange


Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by