split special merged text and number in text file
4 views (last 30 days)
Show older comments
Hi I've special text file (without any spaces or , between text and numbers) (attached file) and I want to split text and number in each lines for example: I have 'X004986Y002446' and I want to convert it to X=004986 and Y=002446 as two variable(Vector/Matrix) how to input text file and split each lines?
thanks
0 Comments
Accepted Answer
Stephen23
on 22 Apr 2017
Edited: Stephen23
on 22 Apr 2017
Using textscan, fgetl, ftell and fseek in a while loop makes this easy. It will copy the lines without X...Y... verbatim to the new file, and imports the X & Y values into MATLAB for you to process. These are then saved into the new file.
fmt = 'X%dY%d';
fi1 = fopen('G1.txt','rt');
fi2 = fopen('G2.txt','wt');
while ~feof(fi1)
byt = ftell(fi1);
txt = fgetl(fi1);
if strncmp(txt,'X',1)
fseek(fi1,byt,'bof');
C = textscan(fi1,fmt);
X = C{1};
Y = C{2};
... your code here
M = [X,Y];
fprintf(fi2,'X%06dY%06d\n',M.');
else
fprintf(fi2,'%s\n',txt);
end
end
fclose(fi1);
fclose(fi2);
Within the if statement you can use txt to identify the current tool block, should you need to do so.
My code was tested on this file (and generates a new file exactly the same!):
2 Comments
Stephen23
on 22 Apr 2017
There might be other ways to resolve this non-uniform file format, but one workaround is to convert it into a uniform file format, for example:
fi1 = fopen('P1.txt','rt');
C = textscan(fi1,'%[^\n]');
fclose(fi1);
C = regexprep(C{1},{'^(X\d+)$','^(Y\d+)$'},{'$1YNaN','XNaN$1'});
fi3 = fopen('P3.txt','wt');
fprintf(fi3,'%s\n',C{:});
fclose(fi3);
Then you can use the same code as my answer give to read the numeric data. How you deal with the NaN' is up to you, e.g. you could change the numeric format string from %d to %f to keep the NaN's as NaN's.
More Answers (1)
KSSV
on 21 Apr 2017
fid = fopen('data.txt') ;
S = textscan(fid,'%s','delimiter','\n') ;
fclose(fid) ;
S = S{1} ;
S = S(7:end-4) ;
out=regexp(S,'[\d]+','match') ;
out = [out{:}] ;
out = reshape(out',2,[])' ;
out=cell2mat(cellfun(@(x) str2double(x),out,'un',0)) ;
There would be more elegant way..
2 Comments
See Also
Categories
Find more on String in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!