ChanChow
ChanChow

Reputation: 1366

How can I read data in particular format to a matrix in Matlab?

I have a text file FILE1.txt which has data logged in the format specified.

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

I would like to load this data into a matrix of size 2*4. I tried using dlmread which throws me errors. I am trying to get something using textread. How can I get something like:

39645212 -79970785 35892002323232 0.0
39645212 -79970785 35892002323232 12.2

Upvotes: 1

Views: 97

Answers (3)

Shai
Shai

Reputation: 114976

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.

Upvotes: 2

Eitan T
Eitan T

Reputation: 32930

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.

Upvotes: 2

Mikhail
Mikhail

Reputation: 8038

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

Upvotes: 2

Related Questions