read selected data from text file from a matrix or array of numeric values

3 views (last 30 days)
I have a log in text file format. It contains Numbers and texts. i want selected content only from the file. The content is in the folwing form:
---------------------------------
ant carrid raw dBFs
---------------------------------
0 0, 23094278, -14.35
1 0, 22990729, -14.37
2 0, 0, 0.00
3 0, 0, 0.00
0 1, 0, 0.00
1 1, 0, 0.00
2 1, 0, 0.00
3 1, 0, 0.00
The file have multiple tables like above and these all data need to be stored in arrays or matrix like below format:
ant carrid raw dBFs
0 0, 23094278, -14.35
1 0, 22990729, -14.37
0 0, 23094278, -14.35
1 0, 22990729, -14.37
always the ant and carrid is 0 0 and 1 0 lines to be read.
please help me to write the code or if you have please share with me. log file is attached here

Answers (1)

Satyam
Satyam on 11 Feb 2025
Hi there,
You can use ‘fopen’ function to open the .txt file in MATLAB. Simultaneously, you can also leverage the usage of ‘fgetl’ to read the lines of the file and check if they comply with your specified format. For more information on how to use ‘fgetl’, you can check out the following documentation: https://www.mathworks.com/help/matlab/ref/fgetl.html
You can use ‘sscanf()’ to read data if the result of ‘fgetl’ function call does comply with your format “ant carrid raw dBFs”. More details on ‘sscanf’ can be found: https://www.mathworks.com/help/matlab/ref/string.sscanf.html
Here’s a code snippet to help you with the approach:
% Open the log file for reading
filename = 'log.txt';
fid = fopen(filename, 'r');
data = [];
currentTable = [];
headers = {'ant', 'carrid', 'raw', 'dBFs'};
% Read the file line by line
while ~feof(fid)
line = fgetl(fid);
% Check for the start of a new table
if contains(line, 'ant carrid raw dBFs')
% If there's a current table, append it to the data
if ~isempty(currentTable)
data = [data; currentTable];
currentTable = [];
end
% Skip the separator line
fgetl(fid);
else
% Parse data lines
values = sscanf(line, '%d %d, %d, %f');
if numel(values) == 4 && ((values(1)==0 && values(2)==0) || (values(1)==1 && values(2)==0))
currentTable = [currentTable; values'];
end
end
end
% Append the last table if it exists
if ~isempty(currentTable)
data = [data; currentTable];
end
fclose(fid);
% Add headers to the data matrix
data_with_headers = [headers; num2cell(data)];
disp(data_with_headers(1:5, :))
{'ant'} {'carrid'} {'raw' } {'dBFs' } {[ 0]} {[ 0]} {[23094278]} {[-14.3500]} {[ 1]} {[ 0]} {[22990729]} {[-14.3700]} {[ 0]} {[ 0]} {[23094278]} {[-14.3500]} {[ 1]} {[ 0]} {[22990729]} {[-14.3700]}
I hope it helps!

Categories

Find more on Data Import and Export in Help Center and File Exchange

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!