How can I create a string array of values pulled from a struct in MATLAB?

Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error How can I create a string array of values pulled from a struct in MATLAB? on this date .

I have a MATLAB struct that I would like to pull a single text field from every entry and put these entries into a string array. An example struct can be created with the following:

allFiles = dir(fullfile('C:UsersusernameDocuments))

The above returns a structure array where each file is an entry with the fields “name”, “folder”, “date”, etc. If I call allFiles.name, I get each filename entry as a separate answer. It looks like

ans = 
    'exampleFile1.txt'
ans = 
    'exampleFile2.txt'

Alternatively, I can call [allFiles.name] and this simply concatenates the character arrays as follows

'exampleFile1.txtexampleFile2.txt'

The only solution I’ve found is to iterate through the list

filesArray = []
for k=1:length(allFiles)
    filesArray = [filesArray string(allFiles(k).name)]
end

and this returns a proper string array ["exampleFile1.txt" "exampleFile2.txt"].

Is there a more elegant solution to extract these entries directly into a string array without iteration?

Answer

Yes, you can collect all names in a cell array.

allNames = {allFiles.name};

Then to turn this into a string array, just do

allNames = string({allFiles.name});