Casting cell array of cells to something workable
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
Walter Roberson
2018-4-18
"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.
采纳的回答
Walter Roberson
2018-4-18
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');
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!