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 ExchangeStructures についてさらに検索

製品

リリース

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