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);

See fscanf for syntax of the formatting string

于 2013-01-27T08:57:40.557 に答える
2

Lets try using 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 :-)

NOTES:

  1. I assume no spaces and only numbers are between the '[', ']' and ','. So I can use str2double on the recovered strings.

  2. I did not pre-allocated mat - this is bad practice and can significantly reduce performance. See this question for details on how to pre-allocate.

于 2013-01-27T08:57:41.453 に答える
2

Your problem is very specific, and so is my solution:

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

This replaces all brackets and commas with spaces, converts everything to numbers and reshapes to a matrix A with 4 columns. It should work for an input file with more than one line as well.

于 2013-01-27T09:47:48.287 に答える