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개)

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