Adding a new column of differences to a table

17 vues (au cours des 30 derniers jours)
Stef1998
Stef1998 le 21 Nov 2021
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'})];

Réponse acceptée

David Hill
David Hill le 21 Nov 2021
[T array2table([0,0;diff(T{:,{'B','C'}})],'VariableNames',{'diffB','diffC'})];

Plus de réponses (1)

Peter Perkins
Peter Perkins le 23 Nov 2021
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

Catégories

En savoir plus sur Tables dans Help Center et File Exchange

Produits


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by