{"id":5868,"date":"2015-02-27T09:00:15","date_gmt":"2015-02-27T14:00:15","guid":{"rendered":"https:\/\/blogs.mathworks.com\/pick\/?p=5868"},"modified":"2015-02-27T09:12:57","modified_gmt":"2015-02-27T14:12:57","slug":"for-each","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/pick\/2015\/02\/27\/for-each\/","title":{"rendered":"For Each"},"content":{"rendered":"<div xmlns:mwsh=\"https:\/\/www.mathworks.com\/namespace\/mcode\/v1\/syntaxhighlight.dtd\" class=\"content\">\n   <introduction>\n      <p><a href=\"https:\/\/www.mathworks.com\/matlabcentral\/answers\/contributors\/3208495\">Sean<\/a>'s pick this week is <a href=\"https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/122917-matlab-for-each\">For-Each<\/a> by <a href=\"https:\/\/www.mathworks.com\/matlabcentral\/profile\/authors\/3171300\">Jeremy Hughes<\/a>.\n      <\/p>\n   <\/introduction>\n   <p>My pick this week is a toolbox from our development organization for a <a href=\"http:\/\/en.wikipedia.org\/wiki\/Foreach_loop\">for-each loop<\/a> construct in MATLAB.  A for-each loop allows you to iterate over a set or dimension without having to worry about indexing.\n   <\/p>\n   <p>MATLAB actually already has this built in for single elements of numeric arrays:<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\"><span style=\"color: #228B22\">% Display each element in x<\/span>\n<span style=\"color: #0000FF\">for<\/span> thisfile = [1 pi 8 -3]\n    disp(thisfile)\n<span style=\"color: #0000FF\">end<\/span><\/pre><pre style=\"font-style:oblique\">     1\n    3.1416\n     8\n    -3\n<\/pre><p>This could've course been written with an index like below.<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\"><span style=\"color: #228B22\">% Display each element in x with an index<\/span>\nthisfile = [1 pi 8 -3];\n<span style=\"color: #0000FF\">for<\/span> ii = 1:numel(thisfile)\n    disp(thisfile(ii))\n<span style=\"color: #0000FF\">end<\/span><\/pre><pre style=\"font-style:oblique\">     1\n    3.1416\n     8\n    -3\n<\/pre><p>But what if we want to traverse every column or slice of a three dimensional array?  Or each element in a cell array?  Or\n      each combination of two arrays?  This is where Jeremy's <tt>for-each<\/tt> construct comes in handy since you won't need to worry about indexing.\n   <\/p>\n   <p>Let's take a bunch of csv files and make copies of them with just the rows of data we care about.  These files contain energy\n      outage information for energy outages in America.   Being from New England, I just want the records that correspond to the\n      North East.\n   <\/p>\n   <p><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/images\/pick\/Sean\/mainForEach\/fileview.png\"> <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\"><span style=\"color: #228B22\">% Scrape the data directory for all csv files<\/span>\ndatadir = <span style=\"color: #A020F0\">'.\\Data\\'<\/span>;\nfiles = dir([datadir <span style=\"color: #A020F0\">'*.csv'<\/span>]);\nfilenames = {files.name};\ndisp(filenames)<\/pre><pre style=\"font-style:oblique\">  Columns 1 through 4\n    '2002Data.csv'    '2003Data.csv'    '2004Data.csv'    '2005Data.csv'\n  Columns 5 through 8\n    '2006Data.csv'    '2007Data.csv'    '2008Data.csv'    '2009Data.csv'\n  Columns 9 through 12\n    '2010Data.csv'    '2011Data.csv'    '2012Data.csv'    '2013Data.csv'\n<\/pre><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\"><span style=\"color: #228B22\">%  Make a directory for output<\/span>\noutputdir = <span style=\"color: #A020F0\">'NorthEastData'<\/span>;\nmkdir(outputdir)\n\n<span style=\"color: #228B22\">% Loop over each filename, read, extract, write<\/span>\n<span style=\"color: #0000FF\">for<\/span> thisfile = each(filenames)\n    <span style=\"color: #228B22\">% Reach each file<\/span>\n    Temp = readtable([datadir thisfile]);\n    Temp.Region = categorical(Temp.Region); <span style=\"color: #228B22\">% Convert to categorical<\/span>\n\n    <span style=\"color: #228B22\">% Identify and extract the northeast records<\/span>\n    northeast = Temp.Region == <span style=\"color: #A020F0\">'NorthEast'<\/span>;\n    Output = Temp(northeast,:);\n\n\n    <span style=\"color: #228B22\">% Make new full file name<\/span>\n    [~,name,ext] = fileparts(thisfile);\n    outputfile = fullfile(pwd,outputdir,[name <span style=\"color: #A020F0\">'_NorthEast'<\/span> ext]);\n\n    <span style=\"color: #228B22\">% Write out<\/span>\n    writetable(Output,outputfile)\n<span style=\"color: #0000FF\">end<\/span><\/pre><p>Now we can check to make sure it did what we expect.<\/p>\n   <p><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/images\/pick\/Sean\/mainForEach\/fileresults.png\"> <\/p>\n   <p>Personally, I see this being really useful for working with sets of files or images, like I have done above, or for needle\n      in the haystack type problems where I want to find something in a bunch of combinations and stop as soon as I do.\n   <\/p>\n   <h3>Advanced Programming Challenge!<a name=\"6\"><\/a><\/h3>\n   <p>And now for a challenge:<\/p>\n   <p>I used the informal interface to this toolbox, i.e. the <tt>each<\/tt> function, to traverse each file.  There is also a formal interface that provides the ability to define your own <a href=\"http:\/\/en.wikipedia.org\/wiki\/Iterator\">iterators<\/a> so that you can traverse objects of your own class or anything else.  I will give some MathWorks goodies to anyone who will\n      write their own <tt>eachFile<\/tt> iterator that I could use above to recreate what I have.\n   <\/p>\n   <p>Please post it <a href=\"https:\/\/blogs.mathworks.com\/pick\/?p=5868#respond\">below<\/a>.\n   <\/p>\n   <h3>Comments<a name=\"7\"><\/a><\/h3>\n   <p>The development team is actively looking for feedback on this, so please leave them a <a href=\"https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/122917-matlab-for-each#comments\">comment<\/a> with any thoughts you have.\n   <\/p>\n   <p>Give it a try and let us know what you think <a href=\"https:\/\/blogs.mathworks.com\/pick\/?p=5868#respond\">here<\/a>.\n   <\/p><script language=\"JavaScript\">\n<!--\n\n    function grabCode_244d5934388a49b9b527845693248f20() {\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='244d5934388a49b9b527845693248f20 ' + '##### ' + 'SOURCE BEGIN' + ' #####';\n        t2='##### ' + 'SOURCE END' + ' #####' + ' 244d5934388a49b9b527845693248f20';\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 2015 The MathWorks, Inc.';\n\n        w = window.open();\n        d = w.document;\n        d.write('<pre>\\n');\n        d.write(code_string);\n\n        \/\/ Add author and copyright lines at the bottom if specified.\n        if ((author.length > 0) || (copyright.length > 0)) {\n            d.writeln('');\n            d.writeln('%%');\n            if (author.length > 0) {\n                d.writeln('% _' + author + '_');\n            }\n            if (copyright.length > 0) {\n                d.writeln('% _' + copyright + '_');\n            }\n        }\n\n        d.write('<\/pre>\\n');\n      \n      d.title = title + ' (MATLAB code)';\n      d.close();\n      }   \n      \n-->\n<\/script><p style=\"text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray\"><br><a href=\"javascript:grabCode_244d5934388a49b9b527845693248f20()\"><span style=\"font-size: x-small;        font-style: italic;\">Get \n            the MATLAB code \n            <noscript>(requires JavaScript)<\/noscript><\/span><\/a><br><br>\n      Published with MATLAB&reg; R2014b<br><\/p>\n<\/div>\n<!--\n244d5934388a49b9b527845693248f20 ##### SOURCE BEGIN #####\n%% For Each\n%\n% <https:\/\/www.mathworks.com\/matlabcentral\/answers\/contributors\/3208495 Sean>'s pick this week is\n% <https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/48729-for-each For-Each> by\n% <https:\/\/www.mathworks.com\/matlabcentral\/profile\/authors\/3171300 Jeremy Hughes>.\n% \n\n%% \n% My pick this week is a toolbox from our development organization for a\n% <http:\/\/en.wikipedia.org\/wiki\/Foreach_loop for-each loop> construct in\n% MATLAB.  A for-each loop allows you to iterate over a set or dimension\n% without having to worry about indexing.\n% \n% MATLAB actually already has this built in for single elements of numeric\n% arrays:\n\n% Display each element in x\nfor thisfile = [1 pi 8 -3]\n    disp(thisfile)\nend\n\n%%\n% This could've course been written with an index like below.\n\n% Display each element in x with an index\nthisfile = [1 pi 8 -3];\nfor ii = 1:numel(thisfile)\n    disp(thisfile(ii))\nend\n\n%%\n% But what if we want to traverse every column or slice of a three\n% dimensional array?  Or each element in a cell array?  Or each combination\n% of two arrays?  This is where Jeremy's |for-each| construct comes in\n% handy since you won't need to worry about indexing.\n%\n% Let's take a bunch of csv files and make copies of them with just the\n% rows of data we care about.  These files contain energy outage\n% information for energy outages in America.   Being from New England, I\n% just want the records that correspond to the North East.\n% \n% <<fileview.png>>\n% \n\n% Scrape the data directory for all csv files\ndatadir = '.\\Data\\';\nfiles = dir([datadir '*.csv']);\nfilenames = {files.name};\ndisp(filenames)\n\n%% \n\n%  Make a directory for output\noutputdir = 'NorthEastData';\nmkdir(outputdir)\n\n% Loop over each filename, read, extract, write\nfor thisfile = each(filenames)\n    % Reach each file\n    Temp = readtable([datadir thisfile]);    \n    Temp.Region = categorical(Temp.Region); % Convert to caterogical\n    \n    % Identify and extract the northeast records\n    northeast = Temp.Region == 'NorthEast';\n    Output = Temp(northeast,:);\n        \n    \n    % Make new full file name\n    [~,name,ext] = fileparts(thisfile);\n    outputfile = fullfile(pwd,outputdir,[name '_NorthEast' ext]);\n    \n    % Write out\n    writetable(Output,outputfile)\nend\n\n%%\n% Now we can check to make sure it did what we expect.\n%\n% <<fileresults.png>>\n%\n% Personally, I see this being really useful for working with sets of files\n% or images, like I have done above, or for needle in the haystack type\n% problems where I want to find something in a bunch of combinations and\n% stop as soon as I do.\n%\n\n%% Advanced Programming Challenge!\n%\n% And now for a challenge:\n%\n% I used the informal interface to this toolbox, i.e. the |each| function,\n% to traverse each file.  There is also a formal interface that provides\n% the ability to define your own <http:\/\/en.wikipedia.org\/wiki\/Iterator\n% iterators> so that you can traverse objects of your own class or anything\n% else.  I will give some MathWorks goodies to anyone who will write their\n% own |eachFile| iterator that I could use above to recreate what I have.\n%\n% Please post it <https:\/\/blogs.mathworks.com\/pick\/?p=5868#respond below>.\n\n%% Comments\n% \n% The development team is actively looking for feedback on this, so please\n% leave them a \n% <https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/48729-for-each#comments\n% comment> with any thoughts you have.\n%\n% Give it a try and let us know what you think\n% <https:\/\/blogs.mathworks.com\/pick\/?p=5868#respond here>.\n%\n\n##### SOURCE END ##### 244d5934388a49b9b527845693248f20\n-->","protected":false},"excerpt":{"rendered":"<div class=\"overview-image\"><img decoding=\"async\"  class=\"img-responsive\" src=\"https:\/\/blogs.mathworks.com\/images\/pick\/Sean\/mainForEach\/fileview.png\" onError=\"this.style.display ='none';\" \/><\/div><p>\n   \n      Sean's pick this week is For-Each by Jeremy Hughes.\n      \n   \n   My pick this week is a toolbox from our development organization for a for-each loop construct in MATLAB.  A... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/pick\/2015\/02\/27\/for-each\/\">read more >><\/a><\/p>","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\/5868"}],"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=5868"}],"version-history":[{"count":4,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/posts\/5868\/revisions"}],"predecessor-version":[{"id":5874,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/posts\/5868\/revisions\/5874"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/media?parent=5868"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/categories?post=5868"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/tags?post=5868"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}