using varfun on a timetable with subscripts?

2 ビュー (過去 30 日間)
Stuart Schady
Stuart Schady 2021 年 6 月 22 日
回答済み: J. Alex Lee 2021 年 6 月 23 日
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?


J. Alex Lee
J. Alex Lee 2021 年 6 月 23 日
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));

その他の回答 (0 件)

Community Treasure Hunt

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

Start Hunting!

Translated by