{"id":131,"date":"2008-03-10T07:38:56","date_gmt":"2008-03-10T12:38:56","guid":{"rendered":"https:\/\/blogs.mathworks.com\/loren\/2008\/03\/10\/keeping-things-tidy\/"},"modified":"2011-03-08T18:01:12","modified_gmt":"2011-03-08T18:01:12","slug":"keeping-things-tidy","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/loren\/2008\/03\/10\/keeping-things-tidy\/","title":{"rendered":"Keeping Things Tidy"},"content":{"rendered":"<div xmlns:mwsh=\"https:\/\/www.mathworks.com\/namespace\/mcode\/v1\/syntaxhighlight.dtd\" class=\"content\">\r\n   <introduction>\r\n      <p>In the past, when you opened a file in a MATLAB program, you had to keep track of it so you could close it under all possible\r\n         conditions, i.e., if reading or processing failed, worked partially, or worked perfectly. You could achieve this using the\r\n         <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/try.html\"><tt>catch<\/tt><\/a> block after a <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/try.html\"><tt>try<\/tt><\/a>. But you still might have to know before closing the file if everything you wanted to do was complete.  Code could easily\r\n         get awkward and buggy if there were lots of code paths to watch out for.  With <a href=\"https:\/\/www.mathworks.com\/products\/new_products\/latest_features.html?s_cid=HP_RH_2008a\">R2008a<\/a>, you can use the <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/oncleanup.html\"><tt>onCleanup<\/tt><\/a> class to help you out more cleanly.\r\n      <\/p>\r\n   <\/introduction>\r\n   <h3>Contents<\/h3>\r\n   <div>\r\n      <ul>\r\n         <li><a href=\"#1\">Example Code - Open File<\/a><\/li>\r\n         <li><a href=\"#4\">Example Code - Manage Open, Close, and Errors Using try\/catch<\/a><\/li>\r\n         <li><a href=\"#6\">Example Code - Use onCleanup to Ensure File Closes<\/a><\/li>\r\n         <li><a href=\"#8\">Example Code - Use onCleanup and Process After Opening the File<\/a><\/li>\r\n         <li><a href=\"#11\">Example Code - Use onCleanup and Process and Close File on Completion<\/a><\/li>\r\n         <li><a href=\"#15\">Other Uses?<\/a><\/li>\r\n      <\/ul>\r\n   <\/div>\r\n   <h3>Example Code - Open File<a name=\"1\"><\/a><\/h3>\r\n   <p>Here's the start of a file I've written that opens up an image file for reading, using <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/fopen.html\"><tt>fopen<\/tt><\/a>.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">type <span style=\"color: #A020F0\">openImageFile0<\/span><\/pre><pre style=\"font-style:oblique\">\r\nfunction openImageFile0\r\n% openImageFile Open an image file.\r\nfd = fopen('pout.tif');\r\n\r\n<\/pre><p>If I run it, you can see that I never close the file.<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">openImageFile0()\r\nfids = fopen(<span style=\"color: #A020F0\">'all'<\/span>)\r\nfilename = fopen(fids(1));\r\nfilename(end-30:end)<\/pre><pre style=\"font-style:oblique\">fids =\r\n     3\r\nans =\r\ntoolbox\\images\\imdemos\\pout.tif\r\n<\/pre><p>Tidy up now.<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">fclose(fids(1));<\/pre><h3>Example Code - Manage Open, Close, and Errors Using try\/catch<a name=\"4\"><\/a><\/h3>\r\n   <p>Now let's look at another version of the code that will close the file it opens before returning.<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">type <span style=\"color: #A020F0\">openImageFile1<\/span><\/pre><pre style=\"font-style:oblique\">\r\nfunction openImageFile1\r\n% openImageFile1 Open\/process file while ensuring file is \r\n% closed on finish.\r\ntry\r\n    fd = fopen('pout.tif');\r\n    if fid == -1\r\n        error('LS:NoImageFile','no such file')\r\n    end\r\n    doMoreHere(fd);\r\ncatch Ex\r\n    disp('Can not read file')\r\nend\r\nif fid ~= -1\r\n    fclose(fid);\r\nend\r\n\r\n   \r\n\r\n<\/pre><p>You can see that, even with <tt>try\/catch<\/tt>, since I always want to close the image file, I have some extra logic at the end of the file.  And I have to be careful to\r\n      know whether the error occurs because the file was never opened, or if instead the error occurs in later processing.\r\n   <\/p>\r\n   <h3>Example Code - Use onCleanup to Ensure File Closes<a name=\"6\"><\/a><\/h3>\r\n   <p>Here's a file roughly equivalent to the first one, but it ensures that the image file is closed when the function is finished\r\n      running.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">type <span style=\"color: #A020F0\">openImageFile2<\/span><\/pre><pre style=\"font-style:oblique\">\r\nfunction openImageFile2\r\n% openImageFile2 Open an image file for further processing.\r\n%   Note: this doesn't do what you want, since the file will\r\n%   be closed after completing and the file identifier won't\r\n%   be active for use upon completion.\r\nfd = fopen('pout.tif');\r\nC = onCleanup(@()fclose(fd));\r\n<\/pre><p>To see that this works we first check that no files are open, run the function, and make sure that no files are open afterwards.<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">fb = fopen(<span style=\"color: #A020F0\">'all'<\/span>);\r\nopenImageFile2()\r\nfp = fopen(<span style=\"color: #A020F0\">'all'<\/span>);\r\nnoFilesOpen = isequal(fp,fb,[])<\/pre><pre style=\"font-style:oblique\">noFilesOpen =\r\n     1\r\n<\/pre><h3>Example Code - Use onCleanup and Process After Opening the File<a name=\"8\"><\/a><\/h3>\r\n   <p>Let's see the next version of the file.<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">type <span style=\"color: #A020F0\">openImageFile3<\/span><\/pre><pre style=\"font-style:oblique\">\r\nfunction fd = openImageFile3\r\n% openImageFile3 Open an image file for further processing.\r\n%   Note: this doesn't do what you want, since the file will \r\n%   be closed after completing and the file identifier won't\r\n%   be active for use upon completion.\r\nfd = fopen('pout.tif');\r\nC = onCleanup(@()fclose(fd));\r\n<\/pre><p>This function returns the file identifier, but as we'll see, the file is closed once the function returns.  This means that\r\n      any processing\/reading we were planning to do with the file after calling the open function will not work (since the file\r\n      will no longer be open).\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">fb = fp;\r\nfid = openImageFile3()\r\nfp = fopen(<span style=\"color: #A020F0\">'all'<\/span>);\r\nnoFilesOpen = isequal(fp,fb,[])<\/pre><pre style=\"font-style:oblique\">fid =\r\n     3\r\nnoFilesOpen =\r\n     1\r\n<\/pre><p>Even though <tt>fid<\/tt> is returned from the function call, the file is no longer open.  This is because the <tt>onCleanup<\/tt> object <tt>C<\/tt> is cleared from existence once <tt>openImageFile3<\/tt> completes execution.\r\n   <\/p>\r\n   <h3>Example Code - Use onCleanup and Process and Close File on Completion<a name=\"11\"><\/a><\/h3>\r\n   <p>Here's the last version of the file for this blog.  As long as you call it with 2 outputs, you are good to go.<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">type <span style=\"color: #A020F0\">openImageFile4<\/span><\/pre><pre style=\"font-style:oblique\">\r\nfunction [fd, C] = openImageFile4\r\n% openImageFile4 Open an image file for further processing.\r\n%   Note: this does what you want, provided you call the \r\n%   function with both output arguments.  When you are done\r\n%   cleaned up and the onCleanup object will trigger the file\r\n%   closing.\r\n\r\n% Don't even open file if function isn't called with 2 outputs.\r\nif nargout &lt; 2\r\n    error('LS:MustHave2Outputs','must call with 2 outputs')\r\nend\r\n\r\nfd = fopen('pout.tif');\r\nC = onCleanup(@()fclose(fd));\r\n<\/pre><p>This version returns the file identifier and the <tt>onCleanup<\/tt> object. Once you have processed your file, simply clear the <tt>onCleanup<\/tt> object and the file will close.\r\n   <\/p>\r\n   <p>To see how this might work, we call it from our function that does the processing.<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">type <span style=\"color: #A020F0\">run4<\/span><\/pre><pre style=\"font-style:oblique\">\r\nfunction y = run4\r\n% run4 processes an image file.\r\n[fid,C] = openImageFile4();\r\nblocksize = 100;\r\ny = [];\r\nwhile something\r\n    dat = fread(fid,count);\r\n    y = doSomething(y,dat);\r\n    something = update(something);\r\nend\r\n\r\n<\/pre><p>You can see that <tt>run4<\/tt> calls openImageFile4, and then does the required processing.  Because <tt>C<\/tt> will vanish once <tt>run4<\/tt> completes, the file will be closed.\r\n   <\/p>\r\n   <h3>Other Uses?<a name=\"15\"><\/a><\/h3>\r\n   <p>The <tt>onCleanup<\/tt> object allows you to more cleanly manage resources such as closing files, closing windows (e.g., last week someone mentioned\r\n      managing instances of <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/waitbar.html\"><tt>waitbar<\/tt><\/a>), managing switching directories.  What uses do you foresee for the <tt>onCleanup<\/tt> object in your work?  Let me know <a href=\"https:\/\/blogs.mathworks.com\/loren\/?p=131#respond\">here<\/a>.\r\n   <\/p><script language=\"JavaScript\">\r\n<!--\r\n\r\n    function grabCode_4e193762b6434086a6c1c84529fa67dd() {\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='4e193762b6434086a6c1c84529fa67dd ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' 4e193762b6434086a6c1c84529fa67dd';\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_4e193762b6434086a6c1c84529fa67dd()\"><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.6<br><\/p>\r\n<\/div>\r\n<!--\r\n4e193762b6434086a6c1c84529fa67dd ##### SOURCE BEGIN #####\r\n%% Keeping Things Tidy\r\n% In the past, when you opened a file in a MATLAB program, you had to keep\r\n% track of it so you could close it under all possible conditions, i.e., if\r\n% reading or processing failed, worked partially, or worked perfectly.\r\n% You could achieve this using the \r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/try.html |catch|>\r\n% block after a\r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/try.html |try|>.\r\n% But you still might have to know before closing the file if everything\r\n% you wanted to do was complete.  Code could easily get awkward and buggy\r\n% if there were lots of code paths to watch out for.  With \r\n% <https:\/\/www.mathworks.com\/products\/new_products\/latest_features.html?s_cid=HP_RH_2008a R2008a>,\r\n% you can use the\r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/oncleanup.html |onCleanup|>\r\n% class to help you out more cleanly.\r\n%% Example Code - Open File\r\n% Here's the start of a file I've written that opens up an image file for\r\n% reading, using <https:\/\/www.mathworks.com\/help\/matlab\/ref\/fopen.html |fopen|>.\r\ntype openImageFile0\r\n%%\r\n% If I run it, you can see that I never close the file.\r\nopenImageFile0()\r\nfids = fopen('all')\r\nfilename = fopen(fids(1));\r\nfilename(end-30:end)\r\n%%\r\n% Tidy up now.\r\nfclose(fids(1));\r\n%% Example Code - Manage Open, Close, and Errors Using try\/catch\r\n% Now let's look at another version of the code that will close the file it\r\n% opens before returning.\r\ntype openImageFile1\r\n%%\r\n% You can see that, even with |try\/catch|, since I always want to close the\r\n% image file, I have some extra logic at the end of the file.  And I have\r\n% to be careful to know whether the error occurs because the file was\r\n% never opened, or if instead the error occurs in later processing.\r\n%% Example Code - Use onCleanup to Ensure File Closes\r\n% Here's a file roughly equivalent to the first one, but it ensures that\r\n% the image file is closed when the function is finished running.\r\ntype openImageFile2\r\n%%\r\n% To see that this works we first check that no files are open, run the\r\n% function, and make sure that no files are open afterwards.\r\nfb = fopen('all');\r\nopenImageFile2()\r\nfp = fopen('all');\r\nnoFilesOpen = isequal(fp,fb,[])\r\n%% Example Code - Use onCleanup and Process After Opening the File\r\n% Let's see the next version of the file.\r\ntype openImageFile3\r\n%%\r\n% This function returns the file identifier, but as we'll see, the file is\r\n% closed once the function returns.  This means that any processing\/reading\r\n% we were planning to do with the file after calling the open function will\r\n% not work (since the file will no longer be open).\r\nfb = fp;\r\nfid = openImageFile3()\r\nfp = fopen('all');\r\nnoFilesOpen = isequal(fp,fb,[])\r\n%%\r\n% Even though |fid| is returned from the function call, the file is no\r\n% longer open.  This is because the |onCleanup| object |C| is cleared from\r\n% existence once |openImageFile3| completes execution.\r\n%% Example Code - Use onCleanup and Process and Close File on Completion\r\n% Here's the last version of the file for this blog.  As long as you call\r\n% it with 2 outputs, you are good to go.\r\ntype openImageFile4\r\n%%\r\n% This version returns the file identifier and the |onCleanup| object. Once\r\n% you have processed your file, simply clear the |onCleanup| object and the\r\n% file will close.  \r\n%%\r\n% To see how this might work, we call it from our function that does the\r\n% processing.\r\ntype run4\r\n%% \r\n% You can see that |run4| calls openImageFile4, and then does the required\r\n% processing.  Because |C| will vanish once |run4| completes, the file will\r\n% be closed.\r\n%% Other Uses?\r\n% The |onCleanup| object allows you to more cleanly manage resources such\r\n% as closing files, closing windows (e.g., last week someone mentioned managing\r\n% instances of\r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/waitbar.html |waitbar|>),\r\n% managing switching directories.  What uses do you foresee for the\r\n% |onCleanup| object in your work?  Let me know\r\n% <https:\/\/blogs.mathworks.com\/loren\/?p=131#respond here>.\r\n%\r\n##### SOURCE END ##### 4e193762b6434086a6c1c84529fa67dd\r\n-->","protected":false},"excerpt":{"rendered":"<p>\r\n   \r\n      In the past, when you opened a file in a MATLAB program, you had to keep track of it so you could close it under all possible\r\n         conditions, i.e., if reading or... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/loren\/2008\/03\/10\/keeping-things-tidy\/\">read more >><\/a><\/p>","protected":false},"author":39,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[16,3,6,44],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/131"}],"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=131"}],"version-history":[{"count":0,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/131\/revisions"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/media?parent=131"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/categories?post=131"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/tags?post=131"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}