Run a code multiple times in different directories

Dear Matlab Users
I have 100 files which ordered by name like i_1 to i_100 and in each file I have a text file which called input.txt and a run.m file
which each time I shoud go to each directory and run this run.m which give me an output.txt by doing some changes in input.txt/ and this takes so long
My question is that how can I write a code in matlab which goes to each file and run the run.m file and save my output in that directory automatically!!!!
Thanks in advance for your help

6 Comments

I think for loop will be cool
The link provided by Walter has complete and sweet answers to the question.
Dear All, thanks for your help,
I used this code for doing my work, but it has a problem for openning and running the .m file in the folder, any idea??
D = 'H:\Projrct\list';
S = dir(fullfile(D,'*'));
N = setdiff({S([S.isdir]).name},{'.','..'}); % list of subfolders of D.
for ii = 20:25
T = dir(fullfile(D,N{ii},'*')); % improve by specifying the file extension.
savename = "run";
f = fopen([savename '.m'],'wt');
fclose(f);
run(savename);
end
Thanks in advance
"... and a run.m file"
Is run.m a script or a function?
I suspect that the name run.m will cause you problems. You should change their names.
"I wrote this code ..."
Actually you copied one of my answers, including the comments verbatim:
run.m is just an script which use some other functions in that file for doing some analysis in .txt file

Sign in to comment.

Answers (2)

"but it has a problem for openning and running the .m file in the folder, any idea??"
Your code opens a text file, and then closes it immediately, without writing anything to the file:
savename = "run";
f = fopen([savename '.m'],'wt');
fclose(f);
This means that run.m is totally empty (because you just discarded any content with the w option).
Then, immediately after creating a totally empty script, you run it:
run(savename);
What do you expect running an empty script should do? I would not expect it to do anything.
F=('E:\New_folder');
name=('ru.m'); % Name RUN
start=71; % Start Number
n=100; % End Number
%% Go to Address and RUN
L=string(F);
for i=start:1:n
L=string(F);
D=L+i;
cd (D);
run (name);
disp (i);
clear a b c
end

1 Comment

Avoid using cd in code like that.
It is not required to change directories to process data files: all MATLAB functions that read/write data files accept absolute/relative filenames.

Sign in to comment.

Categories

Find more on Data Import and Analysis in Help Center and File Exchange

Tags

No tags entered yet.

Asked:

on 28 Aug 2019

Edited:

on 5 Sep 2019

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!