Reading .txt data to Matlab

2019-09-09 15:42发布

问题:

I am trying to read data from this .txt:

obiekt.DEF


Timeplot
Column01: P abs h01 L1 [W]
Column02: P abs h01 L2 [W]
Column03: P abs h01 L3 [W]
Column04: P abs h01 Sum [W]

Time                         Column01    Column02    Column03    Column04
11.03.2004 09:17:02              23500       19812       21529    64,84e+3
11.03.2004 09:17:05              23316       19789       21519    64,62e+3
11.03.2004 09:17:08              23207       19759       21392    64,36e+3

I only need data from column: 01,02,03. Some data have ',' instead '.'. How to change it? I have many file like this. I tried this function, but it write all data to one variable.

b=textread('test.txt','%s','delimiter',' ','whitespace',' ');

回答1:

You could use textscan:

filename='myfile.txt';
fid=fopen(filename,'r');
data=textscan(fid,'%*s%*s%s%s%s%*s','HeaderLines',10,'CollectOutput',1);
fclose(fid);
data=strrep(data{1},',','.');
data=cellfun(@str2num, data);

Setting HeaderLines sets the first 10 lines to be ignored. Setting CollectOutput groups items of the same type into a cell array (so we get 3 columns of strings). The formatspec '%*s%*s%s%s%s%*s' ignores the date, time and Column04 and converts Column01-03 to strings. Then strrep replaces the commas with periods. cellfun calls str2num on each cell and converts the string to a number.