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일
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 Exchange에서 Mathematics에 대해 자세히 알아보기

제품

질문:

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