Changing the values of a column in a table.

3 views (last 30 days)
If I have a table ..datafi{1}.. and I want to change the time column, t, from all the times being different to all the times being the same time as the first time listed in the column, how do I do that in Matlab?

Answers (1)

per isakson
per isakson on 28 Jan 2021
Edited: per isakson on 28 Jan 2021
This statement does it
tbl.t = tbl.t(ones(height(tbl),1)); % once refered to as "Tony's trick"
Example:
%% Create a sample table
t = datetime('now');
t.Format = t.Format + ".SSSS";
x = (1:5).';
t = sort(t + seconds(5*randn(5, 1)));
tbl = timetable(t,x)
%% Change the time column
tbl.t = tbl.t(ones(height(tbl),1));
tbl
Output
tbl =
5×1 timetable
t x
_________________________ _
28-Jan-2021 11:19:16.7425 1
28-Jan-2021 11:19:23.1767 2
28-Jan-2021 11:19:27.0657 3
28-Jan-2021 11:19:27.1190 4
28-Jan-2021 11:19:38.6666 5
tbl =
5×1 timetable
t x
_________________________ _
28-Jan-2021 11:19:16.7425 1
28-Jan-2021 11:19:16.7425 2
28-Jan-2021 11:19:16.7425 3
28-Jan-2021 11:19:16.7425 4
28-Jan-2021 11:19:16.7425 5
  2 Comments
Jacqueline Chrabot
Jacqueline Chrabot on 29 Jan 2021
Thank you so much this worked! I have one more question I might ask you. I have a that same table datafi{1} which I renamed Cast1, with the first and second columns being the date and second column being a time in the format HH:MM:ss. I wanted to combine the date and time together in one column. I tried this:
Cast1.Var1 = datetime(Cast1.Var1, 'InputFormat','MM/dd/yyyy');
Cast1.Var1 = Cast1.Var1 + Cast1.Var2;
Cast1.Var2 = [];
All this is doing is deleting my time column. When I looked under the date column, its still just the date. Why can't I combine the date and time this way?? My end goal for doing all this is to contour a column chlorophyll by depth (y vector) and time (x vector). Its proving more difficult to set up.
Walter Roberson
Walter Roberson on 29 Jan 2021
Cast1.Var1 = datetime(Cast1.Var1, 'InputFormat', 'MM/dd/yyyy', 'Format', 'MM-dd-yyyy hh:mm:ss.SSSS') + Cast1.Var2;

Sign in to comment.

Categories

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!