Reputation: 49
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:\Users\username\Documents))
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?
Upvotes: 2
Views: 199
Reputation: 6863
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});
Upvotes: 3