title: How to delete temporary files in MATLAB
body: <p>I have a MATLAB script that needs to write temporary files to disk, and then delete these files when I'm done with them. It's important that I delete the files myself (rather than letting them accumulate in the temp directory) because the code in question is in a loop that executes many times. If the files aren't promptly deleted, the script will quickly gobble up large amounts of disk space.</p>
  
  <p>I thought that the code snippet below would work, and it does when I run it on its own. For some reason, though, the snippet fails when I include it in my larger script. The temporary files don't get deleted and clutter up the temp directory.</p>
  
  <pre><code>    % create temporary file
      myTmpFile = [tempname '.wav'];
      fs = 32000;
      wavwrite(zeros(fs,1),fs,myTmpFile);
  
  
      % use the file here
  
  
      % delete the file when we're done
      prevState = recycle('off'); % turn recycle off to permanently delete files
      delete(myTmpFile)
      recycle(prevState);         % restore the state of recycle
  </code></pre>
  
  <p>Does anyone have any idea what I'm doing wrong?  I'm running MATLAB 7.10.0 on OS X 10.7.3.</p>
  
  <ul>
  <li>EDIT *</li>
  </ul>
  
  <p>I figured it out.  See my answer below.</p>