2

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?

1 Answer 1

3

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});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.