Changing Current directory (cd) using a string variable.

17 Ansichten (letzte 30 Tage)
Christien Bowman
Christien Bowman am 12 Mär. 2020
Bearbeitet: Christien Bowman am 12 Mär. 2020
I'm trying to change directory into two levels of subfolders but am having trouble making cd(variable) accept the input argument.
Once into each subfolder, I need to call a function (dirf) that will create a batch file of all files in the cd.
Thanks!
%find directory
p = uigetdir
% Get a list of all files and folders in this folder ie: birds
files = dir;
names = {files.name};
% Get a logical vector that tells which is a directory.
dirFlags = [files.isdir] & ~strcmp(names, '.') & ~strcmp(names, '..');
% Extract only those that are directories. . and .. are up and down folder
% commands which is why they are removed
subDirsNames = names(dirFlags);
%gets data on how many subfolders in the cd there are
N = numel(subDirsNames)
% for loop for entering into each subdir
for ii=1:N
% selects subfolder ie: single bird folder
cdm = fullfile(p,subDirsNames(ii))
cdm = cell2mat(cdm)
cd(cdm)
% same logical process filter as before but for sub-sub folders. remove
% this part if you only have single level folders
subsubdir = dir;
subnames = {subsubdir.name}
subdirFlags = [subsubdir.isdir] & ~strcmp(subnames, '.') & ~strcmp(subnames, '..');
subsubDirsNames = subnames(subdirFlags);
NN = numel(subsubDirsNames)
% selects sub subfolder ie: timepoint or FD song/UD song
for jj=1:NN
cds = fullfile(p,subDirsNames(ii),subsubDirsNames(jj))
cds = cell2mat(cdm)
cd(cds)
dirf('*.wav','batch')
end
end
  2 Kommentare
Stephen23
Stephen23 am 12 Mär. 2020
Bearbeitet: Stephen23 am 12 Mär. 2020
@Christien Bowman : do you have a specific problem or question? You have shown us some code, but you have not asked us anything, nor given any error messages or warning that you might be getting.
Rather than messing around with slow cd, it would be simple and efficient to access data files using absolute/relative filenames. All MATLAB functions that read/write to data files accept absolute/relative filenames.
Note you can eliminate the . and .. folders in one line:
files = dir();
names = setdiff({files([files.isdir]).name},{'.','..'})
Christien Bowman
Christien Bowman am 12 Mär. 2020
Bearbeitet: Christien Bowman am 12 Mär. 2020
Thank you! That helps with the efficiency a lot.
I restarted MATLAB and 'cd' appears to be working correctly now.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Walter Roberson
Walter Roberson am 12 Mär. 2020
files = dir;
I think you mean
files = dir(p) ;

Kategorien

Mehr zu File Operations finden Sie in Help Center und File Exchange

Produkte


Version

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by