{"id":124,"date":"2008-02-01T09:34:37","date_gmt":"2008-02-01T14:34:37","guid":{"rendered":"https:\/\/blogs.mathworks.com\/loren\/2008\/02\/01\/structure-initialization\/"},"modified":"2018-01-08T15:26:10","modified_gmt":"2018-01-08T20:26:10","slug":"structure-initialization","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/loren\/2008\/02\/01\/structure-initialization\/","title":{"rendered":"Structure Initialization"},"content":{"rendered":"<div xmlns:mwsh=\"https:\/\/www.mathworks.com\/namespace\/mcode\/v1\/syntaxhighlight.dtd\" class=\"content\">\r\n   <introduction>\r\n      <p>This post continues in the theme of other recent ones, questions frequently posed to me (and probably others).  It has to\r\n         do with initializing structures.  There is a healthy <a>set of posts<\/a> on the MATLAB newsgroup devoted to this topic.  So let's peel things apart today.\r\n      <\/p>\r\n   <\/introduction>\r\n   <h3>Contents<\/h3>\r\n   <div>\r\n      <ul>\r\n         <li><a href=\"#1\">Structures - Mental Model<\/a><\/li>\r\n         <li><a href=\"#5\">Array of structs<\/a><\/li>\r\n         <li><a href=\"#7\">Don't Grow Arrays<\/a><\/li>\r\n         <li><a href=\"#8\">How to Initialize a struct Array<\/a><\/li>\r\n         <li><a href=\"#15\">Initializing the Contents<\/a><\/li>\r\n         <li><a href=\"#16\">Your Use of Structures<\/a><\/li>\r\n      <\/ul>\r\n   <\/div>\r\n   <h3>Structures - Mental Model<a name=\"1\"><\/a><\/h3>\r\n   <p>It first helps to understand how MATLAB treats structures and their fields.  First clear the workspace.<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">clear <span style=\"color: #A020F0\">variables<\/span>\r\nclose <span style=\"color: #A020F0\">all<\/span><\/pre><p>Let's just start with a scalar structure.<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">mystruct.FirstName = <span style=\"color: #A020F0\">'Loren'<\/span>;\r\nmystruct.Height = 150<\/pre><pre style=\"font-style:oblique\">mystruct = \r\n    FirstName: 'Loren'\r\n       Height: 150\r\n<\/pre><p>Each field in the structure <tt>mystruct<\/tt> appears to be a separate MATLAB array.  The first one, <tt>FirstName<\/tt>, is a string of length 5, and the second, <tt>height<\/tt>, is a scalar double (in cm, for those who are paying attention to units).\r\n   <\/p>\r\n   <p>I can add another field and its contents can be the contents of any valid MATLAB variable.  Each field is independent in size\r\n      and datatype.\r\n   <\/p>\r\n   <h3>Array of structs<a name=\"5\"><\/a><\/h3>\r\n   <p>Suppose I want to extend this array to include other people and measurements.  I can grow this array an element at a time.<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">mystruct(2).FirstName = <span style=\"color: #A020F0\">'Fred'<\/span>;\r\nmystruct(2)<\/pre><pre style=\"font-style:oblique\">ans = \r\n    FirstName: 'Fred'\r\n       Height: []\r\n<\/pre><p>You can see here that since the field <tt>Height<\/tt> does not yet have a value, its value is set to empty (<tt>[]<\/tt>).\r\n   <\/p>\r\n   <h3>Don't Grow Arrays<a name=\"7\"><\/a><\/h3>\r\n   <p>Over the years, we have learned that growing arrays is a poor use of resources in MATLAB and that preallocation is helpful\r\n      in terms of both not fragmenting memory and not spending time looking for a large enough memory slot.  So, if I know I want\r\n      to have 100 names in my <tt>struct<\/tt>, I can initialize the struct to be the right size.  I may or may not feel the need to initialize the <b>contents<\/b> of the struct array however, since each field element is essentially its own MATLAB array.\r\n   <\/p>\r\n   <h3>How to Initialize a struct Array<a name=\"8\"><\/a><\/h3>\r\n   <p>Here are 2 ways to initialize the <tt>struct<\/tt>.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">mystruct(100).FirstName = <span style=\"color: #A020F0\">'George'<\/span>;<\/pre><p>With this method, we can see that elements are filled in with empty arrays.<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">mystruct(17)<\/pre><pre style=\"font-style:oblique\">ans = \r\n    FirstName: []\r\n       Height: []\r\n<\/pre><p>There's another way to initialize the <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/struct.html\"><tt>struct<\/tt><\/a> and that is fill it with initial values.\r\n   <\/p>\r\n   <p>If we were building our <tt>struct<\/tt> with the 5 sons of <a href=\"http:\/\/en.wikipedia.org\/wiki\/George_Foreman\">George Forman<\/a>, we might create it like this.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">georgeStruct = struct(<span style=\"color: #A020F0\">'FirstName'<\/span>,<span style=\"color: #A020F0\">'George'<\/span>,<span style=\"color: #A020F0\">'Height'<\/span>, <span style=\"color: #0000FF\">...<\/span>\r\n    {195 189 190 194 193})<\/pre><pre style=\"font-style:oblique\">georgeStruct = \r\n1x5 struct array with fields:\r\n    FirstName\r\n    Height\r\n<\/pre><p>Looking at the contents of georgeStruct we see that his sons are all named George<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">{georgeStruct.FirstName}<\/pre><pre style=\"font-style:oblique\">ans = \r\n    'George'    'George'    'George'    'George'    'George'\r\n<\/pre><p>and I made up their heights<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">[georgeStruct.Height]<\/pre><pre style=\"font-style:oblique\">ans =\r\n   195   189   190   194   193\r\n<\/pre><p>To see when and how to use cell arrays in the initialization, read the <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/struct.html\"><tt>struct<\/tt><\/a> reference page carefully.  If you want a field to contain a cell array, you must embed that cell inside another cell array.\r\n   <\/p>\r\n   <h3>Initializing the Contents<a name=\"15\"><\/a><\/h3>\r\n   <p>How important is it to initialize the <b>contents<\/b> of the <tt>struct<\/tt>.  Of course it depends on your specifics, but since each field is its own MATLAB array, there is not necessarily a need to\r\n      initialize them all up front.  The key however is to try to not grow either the <tt>struct<\/tt> itself or any of its contents incrementally.\r\n   <\/p>\r\n   <h3>Your Use of Structures<a name=\"16\"><\/a><\/h3>\r\n   <p>What do you use structures for?  Are you able to populate the contents of your <tt>struct<\/tt> up front?  Or at least pin down the sizes early in your application?  To tell me about your usage, please post details <a href=\"https:\/\/blogs.mathworks.com\/loren\/?p=124#respond\">here<\/a>.\r\n   <\/p><script language=\"JavaScript\">\r\n<!--\r\n\r\n    function grabCode_79add1968b6945e88a6a4caccfad6de6() {\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='79add1968b6945e88a6a4caccfad6de6 ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' 79add1968b6945e88a6a4caccfad6de6';\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 2008 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_79add1968b6945e88a6a4caccfad6de6()\"><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.5<br><\/p>\r\n<\/div>\r\n<!--\r\n79add1968b6945e88a6a4caccfad6de6 ##### SOURCE BEGIN #####\r\n%% Structure Initialization\r\n% This post continues in the theme of other recent ones, questions\r\n% frequently posed to me (and probably others).  It has to do with\r\n% initializing structures.  There is a healthy \r\n% <http:\/\/search_results?search_string=initialize+structure set of posts>\r\n% on the MATLAB newsgroup devoted to this topic.  So let's peel things\r\n% apart today.\r\n%% Structures - Mental Model\r\n% It first helps to understand how MATLAB treats structures and their\r\n% fields.  First clear the workspace.\r\nclear variables\r\nclose all\r\n%%\r\n% Let's just start with a scalar structure.\r\nmystruct.FirstName = 'Loren';\r\nmystruct.Height = 150\r\n%% \r\n% Each field in the structure |mystruct| appears to be a separate MATLAB\r\n% array.  The first one, |FirstName|, is a string of length 5, and the\r\n% second, |height|, is a scalar double (in cm, for those who are paying\r\n% attention to units).\r\n%%\r\n% I can add another field and its contents can be the contents of any valid\r\n% MATLAB variable.  Each field is independent in size and datatype.\r\n%% Array of structs\r\n% Suppose I want to extend this array to include other people and\r\n% measurements.  I can grow this array an element at a time.\r\nmystruct(2).FirstName = 'Fred';\r\nmystruct(2)\r\n%%\r\n% You can see here that since the field |Height| does not yet have a value,\r\n% its value is set to empty (|[]|).\r\n%% Don't Grow Arrays\r\n% Over the years, we have learned that growing arrays is a poor use of\r\n% resources in MATLAB and that preallocation is helpful in terms of both\r\n% not fragmenting memory and not spending time looking for a large enough\r\n% memory slot.  So, if I know I want to have 100 names in my |struct|, I\r\n% can initialize the struct to be the right size.  I may or may not feel\r\n% the need to initialize the *contents* of the struct array however, since\r\n% each field element is essentially its own MATLAB array.\r\n%% How to Initialize a struct Array\r\n% Here are 2 ways to initialize the |struct|.\r\nmystruct(100).FirstName = 'George';\r\n%%\r\n% With this method, we can see that elements are filled in with empty\r\n% arrays.\r\nmystruct(17)\r\n%%\r\n% There's another way to initialize the \r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/struct.html |struct|> \r\n% and that is fill it with initial values.\r\n%%\r\n% If we were building our |struct| with the 5 sons of \r\n% <http:\/\/en.wikipedia.org\/wiki\/George_Foreman George Forman>, we might\r\n% create it like this.\r\ngeorgeStruct = struct('FirstName','George','Height', ...\r\n    {195 189 190 194 193})\r\n%% \r\n% Looking at the contents of georgeStruct we see that his sons are all\r\n% named George\r\n{georgeStruct.FirstName}\r\n%%\r\n% and I made up their heights\r\n[georgeStruct.Height]\r\n%% \r\n% To see when and how to use cell arrays in the initialization, read the\r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/struct.html |struct|>\r\n% reference page carefully.  If you want a field to contain a cell array,\r\n% you must embed that cell inside another cell array.\r\n%% Initializing the Contents\r\n% How important is it to initialize the *contents* of the |struct|.  Of\r\n% course it depends on your specifics, but since each field is its own\r\n% MATLAB array, there is not necessarily a need to initialize them all up\r\n% front.  The key however is to try to not grow either the |struct| itself\r\n% or any of its contents incrementally.\r\n%% Your Use of Structures\r\n% What do you use structures for?  Are you able to populate the contents of\r\n% your |struct| up front?  Or at least pin down the sizes early in your\r\n% application?  To tell me about your usage, please post details\r\n% <https:\/\/blogs.mathworks.com\/loren\/?p=124#respond here>.\r\n\r\n\r\n##### SOURCE END ##### 79add1968b6945e88a6a4caccfad6de6\r\n-->","protected":false},"excerpt":{"rendered":"<p>\r\n   \r\n      This post continues in the theme of other recent ones, questions frequently posed to me (and probably others).  It has to\r\n         do with initializing structures.  There is a healthy... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/loren\/2008\/02\/01\/structure-initialization\/\">read more >><\/a><\/p>","protected":false},"author":39,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[10,5,12],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/124"}],"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=124"}],"version-history":[{"count":1,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/124\/revisions"}],"predecessor-version":[{"id":2582,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/124\/revisions\/2582"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/media?parent=124"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/categories?post=124"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/tags?post=124"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}