필터 지우기
필터 지우기

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

조회 수: 1 (최근 30일)
beau Blokker
beau Blokker 2021년 5월 31일
답변: Samay Sagar 2024년 2월 21일
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