Second Derivative using diff

357 ビュー (過去 30 日間)
Claire
Claire 2015 年 4 月 9 日
コメント済み: Victor Quezada 2020 年 5 月 19 日
I have a quick question concerning second derivatives using the diff function.
So, after I put in my x and y arrays I did
y1=diff(y)./diff(x)
I know that I have to change the length of y1 to take the second derivative. But I'm not sure in which order it should go. Should it be:
y1=[0 y1]
or
y1=[y1 0]
Then I would proceed to do
y2=diff(y1)./diff(x)
Any help is greatly appreciated! Thank you!
  1 件のコメント
Victor Quezada
Victor Quezada 2020 年 5 月 19 日
Hi,
I'm coming from the future (from the coronavirus-age, actually). Sorry for being late.
Try: (just a suggestion)
diff(diff(y)./diff(x))./diff(x(1:length(x)-1))
or
diff(diff(y)./diff(x))./diff(x(2:length(x)))
Ciao.

サインインしてコメントする。

採用された回答

Star Strider
Star Strider 2015 年 4 月 9 日
I wouldn’t use diff to calculate numerical derivatives. It has its uses, but I always use the gradient function for derivative calculations, since gradient produces a result the same size as its argument.
  2 件のコメント
Star Strider
Star Strider 2015 年 4 月 9 日
Claire’s Answer moved here...
But if I had to use diff for a certain problem, how would I go about this? (The problem specifies to use diff)
Star Strider
Star Strider 2015 年 4 月 9 日
I wouldn’t zero-pad it if you’re using it to calculate a numerical derivative, and for that matter you don’t have to since both ‘diff(y)’ and ‘diff(x)’ are going to be the same lengths. You have to live with the fact that the calculation using diff is going to be shorter than the original vectors. (You would have to zero-pad both at the same location. That would create a NaN value where both were zero. So you can pad with NaN values or use interp1 with the 'extrap' option if you wanted the derivative vectors to be the same lengths as the original vectors.)
For the second derivative, just go directly to it:
x = randi(10, 1, 10);
y = randi(10, 1, 10);
d2ydx2 = diff(y,2)./diff(x,2);

サインインしてコメントする。

その他の回答 (1 件)

Sanskruti Sawant
Sanskruti Sawant 2018 年 1 月 30 日
1/x

カテゴリ

Help Center および File ExchangeMathematics についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by