How do I request a user input value, but if the user does not enter it, I assign a default value instead?
1 view (last 30 days)
Show older comments
= input ('Enter the relative error:');
0 Comments
Accepted Answer
the cyclist
on 17 Sep 2013
You might need to make this a little more robust, but this will work if the user simply hits Return instead of entering a value:
defaultRelativeError = 31;
relativeError = input ('Enter the relative error:');
if isempty(relativeError)
relativeError = defaultRelativeError;
end
More Answers (1)
Image Analyst
on 17 Sep 2013
Feel free to modify this snippet:
% Ask user for a number.
defaultValue = 45;
titleBar = 'Enter a value';
userPrompt = 'Enter the integer';
caUserInput = inputdlg(userPrompt, titleBar, 1, {num2str(defaultValue)});
if isempty(caUserInput),return,end; % Bail out if they clicked Cancel.
integerValue = round(str2double(cell2mat(caUserInput)));
% Check for a valid integer.
if isnan(integerValue)
% They didn't enter a number.
% They clicked Cancel, or entered a character, symbols, or something else not allowed.
integerValue = defaultValue;
message = sprintf('I said it had to be an integer.\nI will use %d and continue.', integerValue);
uiwait(warndlg(message));
end
2 Comments
Image Analyst
on 17 Sep 2013
My code does tend to be longer than most other people's because I need to write robust code for use by other people, plus it has lots of comments which most people unfortunately don't put in, and is fancier (for example using inputdlg rather than input). So my code tends to be more robust, fancier, and longer than others - I guess that's why my answers are not usually the accepted ones. Hopefully you will get used to writing robust code eventually, as the cyclist and I both recommend. When I write code I remember this phrase that I heard they use at Boeing: "Would you ride in a jet plane with code written by your group?"
See Also
Categories
Find more on Linear Algebra in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!