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 views (last 30 days)
Show older comments
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 Comment
Benjamin Thompson
on 14 Apr 2022
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.
Answers (2)
Siraj
on 11 Sep 2023
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 Comments
Image Analyst
on 11 Sep 2023
data = readmatrix(filename, 'NumHeaderLines', 3); % Skip first 3 lines.
0 Comments
See Also
Categories
Find more on Text Files in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!