How do I request a user input value, but if the user does not enter it, I assign a default value instead?

1 Ansicht (letzte 30 Tage)
= input ('Enter the relative error:');

Akzeptierte Antwort

the cyclist
the cyclist am 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

Weitere Antworten (1)

Image Analyst
Image Analyst am 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 Kommentare
Sterlin
Sterlin am 17 Sep. 2013
Totally secure, but lengthy for my simple code. Thanks a lot though. I will get to use it.
Image Analyst
Image Analyst am 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?"

Melden Sie sich an, um zu kommentieren.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by