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
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
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.