How to find derivatives using the diff command

29 Ansichten (letzte 30 Tage)
lateef
lateef am 26 Mär. 2023
Bearbeitet: Walter Roberson am 26 Mär. 2023
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;
diff(f)
Incorrect number or types of inputs or outputs for function 'diff'.

Antworten (3)

Cris LaPierre
Cris LaPierre am 26 Mär. 2023
I think this is the page you want: https://www.mathworks.com/help/symbolic/diff.html

John D'Errico
John D'Errico am 26 Mär. 2023
Bearbeitet: John D'Errico am 26 Mär. 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 am 26 Mär. 2023
Bearbeitet: Walter Roberson am 26 Mär. 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{:});

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by