This functionality has been posted to the FEX many times, e.g., keep, keep2, keep3. This functionality also exists as part of MATLAB itself starting with R2008a, i.e.,
clearvars -except v1 v2 ... clears all variables except for those specified following the -except flag. Use the wildcard character '*' in a variable name to exclude variables that match a pattern from being cleared. clearvars -except X* clears all the variables in the current workspace, except for those that start with X, for instance.