Loop cycle to input similar txt files
Mostrar comentarios más antiguos
Hello everybody, I'm trying to solve a problem to input data. I have 39 txt files that have similar names. The name has two variables and I'd like to import the data as a function that contains those two numbers.
So a general name of the file is "CV_d{m}_die{i}", i goes from 1 to 13 and m is equal to 100, 200 or 400.
I've done this
input_folder = 'folder'
files = dir(fullfile(input_folder, "*.txt"))
file_paths = fullfile({files.folder}, {files.name})
for i = 1:13
for m = [100 200 400]
Data_{m}_{i} = dlmread("CV_d{m}_die{i}.txt", ',', 4, 0)
end
end
So my idea was to do this loop and get 39 Data_m_i. Like Data_100_1, Data_200_1, Data_400_1, and then i=2...
But I get an error that says that the file could not be opened because there's no such file or directory.
Respuesta aceptada
Más respuestas (1)
Image Analyst
el 10 de Dic. de 2022
Editada: Image Analyst
el 10 de Dic. de 2022
Use the first snippet, not the second method like you're doing.
Avoid the problem of missing files by using dir() to get only files that actually exist.
% Specify the folder where the files live.
input_folder = 'C:\Users\yourUserName\Documents\My Pictures';
% Check to make sure that folder actually exists. Warn user if it doesn't.
if ~isfolder(input_folder)
errorMessage = sprintf('Error: The following folder does not exist:\n%s\nPlease specify a new folder.', myFolder);
uiwait(warndlg(errorMessage));
input_folder = uigetdir(); % Ask for a new one.
if input_folder == 0
% User clicked Cancel
return;
end
end
% Get a list of all files in the folder with the desired file name pattern.
filePattern = fullfile(input_folder, '*.txt'); % Change to whatever pattern you need.
theFiles = dir(filePattern);
for k = 1 : length(theFiles)
baseFileName = theFiles(k).name;
fullFileName = fullfile(theFiles(k).folder, baseFileName);
fprintf(1, 'Now reading %s\n', fullFileName);
% Now do whatever you want with this file name,
% such as parsing it to get i and m.
% Parse 'CV_dm_diei.txt'
underlineLocations = strfind(baseFileName, '_');
m = str2double(baseFileName(underlineLocations(1) + 2 : underlineLocations(2) - 1));
dieIndex - strfind(baseFileName, '_die');
i = str2double(baseFileName(dieIndex + 4: end - 4));
% Read in the data (code below is not mine or from the FAQ).
Data(k).value = dlmread(fullFileName, ',', 4, 0);
Data(k).m = m;
Data(k).i = i;
end
Categorías
Más información sobre Variables en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!