{"id":202,"date":"2009-10-15T18:18:06","date_gmt":"2009-10-15T18:18:06","guid":{"rendered":"https:\/\/blogs.mathworks.com\/loren\/2009\/10\/15\/concatenating-structs\/"},"modified":"2016-08-07T13:43:28","modified_gmt":"2016-08-07T18:43:28","slug":"concatenating-structs","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/loren\/2009\/10\/15\/concatenating-structs\/","title":{"rendered":"Concatenating structs"},"content":{"rendered":"<div xmlns:mwsh=\"https:\/\/www.mathworks.com\/namespace\/mcode\/v1\/syntaxhighlight.dtd\" class=\"content\">\r\n   <introduction>\r\n      <p>From time to time, I get asked or see queries about how to concatenate two <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2009b\/techdoc\/ref\/struct.html\"><tt>struct<\/tt><\/a> arrays to merge the fields.  There's even a section in the <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2009b\/techdoc\/matlab_prog\/br04bw6-38.html#br04bw6-78\">documentation<\/a> covering this topic. I thought I'd show it here to help people out.\r\n      <\/p>\r\n   <\/introduction>\r\n   <h3>Contents<\/h3>\r\n   <div>\r\n      <ul>\r\n         <li><a href=\"#1\">Example Data<\/a><\/li>\r\n         <li><a href=\"#10\">mergeStruct<\/a><\/li>\r\n         <li><a href=\"#11\">Do You Need to Merge struct data?<\/a><\/li>\r\n      <\/ul>\r\n   <\/div>\r\n   <h3>Example Data<a name=\"1\"><\/a><\/h3>\r\n   <p>Suppose I've got some system for which I have collected information on a couple of individuals, including their names and\r\n      ages.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">s1.name = <span style=\"color: #A020F0\">'fred'<\/span>;\r\ns1.age = 42;\r\ns1(2).name = <span style=\"color: #A020F0\">'alice'<\/span>;\r\ns1(2).age = 29;<\/pre><p>Later, I go back and collect the individual's heights (in cm).<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">s2.height = 170;\r\ns2(2).height = 160;<\/pre><p>It would be great to merge these arrays now.<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">s1\r\ns2<\/pre><pre style=\"font-style:oblique\">s1 = \r\n1x2 struct array with fields:\r\n    name\r\n    age\r\ns2 = \r\n1x2 struct array with fields:\r\n    height\r\n<\/pre><p>Let me collect the field names.<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">fn1 = fieldnames(s1);\r\nfn2 = fieldnames(s2);\r\nfn = [fn1; fn2];<\/pre><p>Next, I ensure the fieldnames are unique.<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">ufn = length(fn) == unique(length(fn))<\/pre><pre style=\"font-style:oblique\">ufn =\r\n     1\r\n<\/pre><p>Next let me convert the data in my structs into cell arrays using <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2009b\/techdoc\/ref\/struct2cell.html\"><tt>struct2cell<\/tt><\/a>.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">c1 = struct2cell(s1)\r\nc2 = struct2cell(s2)<\/pre><pre style=\"font-style:oblique\">c1(:,:,1) = \r\n    'fred'\r\n    [  42]\r\nc1(:,:,2) = \r\n    'alice'\r\n    [   29]\r\nc2(:,:,1) = \r\n    [170]\r\nc2(:,:,2) = \r\n    [160]\r\n<\/pre><p>Next I merge the data from the 2 cell arrays.<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">c = [c1;c2]<\/pre><pre style=\"font-style:oblique\">c(:,:,1) = \r\n    'fred'\r\n    [  42]\r\n    [ 170]\r\nc(:,:,2) = \r\n    'alice'\r\n    [   29]\r\n    [  160]\r\n<\/pre><p>And finally, I construct the new struct using <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2009b\/techdoc\/ref\/cell2struct.html\"><tt>cell2struct<\/tt><\/a>.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">s = cell2struct(c,fn,1)<\/pre><pre style=\"font-style:oblique\">s = \r\n1x2 struct array with fields:\r\n    name\r\n    age\r\n    height\r\n<\/pre><p>I can check the output now.<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">s(1)\r\ns(2)<\/pre><pre style=\"font-style:oblique\">ans = \r\n      name: 'fred'\r\n       age: 42\r\n    height: 170\r\nans = \r\n      name: 'alice'\r\n       age: 29\r\n    height: 160\r\n<\/pre><h3>mergeStruct<a name=\"10\"><\/a><\/h3>\r\n   <p>Here's the function <tt>mergeStruct<\/tt> that I created to encapsulate the steps in this process, including some error checks.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">dbtype <span style=\"color: #A020F0\">mergeStruct<\/span><\/pre><pre style=\"font-style:oblique\">\r\n1     function sout = mergestruct(varargin)\r\n2     %MERGESTRUCT Merge structures with unique fields.\r\n3     \r\n4     %   Copyright 2009 The MathWorks, Inc.\r\n5     \r\n6     % Start with collecting fieldnames, checking implicitly \r\n7     % that inputs are structures.\r\n8     fn = [];\r\n9     for k = 1:nargin\r\n10        try\r\n11            fn = [fn ; fieldnames(varargin{k})];\r\n12        catch MEstruct\r\n13            throw(MEstruct)\r\n14        end\r\n15    end\r\n16    \r\n17    % Make sure the field names are unique.\r\n18    if length(fn) ~= length(unique(fn))\r\n19        error('mergestruct:FieldsNotUnique',...\r\n20            'Field names must be unique');\r\n21    end\r\n22    \r\n23    % Now concatenate the data from each struct.  Can't use \r\n24    % structfun since input structs may not be scalar.\r\n25    c = [];\r\n26    for k = 1:nargin\r\n27        try\r\n28            c = [c ; struct2cell(varargin{k})];\r\n29        catch MEdata\r\n30            throw(MEdata);\r\n31        end\r\n32    end\r\n33    \r\n34    % Construct the output.\r\n35    sout = cell2struct(c, fn, 1);\r\n<\/pre><h3>Do You Need to Merge struct data?<a name=\"11\"><\/a><\/h3>\r\n   <p>Do you ever need to merge data stored in structs when you gather new information?  Or are your structs static in nature? \r\n      If the information you collect is always the same sort of information, then you probably know the form of the structure when\r\n      you start, even if all the data isn't available at first.\r\n   <\/p>\r\n   <p>There is <a href=\"https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/7842-catstruct\">code<\/a> on the File Exchange to concatenate structures; I confess I have not tried it, but it is highly rated.  Does this post or\r\n      the File Exchange contribution help your work? \r\n   <\/p><script language=\"JavaScript\">\r\n<!--\r\n\r\n    function grabCode_60deb70ff18c4179be87db0fb4a2118f() {\r\n        \/\/ Remember the title so we can use it in the new page\r\n        title = document.title;\r\n\r\n        \/\/ Break up these strings so that their presence\r\n        \/\/ in the Javascript doesn't mess up the search for\r\n        \/\/ the MATLAB code.\r\n        t1='60deb70ff18c4179be87db0fb4a2118f ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' 60deb70ff18c4179be87db0fb4a2118f';\r\n    \r\n        b=document.getElementsByTagName('body')[0];\r\n        i1=b.innerHTML.indexOf(t1)+t1.length;\r\n        i2=b.innerHTML.indexOf(t2);\r\n \r\n        code_string = b.innerHTML.substring(i1, i2);\r\n        code_string = code_string.replace(\/REPLACE_WITH_DASH_DASH\/g,'--');\r\n\r\n        \/\/ Use \/x3C\/g instead of the less-than character to avoid errors \r\n        \/\/ in the XML parser.\r\n        \/\/ Use '\\x26#60;' instead of '<' so that the XML parser\r\n        \/\/ doesn't go ahead and substitute the less-than character. \r\n        code_string = code_string.replace(\/\\x3C\/g, '\\x26#60;');\r\n\r\n        author = 'Loren Shure';\r\n        copyright = 'Copyright 2009 The MathWorks, Inc.';\r\n\r\n        w = window.open();\r\n        d = w.document;\r\n        d.write('<pre>\\n');\r\n        d.write(code_string);\r\n\r\n        \/\/ Add author and copyright lines at the bottom if specified.\r\n        if ((author.length > 0) || (copyright.length > 0)) {\r\n            d.writeln('');\r\n            d.writeln('%%');\r\n            if (author.length > 0) {\r\n                d.writeln('% _' + author + '_');\r\n            }\r\n            if (copyright.length > 0) {\r\n                d.writeln('% _' + copyright + '_');\r\n            }\r\n        }\r\n\r\n        d.write('<\/pre>\\n');\r\n      \r\n      d.title = title + ' (MATLAB code)';\r\n      d.close();\r\n      }   \r\n      \r\n-->\r\n<\/script><p style=\"text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray\"><br><a href=\"javascript:grabCode_60deb70ff18c4179be87db0fb4a2118f()\"><span style=\"font-size: x-small;        font-style: italic;\">Get \r\n            the MATLAB code \r\n            <noscript>(requires JavaScript)<\/noscript><\/span><\/a><br><br>\r\n      Published with MATLAB&reg; 7.9<br><\/p>\r\n<\/div>\r\n<!--\r\n60deb70ff18c4179be87db0fb4a2118f ##### SOURCE BEGIN #####\r\n%% Concatenating Structs\r\n% From time to time, I get asked or see queries about how to concatenate\r\n% two\r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2009b\/techdoc\/ref\/struct.html |struct|>\r\n% arrays to merge the fields.  There's even a section in the\r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2009b\/techdoc\/matlab_prog\/br04bw6-38.html#br04bw6-78 documentation> covering this topic.\r\n% I thought I'd show it here to help people out.\r\n%% Example Data\r\n% Suppose I've got some system for which I have collected information on a\r\n% couple of individuals, including their names and ages.  \r\ns1.name = 'fred';\r\ns1.age = 42;\r\ns1(2).name = 'alice';\r\ns1(2).age = 29;\r\n%%\r\n% Later, I go back and collect the individual's heights (in cm).\r\ns2.height = 170;\r\ns2(2).height = 160;\r\n%%\r\n% It would be great to merge these arrays now.\r\ns1\r\ns2\r\n%%\r\n% Let me collect the field names.\r\nfn1 = fieldnames(s1);\r\nfn2 = fieldnames(s2);\r\nfn = [fn1; fn2];\r\n%%\r\n% Next, I ensure the fieldnames are unique.\r\nufn = length(fn) == unique(length(fn))\r\n%%\r\n% Next let me convert the data in my structs into cell arrays using\r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2009b\/techdoc\/ref\/struct2cell.html |struct2cell|>.\r\nc1 = struct2cell(s1)\r\nc2 = struct2cell(s2)\r\n%%\r\n% Next I merge the data from the 2 cell arrays.\r\nc = [c1;c2]\r\n%%\r\n% And finally, I construct the new struct using \r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2009b\/techdoc\/ref\/cell2struct.html |cell2struct|>.\r\ns = cell2struct(c,fn,1)\r\n%%\r\n% I can check the output now.\r\ns(1)\r\ns(2)\r\n%% mergeStruct\r\n% Here's the function |mergeStruct| that I created to encapsulate the steps\r\n% in this process, including some error checks.\r\ndbtype mergeStruct\r\n%% Do You Need to Merge struct data?\r\n% Do you ever need to merge data stored in structs when you gather new\r\n% information?  Or are your structs static in nature?  If the information\r\n% you collect is always the same sort of information, then you probably\r\n% know the form of the structure when you start, even if all the data isn't\r\n% available at first.  \r\n%%\r\n% There is\r\n% <https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/7842-catstruct code> on the\r\n% File Exchange to concatenate structures; I confess I have not tried it,\r\n% but it is highly rated.  Does this post or the File Exchange contribution\r\n% help your work?  Let me know\r\n% <https:\/\/blogs.mathworks.com\/loren\/?p=XXX#respond here>.\r\n\r\n\r\n##### SOURCE END ##### 60deb70ff18c4179be87db0fb4a2118f\r\n-->","protected":false},"excerpt":{"rendered":"<p>\r\n   \r\n      From time to time, I get asked or see queries about how to concatenate two struct arrays to merge the fields.  There's even a section in the documentation covering this topic. I thought... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/loren\/2009\/10\/15\/concatenating-structs\/\">read more >><\/a><\/p>","protected":false},"author":39,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[5],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/202"}],"collection":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/users\/39"}],"replies":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/comments?post=202"}],"version-history":[{"count":1,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/202\/revisions"}],"predecessor-version":[{"id":1987,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/202\/revisions\/1987"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/media?parent=202"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/categories?post=202"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/tags?post=202"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}