필터 지우기
필터 지우기

problem with numerical derivative using gradient function

조회 수: 7 (최근 30일)
Kobi
Kobi 2015년 4월 15일
댓글: Michael Mauersberger 2020년 4월 30일
while using gradient i encounter a phenomenon that i cannot explain, as you can see from the example below
a=[1 2 7 9;
9 8 4 1;
1 2 3 7]
gradient(a)
ans =
1.0000 3.0000 3.5000 2.0000
-1.0000 -2.5000 -3.5000 -3.0000
1.0000 1.0000 2.5000 4.0000
i get this weird 3.5 value that is not expected all i need's a simple derivative that subtract one value with another similar to the diff function where i get this result
a=[1 2 7 9;
9 8 4 1;
1 2 3 7]
diff(a)
ans =
8 6 -3 -8
-8 -6 -1 6
the problem with diff is that i don't get the same matrix size

답변 (1개)

Star Strider
Star Strider 2015년 4월 15일
You’re only getting half the information that gradient is calculating.
Use this to get the gradient in the default (horizontal, along rows) direction as well as the vertical (along columns) direction:
[dadx,dady] = gradient(a)
The diff function takes the difference in the first dimension >1 by default. (You can specify a different dimension as the third argument.) So if a matrix, it will take the differences between rows (along columns) by default.
So if you want the output of gradient to correspond with the default output of diff, use the second output of gradient, here ‘dady’ in my code.
  댓글 수: 3
Star Strider
Star Strider 2015년 4월 15일
No, there is nothing suspicious about the gradient function. (See the documentation — doc gradient — for the algorithm it uses.) It produces an accurate numerical derivative, not simply the difference between adjacent elements as diff does. If there is a specific, constant, spacing between the elements in each direction that you want to provide, gradient will use them rather than the default spacing of 1.
Michael Mauersberger
Michael Mauersberger 2020년 4월 30일
I agree. Furthermore gradient calculates mean values of neighbouring differences. That is why you get a .5 value. All is written in the doc.

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

카테고리

Help CenterFile Exchange에서 Numerical Integration and Differentiation에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by