Numeric derivative with multiple variables
20 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hello,
given a function f = @(a) [exp(a(1)) - exp(a(2))] with a= [0,0 ]I want to calculate the numeric deriative based on (f(a+h) - f(a-h)) / (2*h);
Calling f(a+h) results in the function getting evaluated with both a values.
But what I want is extracting the result of the first a(1) and a(2) in two different calls.
How can this be achieved?
Thanks in advance
0 commentaires
Réponse acceptée
John D'Errico
le 19 Jan 2022
Modifié(e) : John D'Errico
le 19 Jan 2022
Here is a simple trick to remember. See how I used da1 and da2 below.
f = @(a) sin(a(1)) + cos(a(2)) + a(1) - 2*a(2);
a0 = [1 3];
h = 1e-8;
da1 = [1 0];
da2 = [0 1];
format long g
(f(a0 + da1*h) - f(a0 - da1*h))/(2*h) % numerical partial drivative df/dx
(f(a0 + da2*h) - f(a0 - da2*h))/(2*h) % numerical df/dy
Are those partial derivatives correct? We can check them, by an analytical computation.
syms x y
subs(diff(f([x,y]),x),[x,y],[1 3]) % analytical derivative wrt x, at the point (1,3)
vpa(ans)
Looks good to me.
subs(diff(f([x,y]),y),[x,y],[1 3]) % analytical derivative wrt y
vpa(ans)
The numerical finite difference seems to have worked well enough. They are not exact, but h was only 1e-8. That is about what I would expect for accuracy from a central finite difference approximation.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Number Theory dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!