2017-03-02 7 views
0

루프의 구조 필드 값을 할당하려고합니다. 빈 값루프 matlab에 구조 필드 값의 할당

구조 선언 :

result_struct = struct('a',{},'b',{},'c',{},'d',{}) 

내가 그런 식으로 루프에 값을 할당하고 있습니다 :

% assume a, b, c, d are variables in my workspace 

% field names match with the variable names 

for index=1:n 

% some computation and store results in variables (a-d) 

    result_struct(index).a = a; 

    result_struct(index).b = b; 

    result_struct(index).c = c; 

    result_struct(index).d = d; 

end 

이 어떻게 다른 루프를 사용하여 필드에 값을 할당 할 수 있습니까? 그와 마찬가지로 :

for fname = fieldnames(result_struct)' 

result_struct(index).fname = fname; % field names and variable names match 

end 

답변

0

당신은 구조체합니다 (LEFF 편)에 할당 할 동적 필드 이름를 사용해야합니다. 오른쪽의 경우 일 수 있습니다. eval을 사용합니다.하지만 위험하므로 변수 fname을 파일에 저장 한 다음 fname에 액세스하기 전에 struct으로 다시로드하고 동적 필드 이름을 사용하는 것이 좋습니다.

names = fieldnames(result_struct);  

for k = 1:numel(names) 
    % Save variable to a file 
    save('tmp.mat', names{k});   

    % Load it back into a struct 
    tmp = load('tmp.mat', names{k}); 

    result_struct(index).(names{k}) = tmp.(names{k}); 
end 

다른 방법으로는, 당신은 단지 필드를 통해 루프를하지 않고 구조체에 전체 일을 변환하는 saveload 사용할 수 있습니다.

fields = fieldnames(result_struct); 

% Save all relevant variables to a file 
save('tmp.mat', fields{:}); 

% Load it back into the result_struct 
result_struct(index) = orderfields(load('tmp.mat'), fields); 
+0

안녕하세요 수 에버, 답장을 보내 주셔서 감사합니다. 실제로 루프없이 두 번째 방법을 시도 할 때 MATLAB 오류가 발생했습니다. 오류는 "유사하지 않은 구조 간의 아래 첨자 할당"이라고 표시됩니다. 새 구조체에로드 할 때 문제없이로드됩니다. 내가 관찰 한 것은 필드의 순서가 다르다는 것입니다. 그것은 역할을합니까? – asif

+0

이 코드가 작동합니다 : 모두 지우기; 모두 닫기; result_struct = ('a', {}, 'b', {}, 'c', {}, 'd', {}); result_index = 1; fields = fieldnames (result_struct) a = 1 : 3의 경우 의 경우 의 경우 b = 1 : 3 c = a + b; d = a-b; save ('tmp.mat', 입력란 {:}); result_struct (result_index) =로드 ('tmp.mat'); result_index = result_index +1; 끝 끝 result_table = struct2table (result_struct) – asif

+0

@asif 필드의 순서가 동일하도록 업데이트되었습니다. – Suever