Reading a specific ASCII format file
古いコメントを表示
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.
採用された回答
その他の回答 (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
2024 年 1 月 17 日
編集済み: Venkat Siddarth Reddy
2024 年 1 月 18 日
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!
カテゴリ
ヘルプ センター および File Exchange で Text Files についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!