using varfun on a timetable with subscripts?

2 visualizzazioni (ultimi 30 giorni)
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?

Risposta accettata

J. Alex Lee
J. Alex Lee il 23 Giu 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];
end
% 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));
end

Più risposte (0)

Categorie

Scopri di più su Tables in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by