How can i take ds/dx and ds/dy of a function numerically
8 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
esat gulhan
il 4 Ott 2020
Commentato: Ameer Hamza
il 4 Ott 2020
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 Commenti
Ameer Hamza
il 4 Ott 2020
I am glad that this solved the issue for you. I have added it as an answer too.
Risposta accettata
Ameer Hamza
il 4 Ott 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
0 Commenti
Più risposte (1)
Vedere anche
Categorie
Scopri di più su Surface and Mesh Plots in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!