Numeric derivative with multiple variables

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

 Accepted Answer

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
ans =
1.54030233012747
(f(a0 + da2*h) - f(a0 - da2*h))/(2*h) % numerical df/dy
ans =
-2.14111999241595
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)
ans = 
vpa(ans)
ans = 
1.540302305868139717400936607443
Looks good to me.
subs(diff(f([x,y]),y),[x,y],[1 3]) % analytical derivative wrt y
ans = 
vpa(ans)
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.

1 Comment

Thank you John for the answer.
How exactly does da1 & da2 work in this example? If i have a(3) would I achieve this by da3 = [0 0 1] ?

Sign in to comment.

More Answers (0)

Categories

Find more on Mathematics in Help Center and File Exchange

Products

Asked:

on 19 Jan 2022

Commented:

on 19 Jan 2022

Community Treasure Hunt

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

Start Hunting!