How to run a matlab code for all folders in a directory?

I have one directory with many folders. Each folder contains a .txt file (eg, file1 contain number1.txt, file2 contain number2.txt etc). these files has 4 columns with double numbers.
Also I have, outside of this directories one matlab code that reads the .txt file, makes calculations and write a file with the results.
Is there a way to run tha matlab code for all the folders with automated manner? I mean to run the code with an easy way, and not running the matlab code one by one for each folder?

Réponses (2)

Stephen23
Stephen23 le 23 Avr 2021
Modifié(e) : Stephen23 le 23 Avr 2021
"Is there a way to run tha matlab code for all the folders with automated manner? "
Of course, just use DIR. For example:
P = 'absolute/relative path to the main folder';
S = dir(fullfile(P,'**','number*.txt'));
for k = 1:numel(S)
F = fullfile(S(k).folder,S(k).name)
yourfunction(F)
end

17 commentaires

Thank you. But I have a question. What yourfunction(F) means?
Stephen23
Stephen23 le 23 Avr 2021
Modifié(e) : Stephen23 le 23 Avr 2021
"What yourfunction(F) means?"
This is pseudo-code, to show you where you should call your function, with one filename as its input argument. You will have to adapt this to your own function (because you did not give any information, e.g. the name of your function, what input arguments it accepts. I cannot write code using information that I do not have).
Or perhaps you need to replace that line with some file-import function, and pass that data to your function. Again, I cannot say what you need to do, because you did not state what your function accepts and how it needs to be called.
Ok my code has name "mytestcode.m".
How should I modify you solution?
I am uploading the .m file and the .txt file that is required in order to run my code.
I hope that will helps you.
Thank you.
(.txt files have the same format with file1.txt. Each folder has a file like this .txt file. So, I would like to run mycodetest.m file for each folder in my directory)
Remove the number from the variable name "filename1".
Replace the first four lines of your script with this:
function mycodetest(filename)
Call it as shown in my answer:
mycodetest(F)
Is that you mean?
"Is that you mean?"
No. I wrote that you should replace the first four lines with the function signature that I gave you.
Instead you kept the first four lines and added the function signature as the sixth line.
Delete everything before line six. The function signature should be the first line of your file.
Ivan Mich
Ivan Mich le 23 Avr 2021
Modifié(e) : Ivan Mich le 23 Avr 2021
Ok thank you. One last question. If I want to create a .m that requires also one .xlsx file, excpet from .txt files, (I mean that I need 1 .txt and 1.xlsx file in order to run) how should I modify the code?
I mean Can add one more type of data that I need in filename?
If you need to read two files with the same name but different file extensions, then you can modify your code by generating the second filename based on the first one. Assuming that filename refers to the text file:
[P,N] = fileparts(filename);
xlsname = fullfile(P,sprintf('%s.xlsx',N));
Ivan Mich
Ivan Mich le 23 Avr 2021
Modifié(e) : Ivan Mich le 23 Avr 2021
The problem is that I have different name files and different file extentions. To be more specific I have the following names and extentions of files:
20200423_00.txt
epic.xlsx
size.txt
country.txt
In that case my matlab code takes into account all the 4 mentioned files.
each one of my folders contain all of these files. I have to say that in all folders ontl the first .txt file changes its name (all the other names of the files are stable).
Is there a way to make my purpose taking into account all the parameters I mentioned?
Stephen23
Stephen23 le 23 Avr 2021
Modifié(e) : Stephen23 le 26 Avr 2021
"Is there a way to make my purpose taking into account all the parameters I mentioned?"
Use DIR to loop over the folders. Within each folder you have a fixed number of known file names, these you can access using FULLFILE with those fixed names.
P = 'absolute/relative path to the main folder';
S = dir(fullfile(P,'*'));
C = setdiff({S([S.isdir]).name},{'..','.'});
for k = 1:numel(C)
F = fullfile(P,C{k})
...etc
end
To get the unknown file use DIR to get a list of the files in each folder, then use set difference to get the unknown filename. "First" file is not a valid attribute of any OS that I know of.
well I tried this code:
clc
clear
P = 'G:\Desktop_files\mydirectory';
S = dir(fullfile(P,'*'));
C = setdiff({S([S.isdir]).name},{'..','.'});
for k = 1:numel(C)
fullfile(P,C{k})
mycodetest
end
But command window shows me:
Error: File: mycodetest.m Line: 6 Column: 10
Function with duplicate name "mycodetest" cannot be defined.
I am uploading The files I have in a directory and the .m file ('Untitled.m) which is out of the folder
Could you please help me?
Stephen23
Stephen23 le 26 Avr 2021
Modifié(e) : Stephen23 le 26 Avr 2021
As I wrote earlier, the function definition should be the first line of the file (or be preceded only by comments and/or empty lines):
filename = '*.txt'; % <- delete this line
function mycodetest(filename) % <- first line of your file
and then call your function with the required input (apparently this is the current folder name):
P = 'G:\Desktop_files\mydirectory';
S = dir(fullfile(P,'*'));
C = setdiff({S([S.isdir]).name},{'..','.'}); % subdirectory names.
for k = 1:numel(C)
D = fullfile(P,C{k}); % this is a subdirectory of P (not a filename),
mycodetest(D) % so you still need to handle the filenames here.
end
Note that within your function you still have not included any code that in any way handles the file names (the function input is the folder name, which you have incorrectly named "filename"). You will need to use fullfile within the function (or prior to calling the function) to add the (known, fixed) filenames to the current foldername. For the "unknown" filename you could follow the approach I gave here (or even better, use prior-knowledge about that filename to restrict the DIR search).
Sometimes I prefer to realize this with some cellfun:
P = 'absolute/relative path to the main folder';
S = dir(fullfile(P,'**','number*.txt'));
F = fullfile({S.folder}, {S.name});
cellOutput = cellfun(@(f) yourfunction, F) % set UniformOutput=false if ... he output is non-uniform
Your for-loop based approach is helpful when dealing many/big files to get some user feedback (e.g. uiprogressdlg with k/numel(C))
After the corrections you mentioned command window shows me:
Error in mycodetest (line 4)
[d1,tex]= importdata(filename);
Error in Untitled (line 9)
mycodetest(D) % so you still need to handle the filenames here.
Caused by:
Error using fread
Invalid file identifier. Use fopen to generate a valid file identifier.
How can I solve it?
Stephen23
Stephen23 le 2 Mai 2021
Modifié(e) : Stephen23 le 5 Mai 2021
The most common cause of that error is the user supplying a filename that does not exist. The most common reasons for it not existing are 1) spelling mistakes and 2) an incorrect path.
Most likely you have not provided the complete filename (including the required absolute/relative filepath). You can check this yourself by printing the filename (or even better: using the debugging tools) of the file that you are trying to open.
Note that you will need to use FULLFILE to join the base filepath, the subdirectory name, and the filename. I suspect that you have forgotten to include the filename.
If you want further help with this then:
  • show the complete error message . This means all of the red text.
  • show the code that you are currently using.
  • show the complete filename that you are supplying to whatever function that imports the file data.

Connectez-vous pour commenter.

Catégories

En savoir plus sur File Operations dans Centre d'aide et File Exchange

Question posée :

le 23 Avr 2021

Modifié(e) :

le 5 Mai 2021

Community Treasure Hunt

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

Start Hunting!

Translated by