Search code examples
matlabworkspace

Partially clearing workspace in MATLAB


I have a question on the clear function in MATLAB. I would like to use the function to remove items from my workspace, in order to freeing up system memory. Just performing the code, I would run into an error otherwise.

Therefore, I'm clearing all the variables that are no longer required. This is especially true for variables used to calculate another one. Let's assume I'd have:

a = 2;
b = 3;
c = a + b;

Thereafter, I would just continue to work with c. Is there an alternative to clear the workspace for a and b other than adding clear a; clear b; In other words, is there a function that allows to delete any variable that is just used to compute another variable?


Solution

  • Not realy but you can utilise some of the features of clear, e.g.

    a = 2; 
    b = 3;
    c = a + b
    clearvars -except c
    

    will leave just c

    Or you could use similar names and wildcards in the clear statement

    temp_a = 2; 
    temp_b = 3;
    c = temp_a + temp_b
    clearvars temp*
    

    Also its worth reminding you that you can do:

    clearvars a b etc