How to read a specially structured data file with different structures
6 views (last 30 days)
I asked a similar question on the forum only to realize that I had worded it poorly and incompletely. My apologies for the repetitiveness.
I have a *.5P file (file is an output from the software WAMIT, and can be read by Matlab and/or any text editor) that I want to read through Matlab. Since I cannot upload a *.5P file here in the forum, I changed it to a *.txt file and attached the sample file here.
Now, one line of this data file would include 19 columns (each separated by a tab or space). However, the specific structure of the output file "wraps" each data line to include only 15 columns, and the next 4 lines go into a new line. After a certain amount of lines, the structure changes to 6 columns. I'm adding the following screenshot (mind you, not from the attached test file, but this is the same structure) for ease of explanation but the attached data file should explain things further :)
As it can be seen, lines 1~7556 has 19 columns (15 in one line and 4 in the next line, wrapped), and the lines 7557~ has 6 columns. These two structures repeats in the data file.
This was my code:
fid = fopen('test.5p');
C = cell2mat(textscan(fid, '%f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f'));
and two other solutions were suggested in the earlier posting. Again, my apologies for the mistake.
How can I read the data, and maybe get two separate readings that include two data structures?
Askic V on 27 Feb 2023
I would suggest the follwoing solution:
A = readtable('test.5p', 'ReadVariableNames', false, 'FileType', 'text');
nr_rows = size(A,1);
A2 = ;
B2 = ;
for i = 1:nr_rows-1
aux_i = str2num(cell2mat(table2array(A(i,:))));
aux_ii = str2num(cell2mat(table2array(A(i+1,:))));
if numel(aux_i) == 15 && numel(aux_ii) == 4
A2 = [A2; [aux_i, aux_ii]];
if numel(aux_i) == 6
B2 = [B2; aux_i];
if (numel(aux_ii)) == 6 && (i == nr_rows-1)
B2 = [B2; aux_ii];
This code will create a separate matrix B2 consisting only of 6 elements row.