Reading a specific ASCII format file

51 views (last 30 days)
I have ASCII files in the format uploaded and I would like to read the data below the header [DATA]. Any guidance on how I could do that? The number of columns 3-6 depending on the file and the number of rows might defer as well.

Accepted Answer

Hassaan
Hassaan on 17 Jan 2024
Edited: Hassaan on 17 Jan 2024
% Open the file
filename = 'New Text Document.txt'; % Change to your actual file name
fid = fopen(filename, 'r');
% Initialize a flag to indicate when the [DATA] section starts
data_section_started = false;
% Initialize a cell array to hold the data
data = {};
% Read the file line by line
while ~feof(fid)
line = fgets(fid); % Read a line
% Check if we've reached the [DATA] section
if contains(line, '[DATA]')
data_section_started = true;
continue; % Skip the line with [DATA]
end
% If we're in the [DATA] section, read the numbers
if data_section_started
% Split the line by tab and convert to numbers
num_line = str2num(line); %#ok<ST2NM> % This function is appropriate here
if ~isempty(num_line)
data{end+1} = num_line; % Append to the data cell array
end
end
end
% Close the file
fclose(fid);
% Convert the cell array to a matrix (assuming the data is uniform)
data_matrix = vertcat(data{:});
disp(data_matrix)
  1. The file is opened with fopen, and the script reads the file line by line.
  2. A flag data_section_started is used to determine when the [DATA] section has started.
  3. Each line of numbers is appended to a cell array data as a numeric array.
  4. After all data is read, the cell array is concatenated into a matrix with vertcat.
This script assumes that your data is well-formed (all rows have the same number of columns) and that the data is separated by tabs or spaces. If the data is not uniform or if the file uses a different delimiter, you might need to adjust the str2num line accordingly.
-----------------------------------------------------------------------------------------------------------------------------------------------------
If you find the solution helpful and it resolves your issue, it would be greatly appreciated if you could accept the answer. Also, leaving an upvote and a comment are also wonderful ways to provide feedback.
Professional Interests
  • Technical Services and Consulting
  • Embedded Systems | Firmware Developement | Simulations
  • Electrical and Electronics Engineering
It's important to note that the advice and code are based on limited information and meant for educational purposes. Users should verify and adapt the code to their specific needs, ensuring compatibility and adherence to ethical standards.
Feel free to contact me.
  1 Comment
Hassaan
Hassaan on 17 Jan 2024
@Ashutosh Why not use a JSON format or XML format for organzing your data file.

Sign in to comment.

More Answers (2)

Sai Teja G
Sai Teja G on 17 Jan 2024
Hi Ashutosh,
Please refer to the following code to learn how to read the data situated beneath the '[DATA]' header. Additionally, you can view the output generated from your sample file.
% Open the file for reading
filename = 'your.txt'; % Replace with your actual file name
fileID = fopen(filename, 'r');
% Check if the file was opened successfully
if fileID == -1
error('File could not be opened.');
end
% Read lines until we find the [DATA] header
while ~feof(fileID)
line = fgetl(fileID);
if strcmp(line, '[DATA]')
break;
end
end
% Check if we actually found the [DATA] header
if feof(fileID)
error('No [DATA] header found in the file.');
end
% Read the data below the [DATA] header
% Assuming the data is separated by whitespace and the file does not
% contain text after the numerical data.
data = textscan(fileID, '%f'); % '%f' reads floating point numbers
data = cell2mat(data); % Convert cell array to a matrix
% Close the file
fclose(fileID);
% Reshape the data if necessary
% If the number of columns is known after the header, you can reshape the data.
% For example, if there are 4 columns:
% numColumns = 4;
% numRows = length(data) / numColumns;
% data = reshape(data, [numColumns, numRows])';
display(data);
data = 12×1
1 2 1 1 2 1 1 2 1 1

Venkat Siddarth Reddy
Venkat Siddarth Reddy on 17 Jan 2024
Edited: Venkat Siddarth Reddy on 18 Jan 2024
Hi Ashutosh,
To solve this query, you can read the file line by line until you find the "[DATA]" header.And then read the data into a matrix,using "textscan" function.
Following is an example code snippet to achieve the above:
filename = 'Test doc.txt';
data = readDataAscii(filename)
data = 4×3
1 2 1 1 2 1 1 2 1 1 2 1
function data = readDataAscii(filename)
fid = fopen(filename, 'rt');
% Read the file line by line to find the [DATA] header
foundDataHeader = false;
while ~feof(fid)
line = fgetl(fid);
if strcmp(line, '[DATA]')
foundDataHeader = true;
break;
end
end
% Check if the [DATA] header was found
if ~foundDataHeader
fclose(fid);
error('No [DATA] header found in file: %s', filename);
end
% Read the data below the [DATA] header
% Assuming that the data is numeric and tab-separated
data = [];
while ~feof(fid)
line = fgetl(fid);
if ~ischar(line) % End of file or empty line
break;
end
numCols = numel(strsplit(line));
formatSpec = repmat('%f', 1, numCols); % Create format specifier
lineData = textscan(line, formatSpec, 'Delimiter', ' ', 'MultipleDelimsAsOne', true);
data = [data; cell2mat(lineData)];
end
% Close the file
fclose(fid);
end
I hope it helps!

Categories

Find more on Data Type Conversion 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!