Read text file without header and separate columns

조회 수: 108 (최근 30일)
Philipp Reh
Philipp Reh 2020년 4월 29일
편집: Rik 2022년 4월 21일
Dear Matlab Team,
my problem is as follows. I could not find a solution in other forums, but none seem to work for my issue:
I have a text file with a big headliner, which I want to skip. The data I need starts in line 194 and has 50.000 values. There are 3 values in each row, sperated by ",". Basically, what I need is to extract the 50 000 values and put it in matrix with 3 columns for further analyzation.
This is how the file looks like (starting from below "DATA BLOCK..."]
...
[DATA BLOCK 1-1-1]
0.00000,20.47668,0.13959
0.00010,20.46021,0.16467
0.00020,20.47668,0.11914
0.00030,20.48767,0.19208
...
How can I separate this data and create a matrix from it?
Thanks in advance,
Philipp

채택된 답변

Rik
Rik 2020년 4월 29일
편집: Rik 2020년 4월 29일
You can use the readmatrix function.
A = readmatrix(filename,'NumHeaderLines',193);
Edit:
As Walter suggested below: releases older than R2019a are missing the readmatrix function. On R2013b or newer, the readtable function can help out:
A = table2array(readtable(filename,'NumHeaderLines',193, 'readvariablenames', false));
  댓글 수: 8
Walter Roberson
Walter Roberson 2020년 5월 6일
Looks like I misinterpreted what was being requested.
You should be pre-initializing A.
input_folder = 'folder';
files = dir(fullfile(input_folder, '*.txt'));
file_paths = fullfile({files.folder}, {files.name});
nfile = numel(file_paths);
for i = 1 : nfile
data = readmatrix(file_paths{i},'NumHeaderLines',193);
if i == 1
A(:,3*nfile) = 0; %grow array to largest size
else
A(:, i*3-2:i*3) = data;
end
end
Philipp Reh
Philipp Reh 2020년 5월 6일
Thank you.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

B
B 2022년 4월 21일
편집: Rik 2022년 4월 21일
I think summarizing you've got something like this:
input_folder = 'folder';
files = dir(fullfile(input_folder, '*.txt'));
file_paths = fullfile({files.folder}, {files.name});
nfile = numel(file_paths);
for i = 1 : nfile
data= readmatrix(file_paths{i},'NumHeaderLines',1);% a display of data in a single file
cols=3*(i-1)+(1:3)
A(:,cols)=data; % A is your desired result outpout file
end

카테고리

Help CenterFile Exchange에서 Genetic Algorithm에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by