loop through files in struct

4 次查看(过去 30 天)
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!

采纳的回答

Bob Thompson
Bob Thompson 2019-6-24
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 个评论
Anna Go
Anna Go 2019-6-24
Hi Bob,
thanks for your quick reply. That would work if the files would be already sorted. But they are randomly organised.Sorry I had to explain it better.
I can't attach the whole file but I have a screenshot below. They are not organised in the order I want them to be in the new table. So basically I want Vabe_1 next to Vabc_2, etc. It goes up to Vabc_906.
thanks!
Capture.PNG
Bob Thompson
Bob Thompson 2019-6-24
编辑:Bob Thompson 2019-6-24
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

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by