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.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/637290/image.jpeg)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/637295/image.jpeg)
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?
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/637300/image.jpeg)
Thanks in advance!
0 件のコメント
回答 (1 件)
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:
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Data Import and Analysis についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!