1

我有一个文本文件 FILE1.txt,其中记录了指定格式的数据。

[39645212,-79970785]35892002323232[0.0][39645212,-79970785]35892002323232[12.2]

我想将此数据加载到大小为 2*4 的矩阵中。我尝试使用 dlmread 这会引发错误。我正在尝试使用 textread 获得一些东西。我怎样才能得到类似的东西:

39645212 -79970785 35892002323232 0.0
39645212 -79970785 35892002323232 12.2
4

3 回答 3

2
fid = fopen('fun.txt'); %the file you want to read
A=fscanf(fid,'[%d,%d]%d[%g][%d,%d]%d[%g]',[2 inf]);
fclose(fid);

有关格式化字符串的语法,请参见fscanf

于 2013-01-27T08:57:40.557 回答
2

让我们尝试使用regexp

mat = []; % I am lazy and I do not per-allocate. this is BAD.
fh = fopen( 'FILE1.txt', 'r' ); % open for read
line = fgetl( fh );
while ischar( line )
    tks = regexp( line, '\[([^,]+),([^\]]+)\]([^\[]+)\[([^\]]+)', 'tokens' );
    for ii = 1:numel(tks)
        mat( end+1 ,: ) = str2double( tks{ii} );
    end
    line = fgetl( fh );
end
fclose( fh ); % do not forget to close the handle :-)

笔记:

  1. 我假设'[',']'和','之间没有空格,只有数字。所以我可以str2double在恢复的字符串上使用。

  2. 我没有预先分配mat- 这是不好的做法,会显着降低性能。有关如何预分配的详细信息,请参阅此问题。

于 2013-01-27T08:57:41.453 回答
2

您的问题非常具体,我的解决方案也是如此:

C = textread('FILE1.txt', '%s', 'delimiter', '\n');
A = reshape(str2num(regexprep([C{:}], '[\]\[,]', ' ')), 4, [])'

这会将所有括号和逗号替换为空格,将所有内容转换为数字并重新调整为A具有 4 列的矩阵。它也应该适用于多行的输入文件。

于 2013-01-27T09:47:48.287 回答