taking differences and moving averages

13 ビュー (過去 30 日間)
alpedhuez
alpedhuez 2020 年 5 月 25 日
編集済み: alpedhuez 2020 年 5 月 26 日
I have a spreadsheet with
column 1 =date
column 2 =temperature
I now want to have
column 3 = differences between today's temperature - yesterday's temperature
column 4 = 7 day moving average of column 3
Thank you.

採用された回答

Nicole Peltier
Nicole Peltier 2020 年 5 月 25 日
編集済み: Nicole Peltier 2020 年 5 月 25 日
For column 3, look into diff.
diff(x) = [x(2)-x(1), x(3)-x(2), ...]
Keep in mind that diff will give you a vector with one less item than in columns 2 and 1. So you may want to say something like:
Column3(1) = NaN;
Column3(2:end) = diff(Column2);
To avoid an error, you need to preallocate the size of Column3. If you haven't already, you need a line before the two above that looks like this:
Column3 = nan(length(Column2), 1);
That creates a variable with the number of items that you need. You can then replace values with the ones that you calculate using diff. (If you preallocate values to be NaN, then you actually don't need the line Column3(1)=NaN because it already is NaN.)
For column 4, look into movmean. The following would give you a moving average with a window width of 7:
Column4 = movmean(Column3, 7);
% Moving window is centered on index of input, example below
% Column4(6) = mean(Column4(3:9))
The moving window will be centered on the index of the input (example in comment above). If you want column 4 to represent the average of the last 6 days plus today, you'd want to enter:
Column4 = movmean(Column3, [6, 0]);
Hope this helps!
  4 件のコメント
Nicole Peltier
Nicole Peltier 2020 年 5 月 25 日
I updated my answer above to show you how you can preallocate new. If you don't set the size of the variable, then MATLAB doesn't know what the end element is of your variable new, hence the error.
alpedhuez
alpedhuez 2020 年 5 月 26 日
編集済み: alpedhuez 2020 年 5 月 26 日
new=old;
newcases(1)=NaN;
newcases(2:end)=diff(old);

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeStartup and Shutdown についてさらに検索

タグ

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by