2015-08-26 102 views
0

考慮一個MATLAB結構用Matlab「聯盟」功能,我有一個環比的字段名如下:在一個循環

scenario = fieldnames(myStruct) 
for scenarioidx = 1:length(scenario) 
    scenarioname = scenario{scenarioidx}; 
    category = fieldnames(myStruct.(scenarioname)) 
    for categoryidx = 1:length(category) 
     categoryname = category{categoryidx}; 
     entity = fieldnames(myStruct.(scenarioname).(categoryname)) 
    end 
end 

這個循環返回我對每個類別的實體。現在,我想將所有這些實體合併到一個向量中。我試圖用「聯盟」的功能如下:

scenario = fieldnames(myStruct) 
for scenarioidx = 1:length(scenario) 
    scenarioname = scenario{scenarioidx}; 
    category = fieldnames(myStruct.(scenarioname)) 
    for categoryidx = 1:length(category) 
     categoryname = category{categoryidx}; 
     allEntity = {} 
     entity = fieldnames(myStruct.(scenarioname).(categoryname)) 
     combo_entity = union (allEntity, entity) 
    end 
end 

不幸的是,這只是返回相同的結果之前,而不是結合東西。 有沒有人有關於如何在這樣的循環中實現聯合功能的任何想法?

回答

1

簡單:

struct_entities = structfun(@struct2cell, myStruct, 'UniformOutput', false); 
    cell_entities = struct2cell(struct_entities); 
    all_entities = unique(vertcat(cell_entities{:})); 

的想法是:

  • 檢索單位和放棄的類別名稱;
  • 也放棄了場景名稱,因爲它們不是必需的;
  • 將累積的實體組裝在單個單元格數組中。

如果需要使用工會的,那麼代碼可以被改寫爲:

all_entities = {}; 

scenarios = fieldnames(myStruct); 
for si = 1:numel(scenarios) 
     categories = fieldnames(myStruct.(scenarios{si})); 
     for ci = 1:numel(categories) 
       entities = fieldnames(myStruct.(scenarios{si}).(categories{ci})); 
       all_entities = union(all_entities, entities); 
     end; 
end; 
+0

謝謝你這樣做的工作!不幸的是我需要在這個循環中實現聯合功能! – steve

+0

@steve我不明白。當你說你想*實現*'union'時,你的意思是你想要定義這個函數,或者只是使用標準函數? 'union'是一個標準函數,並且與set union有關。它僅適用於數字數組或字符串的單元數組。所有的「實體」事物都是數字,字符串還是其他東西? –

+0

我只需要使用標準的** union **功能。在運行我的**域名**循環時,**實體**是n×1單元格。 – steve