Only read number between brackets []
10 views (last 30 days)
Show older comments
Hello,
I have a camera that records events on every frame as below. There could be thousands of frames in a single text ('clog') file, and multiple events per frame (at least one).
I am looking to only read the four numbers between the square braquets and write them into a matrix with four columns, each row being the immediate next set (could be to the right or below)
I have tried textscan and alldata unsucessfully.
Frame 1 (409804.687500, 0.000000 s)
[242, 83, 18.0403, 0]
[64, 79, 17.4317, 151.5625]
Frame 2 (412404.687500, 0.000000 s)
[154, 106, 22.1719, 0] [154, 107, 8.08874, 17.1875]
[188, 73, 19.039, 176.5625]
Frame 3 (423560.937500, 0.000000 s)
[36, 59, 17.4567, 0] [35, 59, 11.429, 10.9375]
[21, 248, 11.3223, 156.25] [22, 248, 9.13357, 159.375]
Frame 4 (426721.875000, 0.000000 s)
[237, 28, 30.0476, 0] [237, 29, 16.3758, 1.5625]
[135, 168, 5.45964, 117.1875]
Frame 5 (430692.187500, 0.000000 s)
[241, 144, 43.3381, 0]
[29, 206, 22.4948, 131.25]
Frame 6 (431220.312500, 0.000000 s)
[32, 202, 17.4553, 0] [32, 203, 8.08062, 15.625] [31, 202, 7.46939, 26.5625]
[69, 227, 17.182, 137.5] [70, 227, 7.13842, 159.375]
Frame 7 (434304.687500, 0.000000 s)
[46, 85, 22.0349, 0] [46, 86, 16.5734, 1.5625]
[125, 251, 20.5508, 118.75] [126, 251, 7.23025, 134.375]
Frame 8 (436587.500000, 0.000000 s)
[167, 150, 19.2099, 0]
[81, 242, 17.4231, 151.5625]
2 Comments
Image Analyst
on 8 Apr 2022
There seems to be an inconsistency between lines. Some lines have one set of bracketed numbers, while others have 2 or 3. This inconsistency may be why traditional functions don't work. Can you attach your original text file? Do you just want to put each set into one row of the matrix as you encounter them?
Accepted Answer
Image Analyst
on 8 Apr 2022
Try this:
str = fileread('Trial1.txt');
openingBracketLocations = strfind(str, '[')
closingBracketLocations = strfind(str, ']')
% Check for any missing brackets.
any((closingBracketLocations - openingBracketLocations) < 0) % Should be 0
% Create output matrix
m = zeros(length(closingBracketLocations), 4);
for row = 1 : size(m, 1)
thisSet = str(openingBracketLocations(row) + 1 : closingBracketLocations(row) - 1);
numbers = cell2mat(textscan(thisSet, '%f,'));
m(row, :) = numbers;
end
% Show in command window.
m
More Answers (0)
See Also
Categories
Find more on Text Data Preparation 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!