How to read in a text file with data seperated by a colon first, than a comma and than a dash?
44 views (last 30 days)
I have a .txt file with thousands of lines of data that I want to read into my Matlab workspace. The problem is that the data does not use a consistent separation. For example, 2 lines of data look similar to this:
HA: 2012-01-08, 11:01:45.802 – FFFF0811111111210208
BA: 2012-01-08, 11:01:45.805 – FFFF0811111111220333
In this, I have a variable, “HA” and “BA”, each with a date, time and 422 data. I want to read in this data for a large number of lines. I am trying textscan but I am a little confused how to read in the data because it is not separated by a consistent delimiter such as comma-delimited. Thus far, I have wrote:
I am trying to get my script into a format similar to what Matlab shows in "help textscan":
“C = textscan(FID,'FORMAT',N,'PARAM',VALUE)”
Any help is greatly appreciated.
Dan K on 8 Mar 2013
Here's a place to start from:
str1 = 'HA: 2012-01-08, 11:01:45.802 – FFFF0811111111210208'
C = textscan(str1,'%2c:%d-%d-%d, %d:%d:%f%[^- ]%s')
What this does is:
1. Read 2 characters
2. Then read three integers separated by hypens
3. Then read two integers and a floating point separated by colons
4. Capture or throw away the hypen
5. Then capture the (I assume hex) string at the end.
Hope this helps.
More Answers (1)
Jason Ross on 8 Mar 2013
Edited: Jason Ross on 8 Mar 2013
I'd suggest taking the example you have there, putting it in a file, and using the Import Wizard. In the upper left hand side, you can select "Delimiter" and enter the delimiters you want to use, and preview your data. Under "Import Selection", you can select "generate function" or "generate script", and in that generated file will be the textscan code to use.
Note that you might need to get the delimiters right first, then combine the data back in a separate operation.
Alternatively you might want to look at using regular expresssions, but that might be more hassle than doing the import and then combining things as you want to.