Combining structs into one struct.

1 次查看(过去 30 天)
Sam Litvin
Sam Litvin 2020-5-8
评论: Stephen23 2020-5-8
Hello, I have several structs that I would like to combine together into one. The issue I find is that the data for some reasons gets completely jumbled. Each time the file runs, the columns from one struct become a part of another and I cannot figure out why
CombineGLMParam('2_2_2', '2_3_2','2')
CombineGLMParam(0, '2_5_1','2')
function CombineGLMParam(bat1,bat2,bat)
%Combine GLM parameters by putting in the bat and the file. If bat1 is not 0, open the bat1 file and create a file GLM bat.
% If it is 0, open the GLM Bat file and append the bat 2 file to GLM.
if bat1~=0
b1=load([dirf,'Bat_',bat1,'_GLM_Params.mat']);
b2=load([dirf,'Bat_',bat2,'_GLM_Params.mat']);
b1=struct2cell(b1)
b2=struct2cell(b2)
else
b1=load([dirf,'GLM_',bat,'.mat']);
b2=load([dirf,'Bat_',bat2,'_GLM_Params.mat']);
b1=struct2cell(b1.b4)
b2=struct2cell(b2)
end
for n=1:size(b2,1)
b3{n}=[b1{n}' b2{n}']';
end
Header={'ThetaX', 'ThetaY', 'ThetaZ', 'Td', 'Vd', 'Vw', 'Hd', 'Hw', 'Ld','Lw'};
b4=cell2struct(b3, Header, 2)
save([dirf,'GLM_',bat,'.mat'], 'b4')
  1 个评论
Stephen23
Stephen23 2020-5-8
I recommend avoiding struct2cell and cell2struct for this, because there is no guarantee about the existence or order of the structure fields. Just use fieldnames and loop over the fields:

请先登录,再进行评论。

回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by