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

7 次查看(过去 30 天)
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 个评论
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 中查找有关 Interpolation 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by