Adding a new column of differences to a table

17 ビュー (過去 30 日間)
Stef1998
Stef1998 2021 年 11 月 21 日
回答済み: Peter Perkins 2021 年 11 月 23 日
Hi I have a table T of values - 17520x3, the first column is date/time data (A), the second (B) and third (C) are numbers.
I would like to create 2 new columns that show the difference between each consecutive row in column B and C.
I keep getting an error because the number of rows in the table do not match now. The diffB and diffC columns will always have 1 less.
Is there a way to fix this error?
I would like the output to look like this:
A B C diffB diffC
10/10/2001 3 5 0 0
10/10/2001 5 30 2 25
10/10/2001 10 50 5 20
T = readtable(datafile.csv)
array2table(T, 'VariableNames', {'A', 'B', 'C'})
[T array2table(diff(T{:,{'B','C'}}),'VariableNames',{'diffB','diffC'})];

採用された回答

David Hill
David Hill 2021 年 11 月 21 日
[T array2table([0,0;diff(T{:,{'B','C'}})],'VariableNames',{'diffB','diffC'})];
  1 件のコメント
Stef1998
Stef1998 2021 年 11 月 22 日
thank you so much!

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

その他の回答 (1 件)

Peter Perkins
Peter Perkins 2021 年 11 月 23 日
Even simpler:
T.diffB = [0;diff(T.B)];
T.diffC = [0;diff(T.C)];
David's soln has the advantage of being easier to write when there are a zillion variables. Here's a slightly more succinct version of it:
>> T = array2table([3 5; 5 30; 10 50],"VariableNames",["B" "C"])
T =
3×2 table
B C
__ __
3 5
5 30
10 50
>> T{2:end,["diffB" "diffC"]} = diff(T{:,1:2})
T =
3×4 table
B C diffB diffC
__ __ _____ _____
3 5 0 0
5 30 2 25
10 50 5 20

カテゴリ

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

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by