Help with nested structure
19 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Manuel Arcangeletti
le 19 Avr 2019
Modifié(e) : Stephen23
le 22 Avr 2019
Hello,
I use Matlab for my data analysis. I did a script in which, as output, I obtain a nested structure organized by sublevels. Now I would like to access all my files and analyse them by groups.
So to say.... I would like to select only some of them and extrapolate some parameters from them, then I would like to do this for a different group of them and so on...
I have a structure array like this:
For example, I would like to calculate the mean of each column of the field Currents for all the levels "file_...." that have in the field "FolderLev_3" the value pH8 or things like this...
Is there an easy way to do it?
Thank you very much,
Manuel
0 commentaires
Réponse acceptée
Stephen23
le 19 Avr 2019
Modifié(e) : Stephen23
le 19 Avr 2019
This would be much easier if you had designed your data better.
In particular, rather than using nested structures (which are really not very convenient to access) and awkwardly forcing meta-data (the file names) into the fieldnames, you would be much better off using a simple non-scalar structure:
As long all of the nested structures have the same fields, then you can simply convert to a non-scalar structure (or best of all, redesign your script so that you do this right from the start):
% Fake data:
S.F1.A = 11;
S.F1.B = 12;
S.F1.C = 'Hello';
S.F2.A = 21;
S.F2.B = 22;
S.F2.C = 'World';
% Convert to non-scalar structure, no nesting:
Z = struct2cell(S);
Z = [Z{:}];
Read the link above to know the easy ways you can access data in a non-scalar structure, e.g.:
>> Z(2).B % simple indexing
ans = 22
>> mean([Z.A]) % comma-separated list
ans = 16
>> strcat(Z.C) % comma-separated list
ans = 'HelloWorld'
>> {Z.C} % comma-separated list
ans = {'Hello','World'}
You can trivially use indexing to select any "groups" of those files, just like indexing into any other type of array. Read more here:
And in future remember that meta-data (filenames, test parameters, indices, etc.) do NOT belong in fieldnames or variable names: forcing meta-data into such names just makes your code slow, complex, and buggy. Meta-data is data, so it should be stored in a variable (e.g. as the field name in your example structures).
2 commentaires
Stephen23
le 22 Avr 2019
Modifié(e) : Stephen23
le 22 Avr 2019
@Manuel Arcangeletti: please do not forget to accept my answer if it helped you! Otherwise, if you require more help or clarifications, then please ask.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Structures dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!