Clear Filters
Clear Filters

Hello, I have a cell array with the list of files I would like to delete. However I would not like to use a for loop to loop through each file to delete it.

7 views (last 30 days)
Files - A cell array of size 1x3 with file names to be deleted.
Files =
1×3 cell array
{'1.txt'} {'2.txt'} {'3.txt'}
Working Code :
for i = 1:length(Files)
However, I would like to write a single line of code without for loop to achieve the same.
Note: Every run of my code can have different number of files to be deleted. So hardcoding with the command
delete 1.txt 2.txt 3.txt
will not be helpful.

Accepted Answer

Voss on 8 Mar 2024
Edited: Voss on 8 Mar 2024
Pass the file names as arguments to delete(). Since the names are already in a cell array, this is easy:
% make some .txt files:
% get info about the .txt files:
fn = dir('*.txt') % 3 files found
fn = 3x1 struct array with fields:
name folder date bytes isdir datenum
% construct a cell array with the file names:
Files = fullfile({fn.folder},{});
% delete the files:
% confirm that all three files have been deleted:
fn = dir('*.txt') % 0 files found
fn = 0x1 empty struct array with fields: name folder date bytes isdir datenum

More Answers (1)

Chuguang Pan
Chuguang Pan on 8 Mar 2024
maybe you can use cellfun.
Walter Roberson
Walter Roberson on 8 Mar 2024
You need to account for special characters in file names.
% this will probably break if filenames have spaces or other issues
files = {'1.txt','2.txt','3.txt'};
comstr = sprintf(repmat('"%s" ',[1 numel(files)]),files{:});
system(['rm ' comstr]);
Krishna Ghanakota
Krishna Ghanakota on 9 Mar 2024
I get the following response
'rm' is not recognized as an internal or external command,
operable program or batch file.

Sign in to comment.


Find more on Programming Utilities in Help Center and File Exchange


Community Treasure Hunt

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

Start Hunting!