필터 지우기
필터 지우기

calling gradient multiple times

조회 수: 3 (최근 30일)
Jiawei Gong
Jiawei Gong 2019년 11월 6일
댓글: darova 2019년 11월 6일
MATLAB suggests not to call gradient multiple times, but I did it for sin function. As shown in the figure, the first order derivative is fine, the second has one boundary point off, and the third two points off. I really appreciate if someone can quantatively explain it from the mathematical point of view.
h = .1; % time step
t = 0:h:10; % time array
y = sin(t); % sin function
dy = gradient(y,h);
ddy = gradient(dy,h);
dddy = gradient(ddy,h);
plot(t,[y;dy;ddy;dddy]);

채택된 답변

darova
darova 2019년 11월 6일
It's because of calculation first and last point. gradient does it this way:
first_grad = (y2-y1)/dx;
second_grad = 1/2*(y4-y3)/dx + 1/2*(y3-y2)/dx;
third_grad = 1/2*(y5-y4)/dx + 1/2*(y4-y3)/dx;
%% ...
last_grad = (ylast-ylast_1)/dx;
BLack curve and black points is your original data. Red points are points where gradient/derivative is calculated. Pay attention that first and last points are not at the beginning and end
321.png
Second time you use gradient you use the same step (again). But for the first and last points step/2 should be used.
Interesting fact
If you have not regular step (h is not equal) gradient can't handle it. Better use diff
% generate some data
x = sort(10*rand(100,1));
y = sin(x);
dy1 = gradient(y,x);
dy2 = diff(y)./diff(x);
x2 = x(2:end)-diff(x)/2; % actual x for diff/derivative
plot(x,y) % original data
hold on
plot(x,dy1,'g') % derivative obtained with gradient
plot(x2,dy2,'.m') % derivative obtained with diff
plot(x,cos(x),'k') % exact derivative
hold off
legend('orignal data','gradient','diff','exact')
  댓글 수: 4
Jiawei Gong
Jiawei Gong 2019년 11월 6일
Thank you, I got your idea. It was caused by inconsisently using forward, central, and backward scheme. I did some derivation; it shows the issue was brought from an introduced term of truncation error.
Substituing Eqs.(1) and (2) into (3) yields
darova
darova 2019년 11월 6일
Don't know what you are talking about =)

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Line Plots에 대해 자세히 알아보기

제품


릴리스

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by