Reputation: 1366
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
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:
I assume no spaces and only numbers are between the '[', ']' and ','. So I can use str2double
on the recovered strings.
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
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