{"id":6131,"date":"2015-08-21T09:00:31","date_gmt":"2015-08-21T13:00:31","guid":{"rendered":"https:\/\/blogs.mathworks.com\/pick\/?p=6131"},"modified":"2015-08-21T14:24:20","modified_gmt":"2015-08-21T18:24:20","slug":"writing-a-struct-to-text","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/pick\/2015\/08\/21\/writing-a-struct-to-text\/","title":{"rendered":"Writing a struct to text"},"content":{"rendered":"<div class=\"content\"><!--introduction--><p><a href=\"https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/authors\/911\">Brett<\/a>&#8216;s Pick this week is <a href=\"https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/15017-struct2str\">struct2str<\/a>, by <a href=\"https:\/\/www.mathworks.com\/matlabcentral\/profile\/authors\/870264\">Marco Cococcioni<\/a>.<\/p><!--\/introduction--><h3>Contents<\/h3><div><ul><li><a href=\"#8053c02e-1018-492a-9e61-49669c47ceb3\">Strings from structs<\/a><\/li><li><a href=\"#81aef875-8ed5-4e37-8dbb-a21e115dc502\">struct2str<\/a><\/li><li><a href=\"#1619dc18-41f2-44b0-826b-14fbeb8b6e5b\">And a challenge!<\/a><\/li><li><a href=\"#af95aa4f-dcf3-487f-b352-5cf8c037ce74\">Comments?<\/a><\/li><\/ul><\/div><h4>Strings from structs<a name=\"8053c02e-1018-492a-9e61-49669c47ceb3\"><\/a><\/h4><p>Back in May, <a href=\"https:\/\/www.mathworks.com\/matlabcentral\/profile\/authors\/3208495-sean-de-wolski\">Sean<\/a> wrote about <a href=\"https:\/\/blogs.mathworks.com\/pick\/?p=6002\">different File Exchange submissions<\/a> that facilitate writing cell arrays to text. That was a useful post&#8211;and one that triggered an interesting follow-up discussion between Sean and me: namely, how would one write a struct to string? I write a lot of apps, and frequently want to put the contents of a struct into a listbox, for example. That can be challenging and frustrating.<\/p><p>When I suggested that Sean follow up with a post on writing structs to text, he quickly agreed that that would be interesting. But I think he initially missed my point: he suggested that I could easily write the fieldnames of a structure to a listbox using, for instance,<\/p><pre class=\"language-matlab\">lb = uicontrol(<span class=\"string\">'units'<\/span>,<span class=\"string\">'normalized'<\/span>,<span class=\"keyword\">...<\/span><span class=\"string\">'position'<\/span>,[0.1 0.1 0.8 0.8],<span class=\"keyword\">...<\/span>\r\n\t<span class=\"string\">'Style'<\/span>,<span class=\"string\">'listbox'<\/span>);\r\nd = dir(<span class=\"string\">'.\\*'<\/span>);\r\nlb.String = fieldnames(d);\r\n<\/pre><p><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/pick\/files\/struct2str1.png\" alt=\"\"> <\/p><p>&#8220;True,&#8221; I replied. &#8220;But I want the contents of the struct, not just the fieldnames.&#8221; His reply: &#8220;How about&#8221;<\/p><pre class=\"language-matlab\">names = {d(:).name};\r\nlb.String = names;\r\n<\/pre><p><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/pick\/files\/struct2str2.png\" alt=\"\"> <\/p><p>Okay, that gets me the values of a single fieldname (in this example, &#8216;name&#8217;). However, assume that I get the file information for an image, and want to drop it all in a textbox or listbox:<\/p><pre class=\"codeinput\">structInfo = imfinfo(<span class=\"string\">'street2.jpg'<\/span>)\r\n<\/pre><pre class=\"codeoutput\">structInfo = \r\n           Filename: 'C:\\Program Files\\MATLAB\\R2015a\\toolbox\\matlab\\demos\\...'\r\n        FileModDate: '22-Mar-2004 19:54:40'\r\n           FileSize: 39920\r\n             Format: 'jpg'\r\n      FormatVersion: ''\r\n              Width: 640\r\n             Height: 480\r\n           BitDepth: 24\r\n          ColorType: 'truecolor'\r\n    FormatSignature: ''\r\n    NumberOfSamples: 3\r\n       CodingMethod: 'Huffman'\r\n      CodingProcess: 'Sequential'\r\n            Comment: {}\r\n<\/pre><p>How could I easily put all of that information into a listbox?<\/p><h4>struct2str<a name=\"81aef875-8ed5-4e37-8dbb-a21e115dc502\"><\/a><\/h4><p>That&#8217;s where Marco&#8217;s file comes in:<\/p><pre class=\"language-matlab\">lb.String = struct2str(structInfo);\r\n<\/pre><p><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/pick\/files\/struct2str3.png\" alt=\"\"> <\/p><p>I had initially done this with a particularly ugly <tt>for<\/tt> loop, but <tt>struct2str<\/tt> makes it very easy. (Marco used some loops, too, but his code alleviates for me the pain of writing that loop. Thanks, Marco!)<\/p><h4>And a challenge!<a name=\"1619dc18-41f2-44b0-826b-14fbeb8b6e5b\"><\/a><\/h4><p>Note that there are a few empty fields in the <tt>imfinfo<\/tt> output struct in the usage above. Kudos and swag to the first person who replies with an elegant approach to automatically removing from the struct the fields with empty values. Use any approach you&#8217;d like, including other File Exchange submissions. What I&#8217;d like to see is this:<\/p><pre class=\"codeinput\">structInfo = rmfield(structInfo,{<span class=\"string\">'FormatVersion'<\/span>,<span class=\"string\">'FormatSignature'<\/span>,<span class=\"string\">'Comment'<\/span>})\r\n<\/pre><pre class=\"codeoutput\">structInfo = \r\n           Filename: 'C:\\Program Files\\MATLAB\\R2015a\\toolbox\\matlab\\demos\\...'\r\n        FileModDate: '22-Mar-2004 19:54:40'\r\n           FileSize: 39920\r\n             Format: 'jpg'\r\n              Width: 640\r\n             Height: 480\r\n           BitDepth: 24\r\n          ColorType: 'truecolor'\r\n    NumberOfSamples: 3\r\n       CodingMethod: 'Huffman'\r\n      CodingProcess: 'Sequential'\r\n<\/pre><p>&#8230;but without the manual specification of the empty fields. Let me know how you would approach this, and I will select (and reward) the one I like best. It&#8217;s good to be the blogger. ;)<\/p><h4>Comments?<a name=\"af95aa4f-dcf3-487f-b352-5cf8c037ce74\"><\/a><\/h4><p>As always, comments are welcome! Let me know what you think (or respond to my challenge) <a href=\"https:\/\/blogs.mathworks.com\/pick\/?p=6131#respond\">here<\/a>, or leave feedback for Marco <a href=\"https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/15017-struct2str#comments\">here<\/a>.<\/p><script language=\"JavaScript\"> <!-- \r\n    function grabCode_ec6547c8c0a044cbbec84b58570e61a0() {\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='ec6547c8c0a044cbbec84b58570e61a0 ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' ec6547c8c0a044cbbec84b58570e61a0';\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        copyright = 'Copyright 2015 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 copyright line at the bottom if specified.\r\n        if (copyright.length > 0) {\r\n            d.writeln('');\r\n            d.writeln('%%');\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     --> <\/script><p style=\"text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray\"><br><a href=\"javascript:grabCode_ec6547c8c0a044cbbec84b58570e61a0()\"><span style=\"font-size: x-small;        font-style: italic;\">Get \r\n      the MATLAB code <noscript>(requires JavaScript)<\/noscript><\/span><\/a><br><br>\r\n      Published with MATLAB&reg; R2015a<br><\/p><\/div><!--\r\nec6547c8c0a044cbbec84b58570e61a0 ##### SOURCE BEGIN #####\r\n%% Writing a struct to text\r\n%% \r\n% <https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/authors\/911 Brett>'s Pick this week\r\n% is\r\n% <https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/15017-struct2str struct2str>, \r\n% by <https:\/\/www.mathworks.com\/matlabcentral\/profile\/authors\/870264 Marco Cococcioni>.\r\n\r\n%% Strings from structs\r\n% Back in May, <https:\/\/www.mathworks.com\/matlabcentral\/profile\/authors\/3208495-sean-de-wolski Sean> wrote about <<https:\/\/blogs.mathworks.com\/pick\/2015\/05\/22\/writing-a-cell-array-a-comparison\/ different File Exchange submissions>\r\n% that facilitate writing cell arrays to text. That was a\r\n% useful postREPLACE_WITH_DASH_DASHand one that triggered an interesting follow-up discussion\r\n% between Sean and me: namely, how would one write a struct to string? I\r\n% write a lot of apps, and frequently want to put the contents of a struct\r\n% into a listbox, for example. That can be challenging and frustrating.\r\n\r\n%% \r\n% When I suggested that Sean follow up with a post on writing structs to\r\n% text, he quickly agreed that that would be interesting. But I think he initially missed my point:\r\n% he suggested that I could easily write the fieldnames of a\r\n% structure to a listbox using, for instance,\r\n\r\n%%\r\n%   lb = uicontrol('units','normalized',...\r\n%   \t'position',[0.1 0.1 0.8 0.8],...\r\n%   \t'Style','listbox');\r\n%   d = dir('.\\*');\r\n%   lb.String = fieldnames(d);\r\n% \r\n\r\n%%\r\n% \r\n% <<https:\/\/blogs.mathworks.com\/pick\/files\/struct2str1.png>>\r\n% \r\n\r\n%% \r\n% \"True,\" I replied. \"But I want the contents of the struct, not just the fieldnames.\"\r\n% His reply: \"How about\"\r\n\r\n%%\r\n%   names = {d(:).name};\r\n%   lb.String = names;\r\n\r\n%%\r\n% \r\n% <<https:\/\/blogs.mathworks.com\/pick\/files\/struct2str2.png>>\r\n% \r\n\r\n%%\r\n% Okay, that gets me the values of a single fieldname (in this example, 'name').\r\n% However, assume that I get the file information for an image, and want to drop it all in a textbox or listbox:\r\nstructInfo = imfinfo('street2.jpg')\r\n\r\n%%\r\n% How could I easily put all of that information into a listbox?\r\n\r\n%% struct2str\r\n% That's where Marco's file comes in:\r\n\r\n%%\r\n%   lb.String = struct2str(structInfo);\r\n\r\n%%\r\n% \r\n% <<https:\/\/blogs.mathworks.com\/pick\/files\/struct2str3.png>>\r\n% \r\n\r\n%% \r\n% I had initially done this with a particularly ugly |for| loop, but\r\n% |struct2str| makes it very easy. (Marco used some loops, too, but his code\r\n% alleviates for me the pain of writing that loop. Thanks, Marco!)\r\n\r\n%% And a challenge!\r\n% Note that there are a few empty fields in the |imfinfo| output struct in\r\n% the usage above. Kudos and swag to the first person who replies with an\r\n% elegant approach to automatically removing from the struct the fields\r\n% with empty values. Use any approach you'd like, including other File\r\n% Exchange submissions. What I'd like to see is this:\r\n\r\nstructInfo = rmfield(structInfo,{'FormatVersion','FormatSignature','Comment'})\r\n\r\n%%\r\n% ...but without the manual specification of the empty fields. Let me know\r\n% how you would approach this, and I will select (and reward) the one I\r\n% like best. It's good to be the blogger. ;)\r\n\r\n%% Comments?\r\n% As always, comments are welcome! Let me know what you think (or respond to my challenge)\r\n% <https:\/\/blogs.mathworks.com\/pick\/?p=6131#respond here>, or leave feedback\r\n% for Marco\r\n% <https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/15017-struct2str#comments here>.\r\n##### SOURCE END ##### ec6547c8c0a044cbbec84b58570e61a0\r\n-->\r\n\t","protected":false},"excerpt":{"rendered":"<div class=\"overview-image\"><img decoding=\"async\"  class=\"img-responsive\" src=\"https:\/\/blogs.mathworks.com\/pick\/files\/struct2str1.png\" onError=\"this.style.display ='none';\" \/><\/div><p>Brett&#8216;s Pick this week is struct2str, by Marco Cococcioni.ContentsStrings from structsstruct2strAnd a challenge!Comments?Strings from structsBack in May, Sean wrote about different File&#8230; <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/pick\/2015\/08\/21\/writing-a-struct-to-text\/\">read more >><\/a><\/p>","protected":false},"author":34,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[16],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/posts\/6131"}],"collection":[{"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/users\/34"}],"replies":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/comments?post=6131"}],"version-history":[{"count":22,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/posts\/6131\/revisions"}],"predecessor-version":[{"id":6161,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/posts\/6131\/revisions\/6161"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/media?parent=6131"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/categories?post=6131"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/tags?post=6131"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}