2017-10-30 1 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

'a (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; 

아니요. 나는 그런 구조를 권하고 싶지는 않지만 장난감 예제로 작동합니다. 이 경우 이전 단계와 동일한 단계를 수행하거나 arrayfun을 사용할 수 있습니다.

weights = arrayfun(@(x) x.properties.metric.weight, apple); 
mean(weights) 
관련 문제