MATLAB Answers

avoid memory issues by clear

6 views (last 30 days)
MatG
MatG on 22 Apr 2020
Edited: Adam Danz on 22 Apr 2020
To avoid using too much memory (or breaking due to memory), is it a feasible approach to use "clearvars -except keepVariables" inside each function?
"keepVariables" would be, inside the function, what's returned by the function.

  0 Comments

Sign in to comment.

Accepted Answer

Adam Danz
Adam Danz on 22 Apr 2020
Edited: Adam Danz on 22 Apr 2020
"...is it a feasible approach to use "clearvars -except keepVariables" inside each function? "
clearvars removes all variables from the currently active workspace. Each function has its own workspace. Unless you're using persistent variables, the variables within the function are cleared as soon as the function execution ends. clearvars -except outputs is, in a sense, what the function is already doing.
Generally, any variable within a function should either be an output or a variable needed to compute/generate the outputs. Sometimes some heavy computation or large arrays are needed to compute a much smaller output and that can lead to memory problems.
One way of dealing with that is breaking the function up into sub-functions that have their own workspace. For example, you can imagine a function that produces very many plots and therefore very many large graphics objects. That function could be broken apart into several functions that each produce a plot which would greately reduce the number of graphics handles stored at one time. Follow the gernal rule that a function does 1 thing.
There are circumstances where clearing a variable from within a function could be helpful in preserving memory. For example, imagine a very large array produced solely to compute the marginal means. After the means are computed, there's no purpose of keeping the large array. In that case, clear that particular array from within the function.
Lastly, IMO, clearvars -except keepVariables is much less responsible than directly naming the variables to clear. Imagine a few months from now you open that file and add a new internal variable but forget that you're clearing all variables except a few. It may take a while to realize what the problem is. It may also hinder the troubleshooting process in debug mode after variables have been cleared.
Instead, name the variables you want to clear,
var2clear = {'bigarray', 'memoryKiller', 'wayTooBig'};
clear(vars2clear{:})

  0 Comments

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!