Suppose I run a script X.m and it creates a bunch of variables, and I want to save a variable called Z, so I write myVar = Z.
X.m
Z
myVar = Z
There's Keep on the MATLAB file exchange which lets you clear everything except certain variables that you wish to keep.