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

조회 수: 4(최근 30일)
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.
Comment %Example: Problem 1 Simple Beam
** x,y,z
1, 2, 4
4, 5, 6
7, 5, 9
**Type, left end, right end
distributed, 100.0, 120,0
...% a few more sections
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".

채택된 답변

ANKUR KUMAR 2021년 3월 15일
Attached is the text file.
fileID = fopen('sample_text.txt','r');
dataArray = textscan(fileID, '%s%[^\n\r]', 'Delimiter', '', 'ReturnOnError', false);
raw = repmat({''},length(dataArray{1}),length(dataArray)-1);
for col=1:length(dataArray)-1
raw(1:length(dataArray{col}),col) = dataArray{col};
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);
Above code results into
A_matrix_val =
1 2 4
4 5 6
7 5 9
Hope this helps.

추가 답변(0개)

Community Treasure Hunt

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

Start Hunting!

Translated by