2

我有一个包含大量数据行的文本文件,其中列用空格分隔。如何使用 MATLAB 读取这些数据?我尝试了以下代码但没有成功:

fid = fopen('file.txt');

M = textscan(fid, '%f %f %f');

x = M{1};

y = M{2};

z = M{3};

数据如下图(列不等间距):

4.55686    0.88751    4.71368       0.00000       0.00000   879.7   0.143   1.77  1  1  Iron - Alpha

4.55686    0.88751    4.71368       0.00000       0.00000   879.7   0.143   1.77  1  1  Iron - Alpha

4.55686    0.88751    4.71368       0.00000       0.00000   879.7   0.143   1.77  1  1  Iron - Alpha

4.55686    0.88751    4.71368       0.00000       0.00000   879.7   0.143   1.77  1  1  Iron - Alpha

4.55686    0.88751    4.71368       0.00000       0.00000   879.7   0.143   1.77  1  1  Iron - Alpha

4.55686    0.88751    4.71368       0.00000       0.00000   879.7   0.143   1.77  1  1  Iron - Alpha
4

2 回答 2

3

首先,考虑您的数据文件。每行包含 10 个数字和 3 个字符串。很容易认为它包含 10 个数字和 1 个字符串,但由于使用空格作为分隔符并且字符Iron - Alpha没有用引号括起来,所以它们构成 3 个字符串,而不是 1 个。

Next, textscan will only behave itself as you wish if you provide a complete description of the input line in the format specification. For example, the following

 M = textscan(fid, '%f %f %f %f %f %f %f %f %f %f %s %s %s')

works just fine for me. Since you only want the first 5 columns of data, and this reads all the data, you can easily delete the unwanted columns.

If you want or need to avoid reading the unwanted data you'll have to get a little smarter. You can instruct textscan to ignore specific fields like this:

 M = textscan(fid, '%f %f %f %f %f %*f %*f %*f %*f %*f %*s %*s %*s')

which reads only the first 5 fields in each line. The documentation will point you towards ways of refining your reading routine even further.

于 2012-10-01T14:15:57.267 回答
2

请尝试 dlmread。

data = dlmread('file.txt');

并检查分隔符是否为空格。它可能包含不可见的字符 '\t'。

于 2012-10-01T08:26:54.910 回答