How to read a specially structured data file with different structures

13 visualizzazioni (ultimi 30 giorni)
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'));
fclose(fid);
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?
  2 Commenti
Askic V
Askic V il 27 Feb 2023
Modificato: Askic V il 27 Feb 2023
Is this "After a certain amount of lines" always fixed i.e. 7556. so the rest is from 7557 to the end of the file?
Jake
Jake il 27 Feb 2023
Almost always, yes. However, I'd love to have an option that doesn't take that into account. The "amount of lines" relevant to the attached test data file is 600, btw.

Accedi per commentare.

Risposta accettata

Askic V
Askic V il 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]];
end
if numel(aux_i) == 6
B2 = [B2; aux_i];
end
if (numel(aux_ii)) == 6 && (i == nr_rows-1)
B2 = [B2; aux_ii];
end
end
This code will create a separate matrix B2 consisting only of 6 elements row.

Più risposte (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by