split special merged text and number in text file
4 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponse acceptée
Stephen23
le 22 Avr 2017
Modifié(e) : Stephen23
le 22 Avr 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 commentaires
Stephen23
le 22 Avr 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.
Plus de réponses (1)
KSSV
le 21 Avr 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 commentaires
Voir également
Catégories
En savoir plus sur String dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!