MATLAB: Modifying Text Data without changing the file format

MATLABmodify datasame formattext file

Hi,
I have a file that includes 3 parts of data as the following:
1) Header: 5 lines of chars.
2) Coordinate Info: All numbers , in the form [ID x y z] , many lines (around 9000 lines).
3) Cell Info: All Numbers, in the form [ID node1 node2 node3 node4] , many lines too.
Also there is a keyword before 2nd and 3rd part (one line of chars).
What I need to do is to change only the 2nd part (Coordinate Info) with new calculated coordinates, that have the exact same structure and size, and leave everything else as it was. Pretty much like opening the file then copy new Coordinate Info over the old Coordinate Info.
Also I want to keep the same file format (file.key) if possible.
What is the faster way to do it?
Thanks in advance.

Best Answer

Here is a simple enough way to achieve this.
content = fileread( 'srcFile.txt' ) ;
block1 = regexp( content, '^.+?\*NODE[\r\n]*', 'match', 'once' ) ; % Edited.
block3 = regexp( content, '\*ELEMENT_SOLID.+?$', 'match', 'once' ) ;
data = [1 20 21 22; 2 30 31 32; 3 40 41 42] ; % Replacement data.
block2_new = sprintf( '%d %f %f %f\r\n', data.' ) ; % New block 2.
fid = fopen( 'dstFile.txt', 'w' ) ;
fwrite( fid, [block1, block2_new, block3] ) ;
fclose( fid ) ;
Using the following file content for srcFile.txt
A
B
C
D
*NODE
1 1 2 3
2 4 5 6
*ELEMENT_SOLID
9
10
11
X
Y
Z
We get the following dstFile.txt
A
B
C
D
*NODE
1 20.000000 21.000000 22.000000
2 30.000000 31.000000 32.000000
3 40.000000 41.000000 42.000000
*ELEMENT_SOLID
9
10
11
X
Y
Z
If you didn't want to deal with REGEXP, you could proceed as Walter mentions, using a combination of FGETL, FPRINTF, STRCMP or STRFIND.