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)
Ältere Kommentare anzeigen
= input ('Enter the relative error:');
0 Kommentare
Akzeptierte Antwort
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
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
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?"
Siehe auch
Kategorien
Mehr zu Linear Algebra finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!