How to extract numeric data from the text comments using importdata?

조회 수: 6 (최근 30일)
Chris Wong
Chris Wong 2017년 11월 9일
편집: Looky 2017년 11월 9일
My .txt data files have some text comments in the first few lines, followed by the columns of data. It looks something like this:
lens (mm): 150
Power (uW): 24.4
Inner circle: 56x56
Outer Square: 256x320
remarks: previous didn't work, so switch back to Si (run backward)
2.450000E+1 6.802972E+7 1.086084E+6 1.055582E-5 1.012060E+0 1.036552E+0
2.400000E+1 6.866599E+7 1.088730E+6 1.055617E-5 1.021491E+0 1.039043E+0
2.350000E+1 6.858724E+7 1.086425E+6 1.055993E-5 1.019957E+0 1.036474E+0
2.300000E+1 6.848760E+7 1.084434E+6 1.056495E-5 1.017992E+0 1.034084E+0
If I just use
data = importdata(data_file.txt)
then Matlab can nicely separates the text comments in the beginning as cells, and the rest of the actual data as array. But I also want to read the numbers in the beginning texts such as '150' and '25.4'. How do I do it?

답변 (1개)

Looky
Looky 2017년 11월 9일
편집: Looky 2017년 11월 9일
There are many ways to accomplish that. You can use string manipulation methods to deal with the possible formats you would expect for the header. See strfind, extractAfter, split, num2str, sscanf functions for example.
Here an example:
data.HeaderNumeric={};
for k=1:numel(data.textdata)
data.HeaderNumeric{k}=sscanf(extractAfter(data.textdata{k},':'),'%fx%f');
end
This adds all extracted numerics to a new field HeaderNumeric of your data struct. Note: This example is made for your above shown file. If the header includes lines with several numbers or numbers seperated by something other than x, this won't work and you have do come up with a more sophisticated approach for the format string.

카테고리

Help CenterFile Exchange에서 String Parsing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by