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!