Casting cell array of cells to something workable
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
supernoob
el 18 de Abr. de 2018
Comentada: supernoob
el 19 de Abr. de 2018
Hi there, I have an Nx1 cell (named 'intervals') which contains cell arrays. For example:
K>> intervals(1:5,1)
ans =
5×1 cell array
{'2018-03-2610:25:51 PM'}
{'2018-03-2610:25:51 PM'}
{'2018-03-2610:25:51 PM'}
{'2018-03-2610:25:52 PM'}
{'2018-03-2610:25:52 PM'}
The cell arrays are supposed to contain dates but as you can see they are improperly formatted - I need to add a space between the day and hour to be able to convert this into something useful. The cell I have is very very long (~1500000x1), so I don't want to do this with a for loop. Is there a smart way to add a space in each cell array at the correct spot? Another option is to cast this cell array of cells into a matrix of strings, but every variation of cell2mat I have tried gives me a 1498393x21 char.
My desired output is an array of datetimes
2018-03-26 10:25:51 PM
2018-03-26 10:25:51 PM
2018-03-26 10:25:51 PM
2018-03-26 10:25:52 PM
2018-03-26 10:25:52 PM
My current code will take forever, because the actual text file I'm working with is so huge:
function dates = timestamp_correction()
filename = 'intervals.txt';
fileID = fopen(filename);
intervals = textscan(fileID, '%s', 'delimiter', '\t');
intervals = intervals{1,1};
for i=1:numel(intervals)
dates(i) = datetime(intervals{i,1}, 'InputFormat', 'yyyy-MM-ddhh:mm:ss a');
end
dates = dates';
end
trying
datetime(intervals{:}, 'InputFormat', 'yyyy-MM-ddhh:mm:ss a');
throws an error, it wants it to be an array first but I can't get that to work :(
I've attached a much smaller text file which is a truncated version of the bigger one I am working with.
Thanks!
4 comentarios
Walter Roberson
el 18 de Abr. de 2018
"I need to account for the fact that the day might have one or two digits"
So for example, 2018-03-210:25:51 PM would be possible for 2nd of the month at 10:25:51 PM ?
If so then what happens for times between 1 and 9 ? Is the leading 0 omitted for them, leading to, for example, 2018-03-261:25:51 PM for 1:25:51 PM on the 26th?
If so, then can both end up with leading zeros removed, such as 2018-03-21:25:51 PM for 1:25:51 PM on the 2nd ?
If both can have leading zeros removed then you cannot tell whether 2018-03-211:25:51 PM is 1:25:51 PM on the 21st, or is 11:25:51 PM on the 2nd.
Respuesta aceptada
Walter Roberson
el 18 de Abr. de 2018
reformatted_intervals = cellfun(@(S) [S(1:10) ' ' S(11:end)], intervals, 'uniform', 0)
However since your purpose is to convert to another form, you can instead skip the reformatting and use
intervals_dt = datetime(intervals, 'InputFormat', 'yyyy-MM-ddhh:mm:ss a');
Más respuestas (0)
Ver también
Categorías
Más información sobre Time Series Objects en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!