Help us understand the problem. What is going on with this article?

中心差分の効率良い書き方 in pandas/matlab/numpy

pandas版

pandasには差分を出す関数diffが用意されているが,物理量の離散的な微分値を考えた場合これは全く推奨できない。

多少マシな中心差分はshiftをうまく使えば以下のようにスマートに書ける。

cdiff=(data.shift(-1)-data.shift(1))/2/dt

Sampling時間の考慮,NaNの処理も含めて関数化した結果が以下のようになる。

def centerdiff(data,dt=1):
    cdiff=(data.shift(-1)-data.shift(1))/2/dt
    return cdiff.fillna(method='ffill').fillna(method='bfill')

matlab版(numpyでも可)

この場合スライシングを使って計算するのが良いと思われる。

function cdiff = centerdiff(data,dt)
  cdiff_ = (data(3:end)-data(1:end-2)) /2/dt;
  cdiff = [cdiff_(1) ,cdiff_, cdiff_(end)];
end

より高次の処理にも応用可能なのでひとまず覚えておいて損はないはず。

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away