loop through files in struct

조회 수: 5 (최근 30일)
Anna Go
Anna Go 2019년 6월 24일
편집: Bob Thompson 2019년 6월 24일
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