loop through files in struct
5 views (last 30 days)
Show older comments
Hi everyone, I have a struct class where the files in the struct are called:
Vabc_1, Vabc_2, ...., Vabc_900
I wanted to loop through the structure and execute a command (take the information out of a struct element nad put it into a seperte table/array)
my idea was do do something like this. However I can't use a variable to call a file in the struct element.
for i = 1:length(busV)
for i = 1:length(structData)
chosenFile = 'Vabc_' + string(i) %This is the piece of code I am struggeling with
newTable(:,i) = structData.chosenFile.(i)
end
thanks for your help!
0 Comments
Accepted Answer
Bob Thompson
on 24 Jun 2019
I'm going to assume that your structure already has a variable that contains the file name, and you are just trying to reference it. With a multidimensional structure that type of call should be something like this.
for i = 1:length(structData)
filename = structData(i).file;
end
.file is a generic reference, something that I made up because I don't know what you have called it in your code. You will need to change this for it to be workable.
2 Comments
Bob Thompson
on 24 Jun 2019
Edited: Bob Thompson
on 24 Jun 2019
Ok, so you actually need to sort the values first. There are a couple of options for how to do this.
First, you can try sorting the rows based on the file name. I'm not sure if it will sort correctly because I don't remember exactly how Matlab treats integers in a string. Add this before your loop.
structData = sortrows(structData,'filenamefield');
Ideally that will sort the structure elements based on the filename field into ascending order. If it does not then it will likely give you the exact same value as an output. If this is the case then try the second method.
The second method is to create the ideal string, as you had already (chosenfile should be fine, I think), and then to use logic indexing to call the proper field.
for i = lenght(structData)
chosenFile = 'Vabc_' + string(i);
stuff = structData([structData.filenamefield] == chosenFile).fieldIwant;
end
More Answers (0)
See Also
Categories
Find more on Structures in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!