Using 'union' function in a loop over fieldnames
조회 수: 2 (최근 30일)
이전 댓글 표시
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
답변 (1개)
Titus Edelhofer
2015년 8월 26일
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
Titus Edelhofer
2015년 8월 27일
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
참고 항목
카테고리
Help Center 및 File Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!