Reading a specific ASCII format file
Show older comments
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
More Answers (2)
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);
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)
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 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!