Reading text file to extract specific data chunks
8 views (last 30 days)
Show older comments
Zain Jamal
on 18 Jul 2022
Commented: Image Analyst
on 19 Jul 2022
I have a large text file with important numbers about a certain category. It looks something like this
CATEGORY 1
* 1
* 2
* 3
* 4
CATEGORY 2
* 4
* 5
* 6
* 7
CATEGORY 3
* 8
* 9
* 10
* 11
There are many more categories, but for the example I'll keep it at these two. Depending on a user input, I want to fill a variable, lets call it "numbers" with the numbers under the appropriate category. Say a user inputs "CATEGORY 2", I want the variable "numbers" to be [4 5 6 7]. How could I do this? I'm trying to use fgetl and simply index the number on each line, but I can't get it right. Any help is appreciated!
Edit: Included actual text file being read. Also included the code I've tried with the error I'm getting
component = input('Write the component being analyzed in quotes: ')
fid = fopen(‘stations_clgrids.txt')
station = [];
i = 1;
if component == 'Fairing'
while ~feof(fid)
line = fgetl(fid);
if (line(1:7) == 'FAIRING')
line_sta = fgetl(fid);
if (line_sta(1)=='*')
station(i) = str2num(line_sta(9:16))
elseif isempty(line_sta)
break
end
end
end
end
Write the component being analyzed in quotes: 'Fairing'
Index exceeds the number of array elements (0).
Error in define_cl_station (line 13)
if (line(1:7) == 'FAIRING')
1 Comment
Star Strider
on 19 Jul 2022
I have no idea what you want to do with the contents of that file, so I deleted my answer.
Accepted Answer
Image Analyst
on 19 Jul 2022
Try it this way:
% component = input('Write the component being analyzed in quotes: ')
component = 'Fairing'
fid = fopen('stations_clgrids.txt', 'rt')
station = [];
index = 1;
if strcmpi(component, 'Fairing')
while ~feof(fid)
textLine = fgetl(fid);
fprintf('Just read "%s" from file.\n', textLine)
if contains(textLine, 'FAIRING', 'IgnoreCase',true)
starredLine = fgetl(fid);
fprintf(' Just read starred line "%s" from file.\n', starredLine)
if startsWith(starredLine, '*')
station(index) = str2num(starredLine(2:end));
% Increment counter.
index = index + 1;
elseif isempty(starredLine)
break
end
end
end
end
fclose(fid);
% Show in command window
station
2 Comments
More Answers (0)
See Also
Categories
Find more on Text Files in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!