How to consecutively import the data of multiple .txt files in a function?

1 次查看(过去 30 天)
Dear reader,
I would like to load multiple .txt files consecutively (one-by-one) in a Matlab function.
The .txt is a 16 x 513 matrix in which the first row and column consists of text (headers). The rest of the rows and columns contain numeric data. The function is only running while loading the data of the .txt file into the function.
Could someone explain me what I have to add to the script below so that only the data of the .txt files will be loaded into the function consecutively?
Thanks in advance!

回答(1 个)

Samay Sagar
Samay Sagar 2024-2-21
To load only the numeric data from the TXT files into your function consecutively, you will need to modify the loop that processes the files. Since the first row and column contain text headers, you'll need to skip these when loading the data. You can use the “readmatrix” function in MATLAB, which is designed to handle such cases by specifying the range of data to read.
Here's how you can modify the script
myFolder = pwd; % Replace XXXXXX with the path to your folder
if ~isfolder(myFolder)
errorMessage = sprintf('Error: The following folder does not exist:\n%s', myFolder);
uiwait(warndlg(errorMessage));
return;
end
filePattern = fullfile(myFolder, '*.txt');
txtFiles = dir(filePattern);
for k = 1:length(txtFiles)
baseFileName = txtFiles(k).name;
fullFileName = fullfile(myFolder, baseFileName);
fprintf(1, 'Now reading %s\n', fullFileName);
% Read the numeric data from the file, skipping the first row and column
numericData = readmatrix(fullFileName, 'Range', 'B2');
% Pass the numeric data to your function
end
Read more about “readmatrix” here:

类别

Help CenterFile Exchange 中查找有关 Data Import and Analysis 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by