How can I add a required step before a built-in function runs after calling it?

1 view (last 30 days)
For example, sometimes in a stupor I type in 'clear' and press enter when I mean to type in 'clear x' and press enter. Is there anyway I can require an extra keyboard input after using 'clear' to prevent accidentally clearing all variables? I would like to be prompted by 'Press 'y' if you want to clear all variables.' Is this possible?

Accepted Answer

the cyclist
the cyclist on 21 Jun 2015
I think the simplest way to do this would be to make a function called myclear, which behaves the way you want. For example, it could first check whether you called it with arguments, check with you, then call the MATLAB clear command.
You could use the nice keep function from the File Exchange as a model for how to construct the exact behavior you want.
  2 Comments
Image Analyst
Image Analyst on 21 Jun 2015
No need for the File Exchange keep function with recent versions of MATLAB:
clearvars variables -except keepVariables
removes the variables specified by variables, and does not
remove the variables specified by keepVariables. This syntax
allows you to use a combination of variable names, wild card
characters, or regular expressions to specify variables to remove
or keep.
Kelly
Kelly on 21 Jun 2015
Edited: Kelly on 21 Jun 2015
Thanks for the great suggestion. I wrote this function. I'm sure it will save me in the future.
function [cl] = myclear
clc
prompt = 'Select from the following:\n1=>Clear all variables.\n2=>Clear all variables except those specified.\n3=>Clear only specified variables.\nPress any other key to exit.\n\nYour Choice:';
str = input(prompt,'s');
clc
if isempty(str) || (str ~= '1' && str ~= '2' && str ~= '3')
disp('Variables will not be cleared.')
elseif str == '1'
evalin('caller','clear')
elseif str == '2'
prompt = 'Enter variable names to keep separated by spaces.\n\nVariable Names:';
str = input(prompt,'s');
evalin('caller',['clearvars -except ' str])
elseif str == '3'
prompt = 'Enter variable names to clear separated by spaces.\n\nVariable Names:';
str = input(prompt,'s');
evalin('caller',['clearvars ' str])
end

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!