[SOLVED ALREADY] Loop through data struct with variable names
Mostrar comentarios más antiguos
EDIT:
Hi, So it seems like I was able to solve it already so yeah, Imma post the solution as an answer for people to look into it in case they have a similar problem.
Hi,
I am trying to loop through a structure called 'Erruptions'.
Now in this structure I have 3 more sub structs, thus it's length is 3.
The 3 structures have variable names 'E1', 'E2', etc. These are simply 1x2 doubles or vectors if you wanna call them that.
So by calling one of the structs I write
Erruptions.sub_struct
and I get its content
E1: [6.0014 1.0161]
E2: [4.5936 0.5191]
E3: [3.2693 0.2849]
E4: [2.7640 -0.0073]
E5: [2.3443 0.1345]
But when I want to get the number of elements it says it's only 1, doesn't matter if I use
length(Erruptions.sub_struct) % gives me ans = 1
or
size(Erruptions.sub_struct) % gives me ans = [1 1]
which is very confusing. I want to run a loop through every substruct but since it only recognizes them as one single element, opposed to the above shown 5, itleave the substruct after taking the first into consideration.
How can I solve this problem?
3 comentarios
"which is very confusing."
No, it is not.
The size of a structure is unrelated to how many fields it has.
"but since it only recognizes them as one single element, opposed to the above shown 5,"
A scalar structure only has one element, no matter how many fields it has. If you want to count the number of fields, why are you trying to get the size of the structure? Your confusion is caused by mixing up two different things.
"How can I solve this problem? "
Don't mix up the size of a structure with how many fields it has:
- If you want to loop over the elements of a structure then use its size/numel.
- If you want to loop over the fields of a structure then use its fieldnames.
Sokratis Panagiotidis
el 14 de Jul. de 2022
Steven Lord
el 14 de Jul. de 2022
One analogy or mental model I think helps is that of a bookshelf. One bookshelf (struct) may have many shelves (fields) and each shelf may contain just one item or a series of items (data in the field.)
Respuesta aceptada
Más respuestas (2)
Benjamin Thompson
el 14 de Jul. de 2022
0 votos
You want to index into the structure array, then pass one of those array elements to the length function:
>> S1.E1 = [1 1];
>> S2.E1 = [1 1];
>> SArray(1) = S1
SArray =
struct with fields:
E1: [1 1]
>> SArray(2) = S2
SArray =
1×2 struct array with fields:
E1
>> length(SArray.E1)
Error using length
Too many input arguments.
>> length(SArray(1).E1)
ans =
2
1 comentario
Stephen23
el 14 de Jul. de 2022
A much simpler way to create that structure:
S(1).E1 = [1,1];
S(2).E1 = [0,1];
Sokratis Panagiotidis
el 14 de Jul. de 2022
Categorías
Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!