Adding a new column of differences to a table
10 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Stef1998
am 21 Nov. 2021
Beantwortet: Peter Perkins
am 23 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'})];
0 Kommentare
Akzeptierte Antwort
David Hill
am 21 Nov. 2021
[T array2table([0,0;diff(T{:,{'B','C'}})],'VariableNames',{'diffB','diffC'})];
Weitere Antworten (1)
Peter Perkins
am 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
0 Kommentare
Siehe auch
Kategorien
Mehr zu Tables finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!