Hi, is there a simpler and shorter way for writing this code?
The code is working fine so I assume I'm writing it correctly, just that if there are more extensions to be added, it will be long and repetitive.
extensions = [...
dir(fullfile(folder,'*.txt'));
dir(fullfile(folder, '*.py'));
dir(fullfile(folder, '*.mp3'));
dir(fullfile(folder, '*.exe'));
dir(fullfile(folder,'*.jpg'));
];

 채택된 답변

Voss
Voss 2023년 2월 5일

0 개 추천

You can put those dir() calls in cellfun:
ext = {'*.txt','*.py','*.mp3','*.exe','*.jpg'};
extensions = cellfun(@(x)dir(fullfile(folder,x)),ext,'UniformOutput',false);
extensions = vertcat(extensions{:});
Then when you need to add more extensions, just include them in the 'ext' variable.

댓글 수: 4

Lisa Loh
Lisa Loh 2023년 2월 5일
편집: Lisa Loh 2023년 2월 5일
Thank you for answering!
Your code works fine.
Does @(x) means anonymous cell function? I'm confused about the usage of x in the 2nd line.
I've read up about vertcat, based on my understanding is it to concatenate the extension files instead of extensions?
Voss
Voss 2023년 2월 5일
편집: Voss 2023년 2월 5일
You're welcome!
I placed all the character arrays indicating the file types you want to check for ('*.txt', '*.py', etc.) into the cell array 'ext'.
Then cellfun is used to apply a function to each element of that cell array. In this case the function is the anonymous function @(x)dir(fullfile(folder,x)). Each file type to check for will be substituted in for x when cellfun runs, so cellfun is essentially doing the same thing as the sequence of dir() calls you had in your original code.
In general, the result from a dir() call is a struct column vector (i.e., a struct array of size N-by-1 for some N), so I use 'UniformOutput',false so that cellfun returns a cell array containing all those struct column vectors.
Then I vertcat() the struct arrays together at the end into a single struct column vector containing the results for all the file types. This is the same operation your original code did to combine the results of all the dir() calls.
(Without 'UniformOutput',false, cellfun would try to combine the results from the dir() calls into a single struct array under the assumption that each dir() call returns a scalar struct, and this would fail and throw an error if any of the dir() calls returns a non-scalar struct, i.e., if not exactly one file of any given type was found.)
Lisa Loh
Lisa Loh 2023년 2월 6일
Thank you very much for the deep explanation!
Voss
Voss 2023년 2월 6일
You're welcome!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Structures에 대해 자세히 알아보기

제품

릴리스

R2022b

태그

질문:

2023년 2월 5일

댓글:

2023년 2월 6일

Community Treasure Hunt

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

Start Hunting!

Translated by