I wanted to know how it is possible to delete only the contents (files and folders) of a specific folder, without deleting this folder. Delete only child folders.
I have tried this, but this will delete the folder too:
rmdir(listFolders,'s')
This function work fine:
function rmSubDir( pathDir )
d = dir(pathDir);
isub = [d(:).isdir];
nameFolds = {d(isub).name}';
nameFolds(ismember(nameFolds,{'.','..'})) = [];
for i=1:size(nameFolds,1)
dir2rm = fullfile(pathDir,nameFolds{i});
rmdir(dir2rm, 's');
end
end
Related
Using Matlab, I want to move the images present in the same directory in two new directories according to their name.
In the directory there are two set of image' name: 'neg-0.pgm', 'neg-1.pgm', 'neg-2.pgm', ... and 'pos-0.pgm', 'pos-1.pgm', 'pos-2.pgm', ...
I tried different functions to change the image directory but I wasn't able to make the operation successfully.
My code is:
if not(exist('./CarDataset/TrainImages/PosImages', 'dir'))
mkdir ./CarDataset/TrainImages PosImages
end
if not(exist('./CarDataset/TrainImages/NegImages', 'dir'))
mkdir ./CarDataset/TrainImages NegImages
end
trainIm = dir('./CarDataset/TrainImages/*.pgm');
for i = 1:size(trainIm, 1)
if(strcmp(trainIm(i).name, 'neg*.pgm'))
save(fullfile('./CarDataset/TrainImages/NegImages', ['neg-' num2str(i) '.pgm']))
end
end
I don't get any error but the new directories are still empty.
I believe there are two issues going on:
1 - using strcmp in the if statement with a wildcard (*) may not work properly
2 - use movefile instead of save.
https://www.mathworks.com/help/matlab/ref/movefile.html
See below code (use after you have made the new directories):
origDir = './CarDataset/TrainImages/';
trainIm = dir([origDir '*.pgm']);
for i = 1:size(trainIm, 1)
origFile = trainIm(i).name;
if contains(trainIm(i).name, 'neg'))
newDir = './CarDataset/TrainImages/NegImages/';
else
newDir = './CarDataset/TrainImages/PosImages/';
end
movefile([origDir trainIm(i).name], newDir);
end
I have a folder containing sequential subfolders 000001_wd, 000002_wd,... in which I'm reading data contained in a file called 'plane.txt'. Some of the subfolders don't contain that file. I wish to skip them in a for-if else loop, but it is unable open file.
Tried changing or adding paths but nothing seems to work
workdir = 'D:\wass\test\output_925\';
cd(workdir)
data_frames = [1:1:37];
nframes = numel(data_frames);
V = zeros(nframes,3);
times = zeros(nframes,1);
ii=1;
prev = cd(workdir);
for frame = data_frames
fprintf('Processing frame %d\n',frame);
wdir = sprintf( '%s%06d_wd/', workdir, frame);
cd(wdir)
if exist('plane.txt')
plane_data = importdata([wdir,'plane.txt']);
times(ii) = double(ii-1)/fps;
else
times(ii) = double(ii-1)/fps;
end
ii=ii+1;
end
cd(prev);
fprintf('Saving data...\n');
I want to just continue through the loop until the last subfolder. Is there something I'm missing because the file I'm skipping is in a subfolder of my sequence?
The statement exist('plane.txt') tests to see if the file 'plane.txt' exists in the current directory. If it does, you read a file in the wdir subdirectory. Obviously, you haven't tested if that file exists.
I would simplify your code by reading the data within a try/catch block:
workdir = 'D:\wass\test\output_925\';
data_frames = 1:37; % <- don't use square brackets here, they're useless
nframes = numel(data_frames);
times = zeros(nframes,1);
for ii=1:nframes
frame = data_frames(ii);
fprintf('Processing frame %d\n',frame);
wdir = sprintf( '%s%06d_wd/', workdir, frame);
try
plane_data = importdata([wdir,'plane.txt']);
% do something with plane_data here...
catch
% ignore error
end
times(ii) = double(ii-1)/fps;
end
% ...
Note that I never used cd. You don't need to change directories to read data, and it's always better not to. The importdata statement uses an absolute path, so it does not matter what the current directory is.
A different approach involves getting a list of all files that match 'D:\wass\test\output_925\*\plane.txt':
files = dir(fullfile(workdir, '*', 'plane.txt'));
for ii=1:numel(files)
file = fullfile(files(ii).folder, files(ii).name);
plane_data = importdata(file);
% do something with plane_data here...
end
I have a cell array containing file names. I want to check for the existence of all of these files in the subject folder, and if any one does not exist I wish to send a continue to the top-most for-loop (see mock code). Is there a way to do this in a one or two liner, instead of 1) using a for-loop and a double if-statement, or 2) building a function that for-loops over exist().
subjects = {'/data/subject01','/data/subject02','/data/subject03'};
files = {'a.txt','b.txt','c.txt'};
for ii = 1:numel(subjects)
for jj = 1:numel(files)
fileExists = exist([subject{ii} '/' file{jj}],'file')
if ~fileExists
continue
end
end
if ~fileExists
continue
end
% Some code to execute if all files exist.
end
The *fun functions are just loops internally and are generally slower than the explicit loop. They also very often unnecessarily obfuscate the intent and behavior of the code.
You can use ismember with all and dir to make the approach clearer and remove the unnecessary loop:
subjects = {'./data/subject01','./data/subject02'};
files = {'a.txt','b.txt','c.txt'};
for ii = 1:numel(subjects)
filelist = dir(fullfile(subjects{ii}, '*.txt'));
foundfilenames = {filelist(:).name};
if all(ismember(files, foundfilenames))
fprintf('All %u files are here: %s\n', numel(files), subjects{ii})
else
fprintf('All %u files are not here: %s\n', numel(files), subjects{ii})
end
end
With my folder structure:
/data
/subject01
a.txt
b.txt
/subject02
a.txt
b.txt
c.txt
I see the following, as expected:
All 3 files are not here: ./data/subject01
All 3 files are here: ./data/subject02
You could remove the loop by iterating over all combinations of the two arrays:
subjects = {'/data/subject01','/data/subject02','/data/subject03'};
files = {'a.txt','b.txt','c.txt'};
a=numel(subjects);
b=numel(files);
k=a*b;
paths = arrayfun(#(ii)[subjects{mod(ii-1,a)+1} '/' files{ceil(ii/b)}],1:k,'uniformoutput',0);
checkExist = cellfun(#exist, paths, repmat({'file'},1,k));
if all(checkExist)
% Some code to execute if all files exist
end
Resolved it with a cellfun and by string arrays. Technically there is still a for-loop but it resolves the double if-statement. I will leave this question open for better solutions.
subjects = {'/data/subject01','/data/subject02','/data/subject03'};
files = string({'a.txt','b.txt','c.txt'});
for ii = 1:numel(subjects)
paths = subject{ii} + files;
checkExist = cellfun(#exist, cellstr(paths), repmat({'file'},size(paths))
if ~all(checkExist(:))
continue
end
% Some code to execute if all files exist.
end
I have a simple question but I don't know how to solve it.
I want to process all the files in a folder and I want to write the output values on a separate line on a matrix. After direct the folder and get the list of the files and their names
filePattern=fullfile( myPath,'*.txt')
I applied a 'loop'. To save the results on each line for every file, this is what I'm doing but it doesn't work (the code works with one file, not with all of them).
text= {baseFileName, result2b, result3b, result4b, result5b};
Is there something wrong?
Thanks in advance! Greetings,
Emma
PD)
myPath = 'C:\SP\';
% if ~isdir(myPath)
% errorMessage = sprintf('Error: The following folder does not exist:\n%s', myFolder);
% uiwait(warndlg(errorMessage));
% return;
a= dir (fullfile(myPath,'*.DIM')); %
fileNames = { a.name };
filePattern=fullfile( myPath,'*.txt');
txtFiles= dir(filePattern);
for k = 1:length(txtFiles)
baseFileName=txtFiles(k).name;
fullFileName= fullfile(myPath,baseFileName);
fid=fopen(fullFileName, 'r+');
for i = 1:18
m{i} = fgetl(fid);
end
result2 = m{18};
result2b= result2([12:19]);
(...)
EDIT:
I added a screenshoot about my variables. Is it possible because of the txtFiles is wrong?
i wrote a code that analyze a video file and then plot data on a graph then
save this graph into
excel and jpg.
but my problem is that i have more than 200 video to analyze in around 20 folder,
so i need to automate this code to loop inside folders and analyze each *.avi file inside and
.. So any ideas or suggestions
Really appreciate your help
I need to know how to loop folders and get files inside and the apply a function to these files in that folder
Please note that my function that i also want to save graph result to img, should i then include full path while saving ? and how can i do it ?
The dir and fullfile commands are what you need. Depending on your directory structure, something like this:
video_dir = 'videos';
% I'm not sure if there's a way to directly get a list of directories, but
% this will work
video_dir_children = dir(video_dir);
video_subdirs = [];
for ix = 1 : length(video_dir_children),
% note we're careful to kick out '.' and '..'
% (and any other directory starting with a '.')
if(video_dir_children(ix).isdir && video_dir_children(ix).name(1) ~= '.')
video_subdirs = [video_subdirs; video_dir_children(ix)];
end
end
for ix = 1 : length(video_subdirs),
this_dir = fullfile(video_dir, video_subdirs(ix).name);
avi_files_in_this_dir = dir(fullfile(this_dir, '*.avi'));
for jx = 1 : avi_files_in_this_dir,
doVideoProcessing(fullfile(this_dir, avi_files_in_this_dir(jx).name));
end
end