Gradient Vector for partial derivative seems backward for dfdx
이전 댓글 표시
clc; clear;
xo = 0.8;
yo = 0.2;
%analytic solution
syms f(x,y) %tells matlab to treat f(x) symbolically
f(x,y) = x*exp(-(x^2+y^2));
%Calculate Derivatives
Dfx = diff(f,x); %partial of f w.r.t x
Dfy = diff(f,y); %partial of f w.r.t y
fprintf('Analytic Solutions:\n')
fprintf('Dfx = %9.5f\n',Dfx(xo,yo))
fprintf('Dfy = %9.5f\n',Dfy(xo,yo))
%numerical solution
h = 0.01; %grid size deltax = deltay = 0.01
[nx,ny] = meshgrid(0:h:2); %x and y range from 0 to 2, step size h
z = nx.*exp(-(nx.^2+ny.^2));
%locate index values for xo = 0.8 and yo = 0.2.
nxo = find(nx(1,:)==xo);
nyo = find(ny(:,1)==yo);
Calculate Derivatives
[nDfx, nDfy] = gradient(z,h); %calculate the partials w.r.t x and y
fprintf('Numerical Solutions:\n')
fprintf('Dfx = %9.5f\n',nDfx(nxo,nyo)) %incorrect value
fprintf('Dfx = %9.5f\n',nDfx(nyo,nxo)) %correct value, but why?
fprintf('Dfy = %9.5f\n',nDfy(nxo,nyo))
These are the outputs:
Analytic Solutions:
Dfx = -0.14185
Dfy = -0.16212
Numerical Solutions:
Dfx = 0.46604
Dfx = -0.14180
Dfy = -0.16211
Why must I switch the order for dfdx in order to get the correct result?
채택된 답변
추가 답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Surface and Mesh Plots에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!