Iterating through Matlab Table

3 Ansichten (letzte 30 Tage)
Metin Akyol
Metin Akyol am 24 Feb. 2022
Kommentiert: Metin Akyol am 25 Feb. 2022
I have a simple Matlab table with dates and 2 additional columns that contain numbers and strings. The dates are NOT daily, that is sometimes multple days are missing.
I would like to forward fill the table such that the table becomes a daily table and for each day that is missing, the rows from the previous date are copied.

Akzeptierte Antwort

KSSV
KSSV am 24 Feb. 2022
LEt T be your table. With first column as dates.
% First make the dates daily
thedates = T.(1) ; % existing dates of the table
thedates_new = (thedates(1):thedates(2))' ; % Make daily dates
% GEt the existing dates indices
[idx,ia] = ismember(thedates_new,thedates) ;
C2 = T.(2) ; % second column of table
C2_new = NaN(size(thedates_new)) ;
C2_new(idx) = C2;
C2_new = fillmissing(C2_new) ;
T_new = table(thedates_new,C2_new) ;
Alternatively you may have a look on the function retime

Weitere Antworten (2)

Seth Furman
Seth Furman am 25 Feb. 2022
timetable has a retime method that supports resampling by copying the previous value.
tt = timetable(datetime(2020,1,[1;3;4;7;9]), [1;3;4;7;9])
tt = 5×1 timetable
Time Var1 ___________ ____ 01-Jan-2020 1 03-Jan-2020 3 04-Jan-2020 4 07-Jan-2020 7 09-Jan-2020 9
retime(tt, "daily", "previous")
ans = 9×1 timetable
Time Var1 ___________ ____ 01-Jan-2020 1 02-Jan-2020 1 03-Jan-2020 3 04-Jan-2020 4 05-Jan-2020 4 06-Jan-2020 4 07-Jan-2020 7 08-Jan-2020 7 09-Jan-2020 9

Arif Hoq
Arif Hoq am 24 Feb. 2022
date = {'2014-05-20';'2014-05-21';'2014-05-22';'2014-05-24';'2014-05-25'}; % define the date
name = {'Sanchez';'Johnson';'Li';'Diaz';'Brown'}; % define the string
age = [38;43;38;40;49]; % define the numerical
T=table(date,name,age) % make a table
T = 5×3 table
date name age ______________ ___________ ___ {'2014-05-20'} {'Sanchez'} 38 {'2014-05-21'} {'Johnson'} 43 {'2014-05-22'} {'Li' } 38 {'2014-05-24'} {'Diaz' } 40 {'2014-05-25'} {'Brown' } 49
idx = diff(datenum(T.date, 'yyyy-mm-dd')).'==1; % return the missing date
idx2=find(idx==0); % missing date index
newdate=[T.date(1:idx2);T.date(idx2);T.date(idx2+1:end)]; % concatenate the date
newname=[T.name(1:idx2);T.name(idx2);T.name(idx2+1:end)]; % concatenate the name
newage=[T.age(1:idx2);T.age(idx2);T.age(idx2+1:end)]; % concatenate the age
newTable=table(newdate,newname,newage) % newtable
newTable = 6×3 table
newdate newname newage ______________ ___________ ______ {'2014-05-20'} {'Sanchez'} 38 {'2014-05-21'} {'Johnson'} 43 {'2014-05-22'} {'Li' } 38 {'2014-05-22'} {'Li' } 38 {'2014-05-24'} {'Diaz' } 40 {'2014-05-25'} {'Brown' } 49

Tags

Produkte


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by