Hello good... I would like to know how I can skip the comments header of a text file with data for a graph please :c

조회 수: 5 (최근 30일)
Hello good... I would like to know how I can skip the comments header of a text file with data for a graph please :c
  댓글 수: 1
Benjamin Thompson
Benjamin Thompson 2022년 4월 14일
Can you use the data import tool? Right click on the file in the MATLAB file listing and select "Import Data". Otherwise please post a sample of your file for the Community to see.

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

답변 (2개)

Siraj
Siraj 2023년 9월 11일
Hi! It is my understanding that you want to read a text file while excluding any header comments present in the file.
Method - 1
One approach to exclude header comments when reading a text file is by utilizing the "fgetl" function to skip a specific number of lines, assuming you already know the number of header lines to skip. Below is an example for better clarity:
The contents of the file "file1.txt" used in the example below are as follows:
Comment 1
Comment 2
Comment 3
1 2 1
1 2 3
2 3 4
4 4 6
Here is an example code snippet.
% Specify the file path and name
file = 'file1.txt';
% Open the file for reading
fid = fopen(file, 'r');
% Specify the number of header lines to skip
numHeaderLines = 3;
% Skip the header lines
for i = 1:numHeaderLines
fgetl(fid);
end
% Read the data using textscan
data = textscan(fid, '%f %f %f');
% Close the file
fclose(fid);
Method - 2
Another approach is instead of manually skipping a fixed number of header lines, utilize the comment style option in the “textscan” function to skip lines starting with a specific character, such as '#'. This approach allows you to dynamically skip any number of header or comment lines present in the file. Below is an example for better clarity:
The contents of the file "file2.txt" used in the example below are as follows.
#Comment 1
#Comment 2
#Comment 3
1 2 1
1 2 3
2 3 4
4 4 6
Here is an example code snippet
% Open the file for reading
file = 'file2.txt';
fid = fopen(file, 'r');
% Read the data using textscan and skip lines starting with '#'
data = textscan(fid, '%f %f %f', 'Delimiter', '\t', 'CommentStyle', '#');
% Close the file
fclose(fid);
To learn more about the "fgetl" and "textscan" functions in MATLAB, you can refer to the following links:
Hope this helps.

Image Analyst
Image Analyst 2023년 9월 11일
@Lya Lopez, You can use readmatrix with the NumHeaderLines option:
data = readmatrix(filename, 'NumHeaderLines', 3); % Skip first 3 lines.

카테고리

Help CenterFile Exchange에서 Text Files에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by