Reading text file with variable name
5 次查看(过去 30 天)
显示 更早的评论
Dear all
I wanted to read a text file with variable names in a loop. file names are 1.txt, 2.txt, 3.txt, and 4.txt. The files will be called during iteration repeatedly. I have an array that has the pattern of how the files should be called say: file_number=[1 1 1 2 2 2 3 3 3 4 4 4 1 1 1 2 2 2 3 3 3 4 4 4 ..]. I wonder if there is a way to call the files following this pattern.
Thanks
0 个评论
采纳的回答
Voss
2022-6-17
One way, using file_number in the file name:
file_number=[1 1 1 2 2 2 3 3 3 4 4 4 1 1 1 2 2 2 3 3 3 4 4 4];
for ii = 1:numel(file_number)
current_file_name = sprintf('%d.txt',file_number(ii))
% read the file current_file_name
end
Another way, which works for any set of file names:
file_number=[1 1 1 2 2 2 3 3 3 4 4 4 1 1 1 2 2 2 3 3 3 4 4 4];
file_names = {'a_file.txt' 'another_file.txt' 'yet_another_file.txt' 'you_guessed_it_another_file.txt'};
for ii = 1:numel(file_number)
current_file_name = sprintf('%s',file_names{file_number(ii)})
% read the file current_file_name
end
2 个评论
Voss
2022-6-17
编辑:Voss
2022-6-17
You're welcome! That's right, num2str also works!
As an alternative to all of these approaches, which create one file name at a time, it may be convenient to create all the file names at once, before the loop:
file_number=[1 1 1 2 2 2 3 3 3 4 4 4 1 1 1 2 2 2 3 3 3 4 4 4];
all_file_names = sprintfc('%d.txt',file_number)
for ii = 1:numel(file_number)
current_file_name = all_file_names{ii}
end
file_number=[1 1 1 2 2 2 3 3 3 4 4 4 1 1 1 2 2 2 3 3 3 4 4 4];
file_names = {'a_file.txt' 'another_file.txt' 'yet_another_file.txt' 'you_guessed_it_another_file.txt'};
all_file_names = file_names(file_number)
for ii = 1:numel(file_number)
current_file_name = all_file_names{ii}
end
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!