Needing 'clear all' type function, except a few variables. clearvars -except isn't aggressive enough

9 views (last 30 days)
I want to use clear all, except keep certain variables.
I am using a third party toolkit, and basically want to clear out the buffer and other variables being used in that toolkit. I have no other way to clear it, so as I make requests, the requests take longer and longer until the program basically stops running. This happens pretty quickly as I'm making a lot of requests.
'clearvars -except var_name' doesn't have the same behavior as 'clear all', as it's not aggressive enough to take out everything, so it doesn't work for my application.
Right now I'm doing this:
  1. save the relevant variables to file
  2. clear all
  3. load the relevant varaibles back from file
This makes the code take forever to run since it's saving/loading a lot of data.
Does anyone know of a way around this? I'm thinking there must be some way, but I'm not finding anything in searches.

Answers (1)

Steven Lord
Steven Lord on 1 Sep 2023
From your description I'm guessing the third party toolkit is written using a lot of script files rather than functions or classes. If so I recommend writing functions that wrap those script files. Have those functions only accept as inputs the data those scripts specifically and explicitly require for their operation and only return the outputs that you absolutely need from those scripts. Let the intermediate "helper" variables those scripts create stay in the function workspace and get destroyed automatically when the function calls finish executing and their workspaces get cleaned up normally.
  1 Comment
Mike Ray
Mike Ray on 11 Sep 2023
Sorry for the late reply, I got side tracked on another set of unrelated code issues. I tried encapsulating the function like you suggested and it doesn't appear to make a difference in the runtimes unfortunately. I'm using IB-MATLAB and IQML third party packages and they're written with functions since I'm passing stuff into the data fetching functions.
The only thing that seems to work is clearing the workspace and then reloading it, but the write/load takes absolutely forever since I have to do it so frequently and the workspace files are not small. I'm still trying to figure out other ways around it, and haven't given up yet

Sign in to comment.




Community Treasure Hunt

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

Start Hunting!