英文:
Load in array txt files name to process in Matlab
问题
可以将文件夹中的所有*.txt
文件加载到一个数组中吗?
因为我需要制作大量的绘图,每个绘图都需要一个不同的文本文件作为输入。所以我在想,如果我有一个包含所有文件名的单一数组,我可以使用for循环
一次性创建所有图像并保存它们。
这是可能的吗?
目前,我通过手动更改文件名来执行此操作
T = readtable('file.txt');
进行一些处理并保存它 saveas(gcf,'File.png');
英文:
Is it possible to load all the *.txt
inside a folder (or any other file) into an an array?
Because I need to do a lot of plots, each one having an input a different text file. So I was thinking that if I have a single array with all the name files, I could use a for cycle
creating all the images at once and save it.
Is it possible?
For the moment I do this by hand, changing the name file
T = readtable('file.txt');
do some process and save it saveas(gcf,'File.png');
答案1
得分: 1
以下是翻译好的代码部分:
你可以通过以下代码获取文件夹中的所有文本文件:
d = dir('*.txt');
然后循环处理它们,并以相同的名称保存:
for ii = 1:numel(d)
[~,filename] = fileparts(d(ii).name);
T = readtable(d(ii).name);
% 做一些处理...
saveas(gcf, [filename, '.png']);
end
如果你的当前工作目录不是文本文件所在的地方,那么你可以使用类似的代码,但需要使用完整的文件路径(这可能更稳健):
d = dir('C:\Documents\MyStuff\*.txt');
for ii = 1:numel(d)
[~,filename] = fileparts(d(ii).name);
T = readtable(fullfile(d(ii).folder, d(ii).name));
% 做一些处理...
saveas(gcf, fullfile(d(ii).folder, [filename, '.png']));
end
希望这对你有所帮助。
英文:
You can get all text files in a folder with
d = dir( '*.txt' );
Then loop over them, doing something, then saving with the same name
for ii = 1:numel(d)
[~,filename] = fileparts( d(ii).name );
T = readtable( d(ii).name);
% do stuff...
saveas( gcf, [filename, '.png'] );
end
If your current working directory isn't where the text files are, then you can use something similar but with full file paths (probably more robust regardless):
d = dir( 'C:\Documents\MyStuff\*.txt' );
for ii = 1:numel(d)
[~,filename] = fileparts( d(ii).name );
T = readtable( fullfile( d(ii).folder, d(ii).name );
% do stuff...
saveas( gcf, fullfile( d(ii).folder, [filename, '.png'] ) );
end
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论