0

I have a MatLab struct array as follow:

'country.source.scenario.category.entity= year'

I would like to loop over the existing 'country.source.scenario' combinations and produce cell or matrix containing the fields: category, entity and year. Anyone as an idea about how to do that? Thanks

Suever
  • 64,497
  • 14
  • 82
  • 101
steve
  • 511
  • 1
  • 9
  • 33
  • 2
    please provide a **short** example of what your input looks like and what is your expected output – Shai Aug 06 '15 at 13:05
  • @Shai - My input is a tree if data going from "countries" to "sources" to "scenarios" to "categories" to "entities" ending with "years" contained in a . Basically I have all kind of combinations (e.g. USA.CRF.HISTORY.CAT0.CH4= 2000 2001 2002). From that i would like to lock the existing COUNTRY.SOURCE.SCENARIO combination (such as USA.CRF.HISTORY) and build tables (or whatever other outputs) containing CATEGORY and ENTITY as X and Y and filled with the corresponding years. – steve Aug 06 '15 at 13:13
  • 2
    press "edit" above and edit details into your question. – nkjt Aug 06 '15 at 13:14

1 Answers1

1

You can use fieldnames to get the fields at each level, and isstruct at each sublevel to see if you need to keep drilling, e.g.

fields = fieldnames(str);
for field = fields'
    sub = str.(field{1});
    if isstruct(sub)
        %loop through fieldnames
    end
end

You can put it in a recursive function whereby inside the if you again call the function. I did not do it like that because it was not clear to me what you wanted as a result, it seemed like you only wanted the tags and not the values at the end.

A Hernandez
  • 484
  • 2
  • 7
  • @A Hernandez Thank you for your input! I was just doing that way: for fieldidx=1:length(fields) fieldname=fields{fieldidx}; if isstruct(struct.(fieldname)) but at some point I have any idea about how to organize the loop. At the end I would like to have an output (table) listing for the CATEGORIES as an header row, and ENTITIES as an header line and filled with the YEAR of each CATEGORIES.ENTITIES combinations! – steve Aug 06 '15 at 16:11