MATLAB: Split special merged text and number in text file

split text and number

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

Best Answer

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!):