2014-03-19 129 views
1

我有一個包含兩個字段'word'和'number'的結構,需要找到一種方法爲所有具有相同編號的元素創建新的結構數組。 一個所述strucure陣列的例子可以是:在matlab中對結構數組進行排序

a=struct('word',{'meercat','window','lemon','dog','cheese','penguin'},'number',{4,2,2,2,2,1}) 

我試圖分裂結構分成單獨的陣列對於相同數目的詞語,例如:

a1=struct('word',{'meercat'},'number',{4}) 
a2=struct('word',{'window','lemon','dog','cheese'},'number',{2,2,2,2}) 
a2=struct('word',{'penguin'},'number',{1}) 

回答

2

提取號碼和使用邏輯索引:

a = struct('word' , {'meercat','window','lemon','dog','cheese','penguin'}, ... 
      'number', {4,2,2,2,2,1}) 

% extract numbers 
num = [a(:).number] 

% indexing 
a1 = a(num == 4) 
a2 = a(num == 2) 
a3 = a(num == 1) 

你可以的Automize它:

sortedStructs = arrayfun(@(x) a(num == x), unique(num),'uni',0) 

它返回一個單元陣列與一個結構爲每個編號:

sortedStructs{1} = 

     word: 'penguin' 
    number: 1 

sortedStructs{2} = 

1x4 struct array with fields: 

    word    
    number 

sortedStructs{3} = 

     word: 'meercat' 
    number: 4 

'stable'屬性添加到unique,如果你想保持原來的順序:unique(num,'stable')