0

I have a question regarding the importing of .txt files. The file is in the format below, the problem is that matlab does not seem to recognize the "new line" character indicators following every "$", so matlab just sees the 5th line as a continuous stream of data

Data Matlab sees:

01-24-2013 [6:01:53] 
Kp (0070.0000)
Ki  (0200.0000)
Kd (0009.0000)
$,0045,0044,0000.05,0011.53,0005.64,$,0045,0048,0000.04,0011.55,0005.66,$....etc
01-24-2013 [7:01:48]

Data Wordpad sees:

01-24-2013 [6:01:53] 
Kp (0070.0000)
Ki  (0200.0000)
Kd (0009.0000)
$,0045,0044,0000.05,0011.53,0005.64,
$,0045,0048,0000.04,0011.55,0005.66,
$, ....

I have no problem importing the format seen by "wordpad (re-saved with)" using "csvread" and skipping column 1, but for the raw .txt file "Data Matlab sees", I cant find a way to tell Matlab how to read. Ideally, I would like to tell Matlab to skip to Row-5, then start reading data and creating a new line in the matrix [nx5] every time it encounters a "$". Is there a way to detect the "$" and reformat the data into a usable matrix form?

Thanks!

4

1 回答 1

1

我不知道您是如何设法将这些数据作为一行读取的,但假设您这样做了并且想要拆分它。你可以使用万能regexp的来做到这一点:

C = regexp(str, '\$,', 'split');

然后将字符串转换为数字并将所有内容转换为矩阵:

C = cellfun(@str2num, C, 'Uniform', false);
A = vertcat(C{:});

关于问题的第二部分:

理想情况下,我想告诉 Matlab 跳到第 5 行,然后开始读取数据......

您可以textread使用以下'headerlines'选项来做到这一点:

C = textread('file.txt', '%s', 1, 'headerlines', 4, 'delimiter', '\n')
str = C{1};

然后使用regexp用于拆分字符串的代码str

请注意,这仅在 MATLAB 确实像您描述的那样“看到”第 5 行时才有效。如果没有,您将只获得矩阵中的第一行。

例子

str = '$,0045,0044,0000.05,0011.53,0005.64,$,0045,0048,0000.04,0011.55,0005.66';
C = cellfun(@str2num, regexp(str, '\$,', 'split'), 'Uniform', false);
A = vertcat(C{:})

这导致:

A =
   45.0000   44.0000    0.0500   11.5300    5.6400
   45.0000   48.0000    0.0400   11.5500    5.6600
于 2013-01-29T16:56:41.617 回答