MATLAB: /How does MATLAB run faster when the workspace is full of variables

memoryspeedworkspace

I've been running some finite element code written for MATLAB that takes up at least 40 variables and near 100 mb of memory in the workspace. This code takes anywhere from 28 to 32 minutes to run.
However, I noticed that if I don't clear the workspace with the CLEAR command and just run the new case, MATLAB runs the code in about 15 to 18 minutes! However, if I do clear the workspace with the CLEAR command and run a new case, it takes about 28 to 32 minutes to finish again!
I'm proficient in MATLAB but not an expert. Can someone enlighten me on why this happens and if there is some "trick" that I can exploit to make MATLAB run even faster?
I am using a Dell Precision T1500 with an i5 (64bit) processor with OS as Windows 7. The version of MATLAB is 7.6.0 (R2008a). Thanks

Best Answer

I would be willing to bet that reason you experience the speed increase is that when you issue the CLEAR command you are not only clearing the variables but also the pre-compiled functions from memory. Have a look at this:
clear all
inmem % Should be very little in memory.
F = repmat(2,3,4);
t = ismember(1:4,5:6);
inmem % M-files are compiled into memory for fast use.
clear all
inmem % The above M-files are gone again....
So if you use a lot of M-files that need to be compiled every time you issue a CLEAR, that will eat up some time. Also, depending on how things are running, you might be over-writing variables when you don't issue CLEAR rather than creating new ones, which also takes time.
As for your code taking 30 minutes, that might be something that could be reduced dramatically but it is hard to tell without seeing the code. It can take some time and experience to learn how to speed up MATLAB code, but it may be worth it. Just recently I helped a guy take his code from a running time of 50 minutes to right around 3 seconds. It is not always possible to do that, but it just depends. Good use of vectorization, proper pre-allocating of memory, smart code order and algorithm use - all of these contribute to the final running time.
Related Question