Does MATLAB efficiency benefit from clearing temporary variables?

MATLAB has an annoying function, sometimes requiring the creation of temporary variables, for example. temporary_variable to create something that needs to be used in another variable, after which the temporary variable is not used anywhere in the code. Is there a performance advantage when using clear temporary_variable after the temporary variable has done its job? What is the most effective way to solve this situation? Thank you for understanding!

+6
source share
2 answers

A few comments:

  • If you run out of memory, clearing variables will almost certainly not help performance.
  • In my experience, the problem with the propagation of temporary variables is a contribution to programming errors. For instance. you have a typo, I write x instead of x , but your code does not immediately throw an error, because earlier you defined x .
  • However, I almost never try to clear temporary variables during a MATLAB script.

Tips for keeping your workspace clean (mainly to reduce coding errors)

  • Use the clear command at the beginning of the script. (This reduces the problems of Heisenbug , where the code is working or not working depending on what you did before running the script ...)
  • Put all / all of your code in custom functions . Variables local to the function automatically leave the scope (i.e., Disappear) after the function finishes and inside the function, you cannot mistakenly access variables in your workspace that you should not access.
+3
source

I would say that it is good practice to avoid creating temporary variables if they are too large. I guess I don’t need to explain in detail why this is bad. In most cases, there are alternatives that do not require temporary variables. If temporary variables are still needed, in many cases they are used only once. In this case, you can combine the expressions that you want to write into one expression (in case it does not become messy)

 a = 1:10; b = a(a>5); 

This will create this temporary variable anyway, but you don't have to clear it. Matlab does this cleanup on its own. However, if the pace becomes a problem, it is most likely due to design issues or too large functions. The only problem I noticed with high memory consumption is the memory problem. My experience is that the more information you store in memory, the faster the program runs. It takes a long time to recount some things. However, in most cases, there is a trade-off between memory efficiency and processing efficiency.

0
source

All Articles