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
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
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.
댓글 수: 0
Image Analyst
2023년 9월 11일
data = readmatrix(filename, 'NumHeaderLines', 3); % Skip first 3 lines.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Text Files에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!