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
嗨Suever,感謝您的答覆。當我嘗試第二種方法(沒有循環)時,其實我得到了MATLAB錯誤。錯誤說「不同結構之間的下標分配」。當我加載到新結構時,它會毫無問題地加載。我觀察到的是字段的順序是不同的。它是否發揮作用? – asif
此代碼有效:清除所有; 關閉所有; ('a',{},'b',{},'c',{},'d',{}); result_index = 1;對於a = 1:3 fields = fieldnames(result_struct) 對於b = 1:3 c = a + b; d = a-b; save('tmp.mat',fields {:}); result_struct(result_index)= load('tmp.mat'); result_index = result_index + 1; 結束 結束 result_table = struct2table(result_struct) – asif
@asif更新以確保字段具有相同的排序。 – Suever