How to read in a text file with data seperated by a colon first, than a comma and than a dash?

5 ビュー (過去 30 日間)
Hello,
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:
fid=fopen('TheData.txt','r');
TextData=textscan(fid,'%s');
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.
Thank you.

採用された回答

Dan K
Dan K 2013 年 3 月 8 日
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.

その他の回答 (1 件)

Jason Ross
Jason Ross 2013 年 3 月 8 日
編集済み: Jason Ross 2013 年 3 月 8 日
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.

カテゴリ

Help Center および File ExchangeData Import and Export についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by