Extracting a vector from a struct

109 views Asked by At

I got a struct after using dir(directoryName). I want to get a vector containing all the file names in that folder.

  • How do I extract a vector of names from the struct?
  • Is there a better way to get a vector with the names of all files in a directory?
1

There are 1 answers

0
gnovice On BEST ANSWER

Here's how you can do this:

dirData = dir(directoryName);
fileNames = {dirData(~[dirData.isdir]).name};

This works by making use of comma-separated lists. When you have a structure array and you index a field with the dot operator, you get a comma-separated list of values that you can then pass to a function or collect with square or curly brackets. This code:

...[dirData.isdir]...

Collects the isdir field from every structure in the array, putting the values in a vector using square brackets so it can be used as a logical index. Then this code:

... {dirData(...).name};

Collects the name field from every structure in the array, putting the strings in a cell array.