How do I get cd to work properly?

16 visualizaciones (últimos 30 días)
Abinand Rejimon
Abinand Rejimon el 15 de Jun. de 2022
Comentada: Abinand Rejimon el 15 de Jun. de 2022
I want to create a code that will parse through 15 folders (X_1, X_2, X_3) and open a subfolder folder 'Y_*' in each of these fifteen folders and open one document in the directory (example: X_1/Y_1/*.coord) I can do this easily in the command window using cd and I am able to code a for loop that will parse through the main X folders but I cannot figure out a way to open a folder with only part of the string. All of the subfolders start with Y_ but end with different numbers. I want Matlab to open the folder regardless of what number it is and only examine 'Y_'
I have tried doing this but I always get an error. How do I write this?
cd X_1/Y_*
Error using cd
Unable to change current folder to '/users/mss.system.V2roDc/Y_*' (Name is nonexistent or not a folder).

Respuesta aceptada

Steven Lord
Steven Lord el 15 de Jun. de 2022
The cd function doesn't accept wildcards. You could use dir (which does) and iterate through the list of directories in its output. I would avoid actually using cd to change directory; instead use fullfile to assemble the path to the file and then pass that path into whatever file reader you're using.
d = fullfile(matlabroot, 'toolbox', 'matlab', 'general')
d = '/MATLAB/toolbox/matlab/general'
howManyFilesAndDirs = numel(dir(d))
howManyFilesAndDirs = 82
f = fullfile(d, 'bench.dat')
f = '/MATLAB/toolbox/matlab/general/bench.dat'
theText = fileread(f);
theLines = split(theText, newline);
theLines(1:5)
ans = 5×1 cell array
{'MATLAB(R) Benchmark Data.' } {' ' } {'Copyright 1984-2022 The MathWorks(R), Inc.' } {' LU FFT ODE Sparse 2-D 3-D'} {'Mac mini, macOS 10.15.7, Intel Core i7 @ 2.3 GHz 1.6177 0.5956 0.7646 0.6468 0.8542 0.5738' }
  1 comentario
Abinand Rejimon
Abinand Rejimon el 15 de Jun. de 2022
This is really helpful! Thank you so much for your assistance.

Iniciar sesión para comentar.

Más respuestas (1)

Image Analyst
Image Analyst el 15 de Jun. de 2022
I agree with Steve and the FAQ:
Don't use cd. Use fullfile and possibly sprintf to build up your full file name (folder plus base file name plus extension).
  1 comentario
Abinand Rejimon
Abinand Rejimon el 15 de Jun. de 2022
Thank you! I will look into those functions.

Iniciar sesión para comentar.

Categorías

Más información sobre File Operations en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by