{"id":10846,"date":"2019-07-12T09:00:58","date_gmt":"2019-07-12T13:00:58","guid":{"rendered":"https:\/\/blogs.mathworks.com\/pick\/?p=10846"},"modified":"2019-07-09T15:54:40","modified_gmt":"2019-07-09T19:54:40","slug":"struct2vars","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/pick\/2019\/07\/12\/struct2vars\/","title":{"rendered":"Struct2Vars"},"content":{"rendered":"<div xmlns:mwsh=\"http:\/\/www.mathworks.com\/namespace\/mcode\/v1\/syntaxhighlight.dtd\" class=\"content\">\n   <introduction><\/p>\n<p><a href=\"http:\/\/www.mathworks.com\/matlabcentral\/profile\/authors\/3208495\">Sean<\/a>&#8216;s pick this week is <a href=\"http:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/57370\">struct2vars<\/a> by <a href=\"http:\/\/www.mathworks.com\/matlabcentral\/profile\/authors\/3529521\">Matthew Eicholtz<\/a>.\n      <\/p>\n<p>   <\/introduction><\/p>\n<p>I was recently asked by a colleague: &#8220;How do I get all of the fields of a struct into their own variable?&#8221;.  In general, although it is very doable with <tt>assignin<\/tt>, &#8220;poofing&#8221; a variable a bad idea because you could overwrite existing variables and the language execution engine may lose some of its efficiencies.  That&#8217;s why I like Matthew&#8217;s submission.  It gives you the option to get back specific fields as outputs to a function, or to avoid the best practice and poof them into the workspace with a warning if it&#8217;s overwriting something.\n   <\/p>\n<p>Here&#8217;s it in use:<\/p>\n<pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">clearvars\r\nx = 1;\r\ns = struct(<span style=\"color: #A020F0\">'a'<\/span>, pi, <span style=\"color: #A020F0\">'b'<\/span>, exp(1), <span style=\"color: #A020F0\">'x'<\/span>, 2);\r\nwhos<\/pre>\n<pre style=\"font-style:oblique\">  Name      Size            Bytes  Class     Attributes\r\n\r\n  s         1x1               552  struct              \r\n  x         1x1                 8  double              \r\n\r\n<\/pre>\n<p>Now if I just want <i>b<\/i> back\n   <\/p>\n<pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">b = struct2vars(s, {<span style=\"color: #A020F0\">'b'<\/span>});\r\nwhos<\/pre>\n<pre style=\"font-style:oblique\">  Name      Size            Bytes  Class     Attributes\r\n\r\n  b         1x1                 8  double              \r\n  s         1x1               552  struct              \r\n  x         1x1                 8  double              \r\n\r\n<\/pre>\n<p>Or if I want all of them:<\/p>\n<pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">struct2vars(s)<\/pre>\n<pre style=\"font-style:oblique\">Warning: The following variables already exist\r\nin the caller workspace and will be\r\noverwritten:\r\n\tb\r\n\tx\r\n \r\n<\/pre>\n<pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">whos\r\ndisp(<span style=\"color: #A020F0\">\"x is now: \"<\/span> + x)<\/pre>\n<pre style=\"font-style:oblique\">  Name      Size            Bytes  Class     Attributes\r\n\r\n  a         1x1                 8  double              \r\n  b         1x1                 8  double              \r\n  s         1x1               552  struct              \r\n  x         1x1                 8  double              \r\n\r\nx is now: 2\r\n<\/pre>\n<p>You&#8217;ll see I get a warning; x is now 2, the value from the struct.<\/p>\n<p>The other place you&#8217;ll often see this type of behavior is with the <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/load.html\"><tt>load<\/tt><\/a> command.  By default, <tt>load<\/tt> will poof all of the variables in a MAT file into your workspace.\n   <\/p>\n<pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">save(<span style=\"color: #A020F0\">'ExampleMATFile.mat'<\/span>)\r\nclearvars\r\nwhos<\/pre>\n<pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">load(<span style=\"color: #A020F0\">'ExampleMATFile.mat'<\/span>)\r\nwhos<\/pre>\n<pre style=\"font-style:oblique\">  Name      Size            Bytes  Class     Attributes\r\n\r\n  a         1x1                 8  double              \r\n  b         1x1                 8  double              \r\n  s         1x1               552  struct              \r\n  x         1x1                 8  double              \r\n\r\n<\/pre>\n<p>Instead, I try to always get a structure back and then grab the fields I care about.<\/p>\n<pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">clearvars\r\nwhos\r\nM = load(<span style=\"color: #A020F0\">'ExampleMATFile.mat'<\/span>)<\/pre>\n<pre style=\"font-style:oblique\">M = \r\n  struct with fields:\r\n\r\n    a: 3.1416\r\n    b: 2.7183\r\n    s: [1&times;1 struct]\r\n    x: 2\r\n<\/pre>\n<h3>Comments<a name=\"9\"><\/a><\/h3>\n<p>Give it a try and let us know what you think <a href=\"http:\/\/blogs.mathworks.com\/pick\/?p=10846#respond\">here<\/a> or leave a <a href=\"http:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/57370#comments\">comment<\/a> for Matthew.\n   <\/p>\n<p><script language=\"JavaScript\">\n<!--\n\n    function grabCode_5c7b2167685f45d2817755bdf2dd9ca4() {\n        \/\/ Remember the title so we can use it in the new page\n        title = document.title;\n\n        \/\/ Break up these strings so that their presence\n        \/\/ in the Javascript doesn't mess up the search for\n        \/\/ the MATLAB code.\n        t1='5c7b2167685f45d2817755bdf2dd9ca4 ' + '##### ' + 'SOURCE BEGIN' + ' #####';\n        t2='##### ' + 'SOURCE END' + ' #####' + ' 5c7b2167685f45d2817755bdf2dd9ca4';\n    \n        b=document.getElementsByTagName('body')[0];\n        i1=b.innerHTML.indexOf(t1)+t1.length;\n        i2=b.innerHTML.indexOf(t2);\n \n        code_string = b.innerHTML.substring(i1, i2);\n        code_string = code_string.replace(\/REPLACE_WITH_DASH_DASH\/g,'--');\n\n        \/\/ Use \/x3C\/g instead of the less-than character to avoid errors \n        \/\/ in the XML parser.\n        \/\/ Use '\\x26#60;' instead of '<' so that the XML parser\n        \/\/ doesn't go ahead and substitute the less-than character. \n        code_string = code_string.replace(\/\\x3C\/g, '\\x26#60;');\n\n        author = 'Sean de Wolski';\n        copyright = 'Copyright 2019 The MathWorks, Inc.';\n\n        w = window.open();\n        d = w.document;\n        d.write('\n\n<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\n\\n');\n      \n      d.title = title + ' (MATLAB code)';\n      d.close();\n      }   \n      \n-->\n<\/script><\/p>\n<p style=\"text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray\"><a href=\"javascript:grabCode_5c7b2167685f45d2817755bdf2dd9ca4()\"><span style=\"font-size: x-small;        font-style: italic;\"><\/span><\/a><\/p>\n<p>      Published with MATLAB&reg; R2019a<\/p>\n<\/div>\n<p><!--\n5c7b2167685f45d2817755bdf2dd9ca4 ##### SOURCE BEGIN #####\n%% Struct2Vars\n%\n% <http:\/\/www.mathworks.com\/matlabcentral\/profile\/authors\/3208495 Sean>'s pick this week is\n% <http:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/57370 struct2vars> by\n% <http:\/\/www.mathworks.com\/matlabcentral\/profile\/authors\/3529521 Matthew Eicholtz>.\n% \n\n%% \n%\n% I was recently asked by a colleague: \"How do I get all of the fields of a\n% struct into their own variable?\".  In general, although it is very doable\n% with |assignin|, \"poofing\" a variable a bad idea because you could\n% overwrite existing variables and the language execution engine may lose\n% some of its efficiencies.  That's why I like Matthew's submission.  It\n% gives you the option to get back specific fields as outputs to a\n% function, or to avoid the best practice and poof them into the workspace\n% with a warning if it's overwriting something.\n%\n% Here's it in use:\n\nclearvars\nx = 1;\ns = struct('a', pi, 'b', exp(1), 'x', 2);\nwhos\n\n%%\n% Now if I just want _b_ back\n\nb = struct2vars(s, {'b'});\nwhos\n\n%%\n% Or if I want all of them:\n\nstruct2vars(s)\n%%\nwhos\ndisp(\"x is now: \" + x)\n\n%%\n% You'll see I get a warning; x is now 2, the value from the struct.\n\n%%\n% The other place you'll often see this type of behavior is with the\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/load.html |load|> command.  By\n% default, |load| will poof all of the variables in a MAT file into your\n% workspace.\n\nsave('ExampleMATFile.mat')\nclearvars\nwhos\n%%\nload('ExampleMATFile.mat')\nwhos\n\n%%\n% Instead, I try to always get a structure back and then grab the fields I\n% care about.\n\nclearvars\nwhos\nM = load('ExampleMATFile.mat')\n\n%% Comments\n% \n% Give it a try and let us know what you think\n% <http:\/\/blogs.mathworks.com\/pick\/?p=10846#respond here> or leave a\n% <http:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/57370#comments\n% comment> for Matthew.\n%\n \n\n##### SOURCE END ##### 5c7b2167685f45d2817755bdf2dd9ca4\n--><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Sean&#8216;s pick this week is struct2vars by Matthew Eicholtz.<\/p>\n<p>I was recently asked by a colleague: &#8220;How do I get all of the fields of a struct into their own variable?&#8221;&#8230;. <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/pick\/2019\/07\/12\/struct2vars\/\">read more >><\/a><\/p>\n","protected":false},"author":87,"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\/10846"}],"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\/87"}],"replies":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/comments?post=10846"}],"version-history":[{"count":4,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/posts\/10846\/revisions"}],"predecessor-version":[{"id":10854,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/posts\/10846\/revisions\/10854"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/media?parent=10846"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/categories?post=10846"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/tags?post=10846"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}