using varfun on a timetable with subscripts?

1 view (last 30 days)
Is it possible to use varfun on a timtable and include subscripts?
Say I have a large timetable of stock prices and wanted to do a simple caluclation on each price element, but the caluclation requires previous elements, is this possible using varfun?
Ideally I want a timetable returned which is why I do not want to use subscripting as it will only return a matrix.
As a simple example, say I wanted the difference between each element and its previous element, using subscript: stocks{2:end, :} - stocks{1: end -1, : }, but I lose the date index as a result. Is there a way to do this in varfun using an anonymous function?

Accepted Answer

J. Alex Lee
J. Alex Lee on 23 Jun 2021
first of all, your operation looks like a "diff", no subscripts (for rows, i.e., timestamps) necessary
second, you will be deficient by 1 row of data after that operation, so how do you expect the result to assigned to timestamps?
third, do you want to append data to your table, or create a new table (with one fewer row)?
stocks = % a timetable with all variables numeric values
VarNames = string(stocks.Properties.VariableNames);
% add fields
for i = 1:numel(VarNames)
var = VarNames(i);
% assign difference to the later timestamp
stocks.(var+"_diff") = [nan;diff(stocks.(var))];
% assign difference to the earlier timestamp
% stocks.(var+"_diff") = [diff(stocks.(var));nan];
% shortcut to create a new table with correct timestamps and variables
stocks_diff = stocks(2:end,:); % assign difference to later timestamp
% stocks_diff = stocks(1:end-1,:); % assign difference to earlier timestamp
for i = 1:numel(VarNames)
var = VarNames(i);
% inplace replacement
stocks.(var) = diff(stocks.(var));

More Answers (0)


Find more on Tables in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!