2010-05-10 3 views
58

제 질문은 쉽게 요약 할 수 있습니다 : "왜 다음은 작동하지 않습니까?"MATLAB의 구조체 필드 이름 반복하기

teststruct = struct('a',3,'b',5,'c',9) 

fields = fieldnames(teststruct) 

for i=1:numel(fields) 
    fields(i) 
    teststruct.(fields(i)) 
end 

출력 :

ans = 'a' 

??? Argument to dynamic structure reference must evaluate to a valid field name. 

특히 teststruct.('a') 보낸 작업을 수행합니다. 그리고 fields(i)ans = 'a'을 출력합니다.

나는 주위에 내 머리를 얻을 수 없습니다.

for i = 1:numel(fields) 
    teststruct.(fields{i}) 
end 

단지와 다르게 표시되는 다른 셀 배열을 반환합니다 access data in your cell array에 괄호를 사용 : fieldnames 함수는 문자열의 cell array을 반환 이후

답변

75

당신은, fields에 액세스 할 수 중괄호 ({})를 사용해야합니다 문자 배열 :

>> fields(1) % Get the first cell of the cell array 

ans = 

    'a'  % This is how the 1-element cell array is displayed 

>> fields{1} % Get the contents of the first cell of the cell array 

ans = 

a    % This is how the single character is displayed 
+2

당신의 대답은 믿을 수 없을만큼 도움이되고 몇 년 동안 문자 그대로 나를 괴롭혔던 몇 가지 사항들을 정리했습니다. –

5

fns는 cellstr 배열입니다. 단일 문자열을 char로 가져 오려면() 대신 {}을 사용하여 색인을 생성해야합니다.

fns{i} 
teststruct.(fns{i}) 

와 그것의 인덱싱()은. "(이름)이"동적 필드 참조하고자하는 문자 배열과 같은 형식이 아닌 1 긴 cellstr 배열을 반환한다. 특히 디스플레이 출력에서 ​​서식을 혼동시킬 수 있습니다. 차이점을 확인하려면이 방법을 사용하십시오. fields 또는 fns는 셀 어레이 때문에

name_as_char = 'a' 
name_as_cellstr = {'a'} 
14

, 당신은 즉, 문자열 셀의 내용을 액세스하기 위해,에 중괄호 {}와 인덱스에 있습니다.

숫자를 반복하지 않고 fields을 직접 루프 할 수 있습니다. 어떤 배열을 통해 루프 할 수있는 깔끔한 Matlab 기능을 사용합니다. 반복 변수는 배열의 각 열의 값을 취합니다.

teststruct = struct('a',3,'b',5,'c',9) 

fields = fieldnames(teststruct) 

for fn=fields' 
    fn 
    %# since fn is a 1-by-1 cell array, you still need to index into it, unfortunately 
    teststruct.(fn{1}) 
end 
0

당신은 http://www.mathworks.com/matlabcentral/fileexchange/48729-for-each에서 각 도구 상자의를 사용할 수 있습니다.

>> signal 
signal = 
sin: {{1x1x25 cell} {1x1x25 cell}} 
cos: {{1x1x25 cell} {1x1x25 cell}} 

>> each(fieldnames(signal)) 
ans = 
CellIterator with properties: 

NumberOfIterations: 2.0000e+000 

사용법 : 내가 아주 많이 좋아

for bridge = each(fieldnames(signal)) 
    signal.(bridge) = rand(10); 
end 

. 물론 도구 상자를 개발 한 Jeremy Hughes에게 도움이 될 것입니다.