{"id":103,"date":"2007-08-15T13:53:54","date_gmt":"2007-08-15T18:53:54","guid":{"rendered":"https:\/\/blogs.mathworks.com\/loren\/2007\/08\/15\/iterating-over-non-numeric-values\/"},"modified":"2007-08-07T13:54:28","modified_gmt":"2007-08-07T18:54:28","slug":"iterating-over-non-numeric-values","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/loren\/2007\/08\/15\/iterating-over-non-numeric-values\/","title":{"rendered":"Iterating over Non-Numeric Values"},"content":{"rendered":"<div xmlns:mwsh=\"https:\/\/www.mathworks.com\/namespace\/mcode\/v1\/syntaxhighlight.dtd\" class=\"content\">\r\n   <introduction>\r\n      <p>Recently a colleague was hoping to write some code to iterate over fields in a structure.  There are at least three different\r\n         ways I can think of, some more straight-forward than others.  Here's what I've come up with.\r\n      <\/p>\r\n   <\/introduction>\r\n   <h3>Contents<\/h3>\r\n   <div>\r\n      <ul>\r\n         <li><a href=\"#1\">Create Data for an Example<\/a><\/li>\r\n         <li><a href=\"#3\">First Method - Loop Over Number of Field Names<\/a><\/li>\r\n         <li><a href=\"#4\">Second Method - Loop Over Field Names Themselves<\/a><\/li>\r\n         <li><a href=\"#6\">Third Method - Use structfun<\/a><\/li>\r\n         <li><a href=\"#8\">Which Way is Clearest?<\/a><\/li>\r\n      <\/ul>\r\n   <\/div>\r\n   <h3>Create Data for an Example<a name=\"1\"><\/a><\/h3>\r\n   <p>I'm only going to consider scalar structures for this post.  The contents of each field in this case will also be scalars,\r\n      for easy illustration. I'd like to create output that increases the value of each entry by 1.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">s.a = 1;\r\ns.b = 2;\r\ns.c = 3;<\/pre><p>Let me get the field names so I can have the code be reasonably generic.<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">fn = fieldnames(s)<\/pre><pre style=\"font-style:oblique\">fn = \r\n    'a'\r\n    'b'\r\n    'c'\r\n<\/pre><h3>First Method - Loop Over Number of Field Names<a name=\"3\"><\/a><\/h3>\r\n   <p>In the first case, I find out how many fields are in the struct, and then loop over each of them, using dynamic field referencing\r\n      to access the value in each field.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">out1 = zeros(1, length(fn));\r\n<span style=\"color: #0000FF\">for<\/span> n = 1:length(fn)\r\n    out1(n) = s.(fn{n}) + 1;\r\n<span style=\"color: #0000FF\">end<\/span>\r\nout1<\/pre><pre style=\"font-style:oblique\">out1 =\r\n     2     3     4\r\n<\/pre><h3>Second Method - Loop Over Field Names Themselves<a name=\"4\"><\/a><\/h3>\r\n   <p>In the second case, I am going to bypass the numeric indexing and loop through the fields themselves.  Since the <tt>for<\/tt> loop in MATLAB processes the indices a column at a time, I have to turn my column of field names into a row vector.  It happens\r\n      to be a cell array, so I also have to convert the field names to character arrays to use dynamic field referencing.  I won't\r\n      preallocate the output <tt>out2<\/tt> this time, but allow this small array to grow, so I don't need to add a counter to the loop.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">out2 = [];\r\n<span style=\"color: #0000FF\">for<\/span> str = fn'\r\n    out2(end+1) = s.(char(str)) + 1;\r\n<span style=\"color: #0000FF\">end<\/span>\r\nout2<\/pre><pre style=\"font-style:oblique\">out2 =\r\n     2     3     4\r\n<\/pre><p>Check that the results of the first two methods agree.<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">isequal(out1,out2)<\/pre><pre style=\"font-style:oblique\">ans =\r\n     1\r\n<\/pre><h3>Third Method - Use structfun<a name=\"6\"><\/a><\/h3>\r\n   <p>Instead of looping through fields at all, use <tt>structfun<\/tt> which iterates over fields in a scalar structure.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">out3 = structfun(@(x)x+1,s);\r\nout3 = out3.'<\/pre><pre style=\"font-style:oblique\">out3 =\r\n     2     3     4\r\n<\/pre><p>Since the results are returned as a column vector, I transpose them so I can compare the output to that of the other methods.\r\n      Check that the results of the last two methods agree.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">isequal(out2,out3)<\/pre><pre style=\"font-style:oblique\">ans =\r\n     1\r\n<\/pre><h3>Which Way is Clearest?<a name=\"8\"><\/a><\/h3>\r\n   <p>I've shown you three ways to iterate over fields in a structure. Which method(s) do you currently use?  Which one seems clearest\r\n      to you? Let me know <a href=\"https:\/\/blogs.mathworks.com\/loren\/?p=103#respond\">here<\/a>.\r\n   <\/p><script language=\"JavaScript\">\r\n<!--\r\n\r\n    function grabCode_0aea0ab3e6ff4e94a385aa7929cfcf44() {\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='0aea0ab3e6ff4e94a385aa7929cfcf44 ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' 0aea0ab3e6ff4e94a385aa7929cfcf44';\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 2007 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_0aea0ab3e6ff4e94a385aa7929cfcf44()\"><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.4<br><\/p>\r\n<\/div>\r\n<!--\r\n0aea0ab3e6ff4e94a385aa7929cfcf44 ##### SOURCE BEGIN #####\r\n%% Iterating over Non-Numeric Values\r\n% Recently a colleague was hoping to write some code to iterate over fields\r\n% in a structure.  There are at least three different ways I can think of,\r\n% some more straight-forward than others.  Here's what I've come up with.\r\n%% Create Data for an Example\r\n% I'm only going to consider scalar structures for this post.  The contents\r\n% of each field in this case will also be scalars, for easy illustration.\r\n% I'd like to create output that increases the value of each entry by 1.\r\ns.a = 1;\r\ns.b = 2;\r\ns.c = 3;\r\n%%\r\n% Let me get the field names so I can have the code be reasonably generic.\r\nfn = fieldnames(s)\r\n%% First Method - Loop Over Number of Field Names\r\n% In the first case, I find out how many fields are in the struct, and then\r\n% loop over each of them, using dynamic field referencing to access the\r\n% value in each field.\r\nout1 = zeros(1, length(fn));\r\nfor n = 1:length(fn)\r\n    out1(n) = s.(fn{n}) + 1;\r\nend\r\nout1\r\n%% Second Method - Loop Over Field Names Themselves\r\n% In the second case, I am going to bypass the numeric indexing and loop\r\n% through the fields themselves.  Since the |for| loop in MATLAB processes\r\n% the indices a column at a time, I have to turn my column of field names\r\n% into a row vector.  It happens to be a cell array, so I also have to\r\n% convert the field names to character arrays to use dynamic field\r\n% referencing.  I won't preallocate the output |out2| this time, but allow\r\n% this small array to grow, so I don't need to add a counter to the loop.\r\nout2 = [];\r\nfor str = fn'\r\n    out2(end+1) = s.(char(str)) + 1;\r\nend\r\nout2\r\n%%\r\n% Check that the results of the first two methods agree.\r\nisequal(out1,out2)\r\n%% Third Method - Use structfun\r\n% Instead of looping through fields at all, use |structfun| which iterates\r\n% over fields in a scalar structure.  \r\nout3 = structfun(@(x)x+1,s);\r\nout3 = out3.'\r\n%%\r\n% Since the results are returned as a column vector, I transpose them so I\r\n% can compare the output to that of the other methods. Check that the\r\n% results of the last two methods agree.\r\nisequal(out2,out3)\r\n%% Which Way is Clearest?\r\n% I've shown you three ways to iterate over fields in a structure.\r\n% Which method(s) do you currently use?  Which one seems clearest to you?\r\n% Let me know <https:\/\/blogs.mathworks.com\/loren\/?p=103#respond here>.\r\n##### SOURCE END ##### 0aea0ab3e6ff4e94a385aa7929cfcf44\r\n-->","protected":false},"excerpt":{"rendered":"<p>\r\n   \r\n      Recently a colleague was hoping to write some code to iterate over fields in a structure.  There are at least three different\r\n         ways I can think of, some more straight-forward... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/loren\/2007\/08\/15\/iterating-over-non-numeric-values\/\">read more >><\/a><\/p>","protected":false},"author":39,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[15,2,5],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/103"}],"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=103"}],"version-history":[{"count":0,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/103\/revisions"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/media?parent=103"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/categories?post=103"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/tags?post=103"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}