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

 採用された回答

John D'Errico
John D'Errico 2022 年 1 月 19 日
編集済み: John D'Errico 2022 年 1 月 19 日

2 投票

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 件のコメント

Clueless
Clueless 2022 年 1 月 19 日
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] ?

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeMathematics についてさらに検索

製品

質問済み:

2022 年 1 月 19 日

コメント済み:

2022 年 1 月 19 日

Community Treasure Hunt

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

Start Hunting!

Translated by