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

조회 수: 43 (최근 30일)
Ivan Mich
Ivan Mich 2021년 4월 23일
편집: Stephen23 2021년 5월 5일
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?

답변 (2개)

Stephen23
Stephen23 2021년 4월 23일
편집: Stephen23 2021년 4월 23일
"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
Ivan Mich
Ivan Mich 2021년 5월 2일
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 2021년 5월 2일
편집: Stephen23 2021년 5월 5일
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.

댓글을 달려면 로그인하십시오.


Attaullah Shafiq
Attaullah Shafiq 2021년 5월 1일
yes you can use dir function. plz visit dir func help

카테고리

Help CenterFile Exchange에서 File Operations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by