How do I request a user input value, but if the user does not enter it, I assign a default value instead?
1 回表示 (過去 30 日間)
古いコメントを表示
= input ('Enter the relative error:');
0 件のコメント
採用された回答
the cyclist
2013 年 9 月 17 日
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
その他の回答 (1 件)
Image Analyst
2013 年 9 月 17 日
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 件のコメント
Image Analyst
2013 年 9 月 17 日
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?"
参考
カテゴリ
Help Center および File Exchange で Linear Algebra についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!