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

8 views (last 30 days)
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 Comments
Ameer Hamza
Ameer Hamza on 4 Oct 2020
I am glad that this solved the issue for you. I have added it as an answer too.

Sign in to comment.

Accepted Answer

Ameer Hamza
Ameer Hamza on 4 Oct 2020
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

More Answers (1)

KSSV
KSSV on 4 Oct 2020
ds/dx=-3*x^2+3*y^2
ds/dy = 6*x*y
  1 Comment
esat gulhan
esat gulhan on 4 Oct 2020
I know analtical solution. How can i solve it numerically. I take gradient but it gives wrong result

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!