MATLAB: How to read a txt and store specific line in matrix

data importexportfindMATLAB

I have a long txt file and I am interested in a specific lines. The segement that I am interested in is something like:
Activities in Cartesian coordinate
mode 1
( 0.000000000 0.346863768 0.194956009 )
( 0.346863768 0.000000000 -0.000000000 )
( 0.194956009 -0.000000000 0.000000000 )
( 0.346863768 0.000000000 -0.000000000 )
( 0.000000000 -0.346863768 0.194956009 )
( -0.000000000 0.194956009 -0.000000000 )
( 0.187247036 0.000000000 0.000000000 )
( 0.000000000 0.187247036 0.000000000 )
( 0.000000000 0.000000000 -0.893848809 )
mode 2
( 0.000000000 -0.346863768 0.194956009 )
( -0.346863768 0.000000000 0.000000000 )
( 0.194956009 0.000000000 0.000000000 )
( -0.346863768 -0.000000000 0.000000000 )
( -0.000000000 0.346863768 0.194956009 )
( 0.000000000 0.194956009 -0.000000000 )
( 0.187247036 0.000000000 0.000000000 )
( 0.000000000 0.187247036 0.000000000 )
( 0.000000000 0.000000000 -0.893848809 )
mode 3
( -0.000000000 0.292966545 -0.197313262 )
( 0.292966545 0.000000000 0.000000000 )
( -0.197313262 0.000000000 0.000000000 )
( 0.292966545 -0.000000000 0.000000000 )
( -0.000000000 -0.292966545 -0.197313262 )
( 0.000000000 -0.197313262 -0.000000000 )
( -0.182193022 -0.000000000 0.000000000 )
( -0.000000000 -0.182193022 0.000000000 )
( 0.000000000 0.000000000 0.894144988 )
mode 4
( 0.000000000 -0.292966545 -0.197313262 )
( -0.292966545 0.000000000 -0.000000000 )
( -0.197313262 -0.000000000 -0.000000000 )
( -0.292966545 0.000000000 -0.000000000 )
( 0.000000000 0.292966545 -0.197313262 )
( -0.000000000 -0.197313262 0.000000000 )
( -0.182193022 -0.000000000 0.000000000 )
( -0.000000000 -0.182193022 0.000000000 )
( 0.000000000 0.000000000 0.894144988 )
I want to take each mode and store the 3×3 matrices that correspond to in a variable that have a name like modeij. i is the number of the mode, and j is the index of each matrix.
I hope to hear from you.

Best Answer

fmt1='mode%n';
fmt2=['(' repmat('%f',1,3) ')'];
flds={'X','Y','Z'};
fid=fopen(fname,'r');
dat=struct([]);
i=0;
while ~feof(fid)
i=i+1;
dat(i).m=cell2mat(textscan(fid,fmt1,1));
for j=1:length(flds)
dat(i).(flds{j})=cell2mat(textscan(fid,fmt2,3,'collectoutput',1)).';
end
end
fid=fclose(fid);
will return a stuct array dat with fields m,_X_,_Y_,_Z_
You will have to find the initial section in the file before using this code snippet (after the fopen of course) by either knowing a priori a 'headerlines' count number or using a loop and fgetl(fid) to read records until find the section wanted.
A test here returned
>> fname='ZA.dat';
>> ZA
>> whos dat
Name Size Bytes Class Attributes
dat 1x5 3392 struct
>> dat(1)
ans =
struct with fields:
m: 1
X: [3×3 double]
Y: [3×3 double]
Z: [3×3 double]
>> dat(1).X
ans =
0 0.3469 0.1950
0.3469 0 0
0.1950 0 0
>> dat(2).X
ans =
0 -0.3469 0.1950
-0.3469 0 0
0.1950 0 0
>>