How to read date and time from text file and move into cell array?
Show older comments
hello. i have a text file which contains a date and a time. I need to extract the date and time from the text file and put it in the cell array. The cell array should look like this:
Date Time 06 00 06 00
OBDMIDs ExhaustGasSensorMonitorBank1Sensor1
2016-03-18 09:21:31 OBDmonitorIDsSupported$01_$1F Supported
Please note that nothing needs to be done for rest of the columns. Its already done.
this is my code;
Cstr = textread('Test1.txt', '%s', 'delimiter', '');
cString = Cstr(29:end); %removes headers
cString = char(cString); %Transforms into a char array,...
%split the columns
pdu = cellstr(cString(:, 1));
parameter = cellstr(cString(:, 1:42));
value = cellstr(cString(:, 43:86));
%unit = cellstr(cString(:, 87:end));
for i=1:length(parameter)
temp = parameter{i};
if ismember(temp(1),num2str(0:9))
tempSplit = regexp(temp,' ', 'split');
newPDU(i) = tempSplit(1);
newParameter(i) = tempSplit(2);
else
newPDU(i) = newPDU(i-1);
newParameter(i) = parameter(i);
end
end
newc = [newPDU; newParameter; value'];
the text file is attached below. Thank you for the help in advance.
Accepted Answer
More Answers (1)
Before you remove the headers obviously:
date = regexp(Cstr{4}, '(?<=Date:\s*)\S+', 'match', 'once');
time = regexp(Cstr{5}, '(?<=Time:\s*)\S+', 'match', 'once');
At the end:
newc = [{'Date', 'Time'; '', ''; date, time}, newc];
I see you've given up on my previous solution for reading your file, which is a shame as it avoided loops entirely.
3 Comments
yousaf obaid
on 20 Jun 2016
Guillaume
on 20 Jun 2016
Well, you're parsing the PDU very differently and as a result requires even more parsing. You went from a clean and efficient (in my opinion) solution to one that includes an extra loop for more parsing and, if you use the overly complicated answer you've accepted here, even more parsing!
You're parsing the same data three times now. In the grand scheme of things it probably does not matter as your text file is fairly small so you won't notice the extra time spent reparsing the data.
I would recommend adding comments to questions if the solution does not work perfectly rather than asking new question. It makes it easier to follow what you're doing.
Also, I'd recommend waiting a little before accepting answers.
yousaf obaid
on 20 Jun 2016
Categories
Find more on String Parsing 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!