Parse txt file that is organized with different sections from top to bottom?

1 visualizzazione (ultimi 30 giorni)
I currently have been trying to use the textscan function to read a set of data that is broken into sections. I was hoping to get some help setting it up so that I can complete the rest of it by myself.
The file has different sections that are denoted by * and comments that are denoted as **. Here is a example of the text file.
*feat
*heading
Comment %Example: Problem 1 Simple Beam
*Coordinates
** x,y,z
1, 2, 4
4, 5, 6
7, 5, 9
*Loads
**Type, left end, right end
distributed, 100.0, 120,0
...% a few more sections
*end
Each section has n number of lines or could have zero lines, for example *Coordinates may have 4 lines or 20 lines that I would like to store in matrix. The *Loads section may have n lines or no lines and contains text in the first column and numbers in the rest. I also would like to store this as a matrix. The file ends at "*end".

Risposta accettata

ANKUR KUMAR
ANKUR KUMAR il 15 Mar 2021
Attached is the text file.
clc
clear
fileID = fopen('sample_text.txt','r');
dataArray = textscan(fileID, '%s%[^\n\r]', 'Delimiter', '', 'ReturnOnError', false);
fclose(fileID);
raw = repmat({''},length(dataArray{1}),length(dataArray)-1);
for col=1:length(dataArray)-1
raw(1:length(dataArray{col}),col) = dataArray{col};
end
numericData = NaN(size(dataArray{1},1),size(dataArray,2));
rawNumericColumns = {};
rawCellColumns = raw(:, 1);
A = raw;
A_matrix=A(find(contains(A,'x,y,z'))+1 : find(contains(A,'Loads'))-1,:);
A_matrix_val=cellfun(@(x) strsplit(x,','),A_matrix,'uni',0);
A_matrix_val=str2double(cat(1,A_matrix_val{:}))
Above code results into
A_matrix_val =
1 2 4
4 5 6
7 5 9
Hope this helps.

Più risposte (0)

Categorie

Scopri di più su Data Import and Export in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by