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

9 次查看(过去 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.

产品

Community Treasure Hunt

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

Start Hunting!

Translated by