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.

6 visualizaciones (últimos 30 días)
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)
delete(string(Files(i)));
end
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.

Respuesta aceptada

Voss
Voss el 8 de Mzo. de 2024
Editada: Voss el 8 de Mzo. de 2024
Pass the file names as arguments to delete(). Since the names are already in a cell array, this is easy:
delete(Files{:})
Demonstration:
% make some .txt files:
writematrix(1,'1.txt')
writematrix(2,'2.txt')
writematrix(3,'3.txt')
% 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},{fn.name});
% delete the files:
delete(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
  5 comentarios
Stephen23
Stephen23 el 18 de Jun. de 2024
Editada: Stephen23 el 18 de Jun. de 2024
"This use of calling delete with a cell array of file names is not documented but probably should be in the documentation for delete."
This answer does not call DELETE with a cell array of filenames. In fact it calls DELETE with every filename as a separate input, exactly as documented: https://www.mathworks.com/help/matlab/ref/delete.html
This answer uses a comma-separated list generated from a cell array. A comma-separated list is a general syntactical feature of MATLAB that can be used with any function or operator:
Steve Van Hooser
Steve Van Hooser el 18 de Jun. de 2024
Yes, this is correct. Sorry for my error. DELETE does NOT take cell arrays as an input. (I just realized and was coming back to correct myself! You beat me to it.)
Thanks
Steve

Iniciar sesión para comentar.

Más respuestas (1)

Chuguang Pan
Chuguang Pan el 8 de Mzo. de 2024
maybe you can use cellfun.
Files={'1.txt','2.txt','3.txt'};
cellfun(@delete,Files)
  5 comentarios
Krishna Ghanakota
Krishna Ghanakota el 9 de Mzo. de 2024
I get the following response
'rm' is not recognized as an internal or external command,
operable program or batch file.

Iniciar sesión para comentar.

Categorías

Más información sobre Characters and Strings 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