difference between two columns in a table in matlab

You can use the diff function to calculate the difference between two columns in a table.

Suppose you have a table T with columns A and B, and you want to calculate the difference between B and A.

main.m
T = table(rand(5,1), rand(5,1).*10, 'VariableNames', {'A', 'B'});

diff_col = diff(T.B - T.A);
95 chars
4 lines

This will create a new column diff_col with the difference between B and A. The diff function calculates the difference between adjacent elements in the column, so the resulting column will have one fewer element than the original columns.

You can also add the resulting column back to the original table using the addvars function:

main.m
T = addvars(T, diff_col, 'After', 'B', 'NewVariableNames', 'B-A');
67 chars
2 lines

This will add a new variable to T with the name 'B-A', placed after the column 'B'.

Note that the diff function is undefined for the first element of the column, since there is no preceding element to calculate the difference with. Therefore, the resulting column will have a 'missing' value as its first element.

related categories

gistlibby LogSnag