How can i take ds/dx and ds/dy of a function numerically

조회 수: 8 (최근 30일)
esat gulhan
esat gulhan 2020년 10월 4일
댓글: Ameer Hamza 2020년 10월 4일
I tried to take derivatives of s=-x^3+3*x*y^2 numericaly
ds/dx=3*y^2-3*x^2
ds/dy=6*x*y
I tried to gradient of s to find ds/dx and ds/dy but results are far from analtical results. My code is below
clc;clear;
[x y]=meshgrid(0:5,0:5)
s=-x.^3+3.*x.*y.^2
[dsx,dsy]=gradient(s)
dsy should refers ds/dy
0 3 6 9 12 15
0 6 12 18 24 30
0 12 24 36 48 60
0 18 36 54 72 90
0 24 48 72 96 120
0 27 54 81 108 135
ds/dy =6xy analtically
0 0 0 0 0 0
0 6 12 18 24 30
0 12 24 36 48 60
0 18 36 54 72 90
0 24 48 72 96 120
0 30 60 90 120 150
How can i take derivatives numerically in gradient way. where is my fault.
NOTE: It is the simplified example to find the derivatieves numerically. My real project is very complicated and all values in matrices form. So I do not intrested in analtical solutions. It should be solved in numerical. Why gradient results are far away from analtical results how can i solve this numerically.
  댓글 수: 3
esat gulhan
esat gulhan 2020년 10월 4일
Oh yes, the error is step size. thanks
Ameer Hamza
Ameer Hamza 2020년 10월 4일
I am glad that this solved the issue for you. I have added it as an answer too.

댓글을 달려면 로그인하십시오.

채택된 답변

Ameer Hamza
Ameer Hamza 2020년 10월 4일
The numerical gradient can not be exactly equal to the analytical gradient, except in very simple cases. For any nonlinear function, there will be a huge difference between both. There is no way around except using a very small step size, which will decrease the difference beween analytical and numerical gradient. For example:
If step size is 1
[x, y] = meshgrid(0:5,0:5);
s = -x.^3+3.*x.*y.^2;
[~, dsy] = gradient(s, 1, 1);
err = mean((dsy - 6.*x.*y).^2, 'all') % mean squared error
Result
>> err
err =
27.5000
If step size is 0.1
[x, y] = meshgrid(0:0.1:5,0:0.1:5);
s = -x.^3+3.*x.*y.^2;
[~, dsy] = gradient(s, 0.1, 0.1);
err = mean((dsy - 6.*x.*y).^2, 'all') % mean squared error
Result
>> err
err =
0.0297

추가 답변 (1개)

KSSV
KSSV 2020년 10월 4일
ds/dx=-3*x^2+3*y^2
ds/dy = 6*x*y
  댓글 수: 1
esat gulhan
esat gulhan 2020년 10월 4일
I know analtical solution. How can i solve it numerically. I take gradient but it gives wrong result

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Surface and Mesh Plots에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by