import data from a .txt file with multiple delimiters and headerlines

3 views (last 30 days)
Hello dear Matlab Gurus,
I would like to know a way to import data from a .txt file. The file has 5 lines which I would like to ignore and the columns are separated by commas and > (larger than symbol). Here is an example of the .txt file:
>>128
10347
00>17:05:38,06/27/12,78.0,920
01>17:05:42,06/27/12,78.0,920
02>17:05:45,06/27/12,78.0,920
I would like the outcome to look something like this:
00 17:05:38 06/27/12 78.0 920 01 17:05:42 06/27/12 78.0 920 02 !7:05:45 06/27/12 78.0 920
Or even better, if I could ignore the first column and show the time and date columns as serial time and date. So have only 4 columns like this:
0.71224537 39625 78.00 920 ....
The last step could probably be done after the import.
So far I have been trying to use this code but without much luck :
fd = fopen('file.txt','rt');
data = textscan(fd, '%d%d%f%d', 'delimiter', ', >','headerlines',5);
fclose(fd);
I hope I described my problem good enough and someone will be able to help me. Any hint into the right direction is very appreciated...
Thank you very much...
Nils

Accepted Answer

Walter Roberson
Walter Roberson on 3 Jul 2012
dataCell = textscan( fid, '%*3c%s%s%f%f', 'Delimiter', ',', 'HeaderLines', 2 );
Then
sernums = datestr( strcat(DataCell(2), ' ', DataCell(1)) );
output = [sernums dataCell{3} dataCell{4}];
This would convert the times and dates together as serial date numbers. If you want the columns to be separate as you show in your example, then
sernums = [datestr( DataCell(2) ), datestr( DataCell(1) )];
output = [sernums dataCell{3} dataCell{4}];
  1 Comment
Nils
Nils on 4 Jul 2012
Hello Walter,
thank you for your fast response. The import seems to work now, but I get an error with the time/date conversion. This is the code:
fid = fopen('data.txt','rt');
dataCell = textscan( fid, '%*3c%s%s%f%f', 'Delimiter', ',', 'HeaderLines', 4 );
sernums = [datestr( dataCell(1,2) ), datestr( dataCell(1,1) )];
output = [sernums dataCell{3} dataCell{4}];
... and this is the error:
??? Error using ==> datestr at 180 Cannot convert input into specified date string. DATENUM failed..
Also, could you explain a little bit the textscan code so I could change it if needed? What does "%*3c" do? And is it possible to obtain a double rather than a cell matrix? I hope these questions are not stupid.
Thank you so much.
Nils

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!