2017-10-30 9 views
2

多くの場合、計算のために構造化配列のデータの葉にアクセスする必要があります。 これはMatlab 2017bでどのように最適ですか?構造体の葉をMatlabのベクターとして返す方法は?

% Minimal working example: 
egg(1).weight = 30; 
egg(2).weight = 33; 
egg(3).weight = 34; 

someeggs = mean([egg.weight]) % works fine 

apple(1).properties.weight = 300; 
apple(2).properties.weight = 330; 
apple(3).properties.weight = 340; 

someapples = mean([apple.properties.weight]) %fails 
weights = [apple.properties.weight] %fails too 

% Expected one output from a curly brace or dot indexing expression, 
% but there were 3 results. 
+0

これはあなたの例や任意の構造のためだけですか? – gnovice

+0

''(k).b.c .... z'型の任意の構造体のための@gnovice私は 'z(k)'を書いています。しかし、それを構造に採用するためにソリューションのビットを少し変更する必要がある場合は問題ありません。 –

答えて

1

トップレベルのみが非スカラーstructure arrayあり、かつ以下のすべてのエントリがスカラー構造体である場合は、返されたベクトルであなたの計算を行い、その後、arrayfunへの呼び出しで葉を収集することができます。

>> weights = arrayfun(@(s) s.properties.weight, apple) % To get the vector 

weights = 

    300 330 340 

>> someapples = mean(arrayfun(@(s) s.properties.weight, apple)) 

someapples = 

    323.3333 

[apple.properties.weight]という理由は、ドットインデックス付けがapple.propertiesの構造のcomma-separated listを返すためです。このリストを新しい構造体配列に収集し、次のフィールドweightのインデックスにドットインデックスを適用する必要があります。

1

あなたは、一時的な構造体配列にpropertiesを収集し、その後、通常のようにそれを使用することができます。

apple_properties = [apple.properties]; 
someapples = mean([apple_properties.weight]) %works 

あなたも、より多くのネストされたレベルを有していた場合、これは動作しないでしょう。おそらく、このような何か:

apple(1).properties.imperial.weight = 10; 
apple(2).properties.imperial.weight = 15; 
apple(3).properties.imperial.weight = 18; 
apple(1).properties.metric.weight = 4; 
apple(2).properties.metric.weight = 7; 
apple(3).properties.metric.weight = 8; 

ない私は、このような構造を助言するだろうが、それはおもちゃの一例として動作すること。その場合は、前の2つの手順と同じ操作を行うか、arrayfunを使用します。

weights = arrayfun(@(x) x.properties.metric.weight, apple); 
mean(weights) 
関連する問題