Using 'union' function in a loop over fieldnames
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Dears,
I Have a MatLab structure (see enclosed) I am running a loop over the fieldnames of this structure. This structure is composed as follow : COUNTRY.SOURCE.SCENARIO.CATEGORY.ENTITY. At one point I would like to compare the ENTITY linked with each CATEGORY using the 'union' function, and then output just a value of gases entails in all the CATEGORY together. I am currently using the following function.
function comboloop = loopoverV2(myStruct)
country = fieldnames(myStruct)
for countryidx = 1:length(country)
countryname = country{countryidx}
source = fieldnames(myStruct.(countryname))
for sourceidx = 1:length(source)
sourcename = source{sourceidx};
scenario = fieldnames(myStruct.(countryname).(sourcename))
for scenarioidx = 1:length(scenario)
scenarioname = scenario{scenarioidx};
category_full = fieldnames(myStruct.(countryname).(sourcename).(scenarioname));
category = intersect(category_full,category_header)
allGas = [];
for categoryidx = 1:length(category)
categoryname = category{categoryidx};
gas_full = fieldnames(myStruct.(countryname).(sourcename).(scenarioname).(categoryname))
gas = union(allGas,gas_full)
end
end
end
end
Unfortunately this is not working as I expected. Does anyone as any idea why? Thank you so much!
0 commentaires
Réponses (1)
Titus Edelhofer
le 26 Août 2015
Hi,
what do you mean by "not working as expected". Does it throw an error? Wrong result? Nothing happens?
One thing that you should change in any case is the initialization of allGas: since the fieldnames below are a cell array of strings, allGas should be an empty cell:
allGas = {};
Titus
3 commentaires
Titus Edelhofer
le 27 Août 2015
Hi David,
if you have this code:
allGas = {};
for categoryidx = 1:length(category)
categoryname = category{categoryidx};
gas_full = fieldnames(myStruct.(countryname).(sourcename).(scenarioname).(categoryname));
allGas = union(allGas,gas_full);
end
Then after the loop the variable allGas should contain a list of names, i.e., one cell array...?
But if in each category you want to store more than just the names of the gases you would need to do something different, more like
allGas = {};
for categoryidx = 1:length(category)
categoryname = category{categoryidx};
gas_full = struct2cell(myStruct.(countryname).(sourcename).(scenarioname).(categoryname));
allGas(end+1,:) = gas_full';
end
Maybe you can show us, what myStruct.(countryname).(sourcename).(scenarioname).(categoryname) looks like for one or two categories, and then what allGas should look like...? Titus
Voir également
Catégories
En savoir plus sur Resizing and Reshaping Matrices 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!