MATLAB: Read a complex text file and then rearrange it

headerMATLABmatrix arrayread data

Hello people!
I have a .txt file I need to import in MATLAB, read and then rearrange. But let's stick to the reading part for now. The text file may be found here:
As you may notice the file structure is several lines of header, a four column matrix, some lines of header again and then a five column matrix until the end of the file.
What do I need to keep: 1. some numbers from both header groups 2. 2 first columns from the first matrix 3. all columns from the last matrix
My inquiry is: 1. How can I read the first four headers and store them (numbers as numbers and text as text)? 2. How can I read the first two columns of the first matrix and ignore the others. Note that 48 is the length of number of rows of the first matrix. Is it possible to keep the first two columns in two separate single column matrices A(n,1)? 3. Read the next set of three headers like in point 1 4. How can I real all the columns of the last matrix and store the data in five single column matrices? Note that 680 is the number of rows of the last matrix.
I have some knowledge of FORTRAN but it's been too long since I used it, plus I don't own a FORTRAN license anymore. MATLAB is my only option. So I would appreciate it if a brief desription followed each code line.
Thank you in advance!
Giorgos

Best Answer

fid = fopen('data.txt');
s = fgets(fid); % get first line
num1 = sscanf(s, '%d') % convert to number
s = fgets(fid); % get next, i.e, second line
s = fgets(fid); % get next, i.e, third line
num2 = sscanf(s, '%d')
s = fgets(fid); % get next, i.e, fourth line
Nlines = sscanf(s, '%d')
M1 = fscanf(fid, '%f\n', 4*Nlines);
M1 = reshape(M1, 4, [])';
% keep the first two columns in two separate single column matrices
C11 = M1(:, 1);
C12 = M1(:, 2);
header2 = fscanf(fid, '%f\n', 3);
Nlines = header2(2)
M2 = fscanf(fid, '%f\n', 5*Nlines);
M2 = reshape(M2, 5, [])';
% store the data in five single column matrices
C21 = M2(:, 1);
C22 = M2(:, 2);
C23 = M2(:, 3);
C24 = M2(:, 4);
C25 = M2(:, 5);
fclose(fid)