Adding a new column of differences to a table

17 次查看(过去 30 天)
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 个)

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 CenterFile Exchange 中查找有关 Tables 的更多信息

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by