How to get integer data using inputdlg,, or using any other way?

조회 수: 25 (최근 30일)
Talha Khan
Talha Khan 2015년 4월 27일
댓글: Talha Khan 2015년 5월 4일
Hi Everyone, I am using the following command to get data using dialog box.
prompt={'Enter Lowest Energy'};
dlg_title='Input';
lowest_energy1=inputdlg(prompt,dlg_title);
disp(lowest_energy1);
In this I am giving the decimal value as an input. but i can't use it as a decimal value. the value of lowest_energy1= '1'(if i write 1 in the dialogue box).
that can not be used as decimal value. Kindly help me in this regard. Thanks in anticipation :)

채택된 답변

Image Analyst
Image Analyst 2015년 4월 27일
Here's a way to force the user to enter an integer:
% 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.
% Round to nearest integer in case they entered a floating point number.
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
  댓글 수: 4
Image Analyst
Image Analyst 2015년 4월 28일
Here's my snippet for that. Adapt as needed:
% Ask user for two floating point numbers.
defaultValue = {'45.67', '78.91'};
titleBar = 'Enter a value';
userPrompt = {'Enter floating point number 1 : ', 'Enter floating point number 2: '};
caUserInput = inputdlg(userPrompt, titleBar, 1, defaultValue);
if isempty(caUserInput),return,end; % Bail out if they clicked Cancel.
% Convert to floating point from string.
usersValue1 = str2double(caUserInput{1})
usersValue2 = str2double(caUserInput{2})
% Check for a valid number.
if isnan(usersValue1)
% They didn't enter a number.
% They clicked Cancel, or entered a character, symbols, or something else not allowed.
% Convert the default from a string and stick that into usersValue1.
usersValue1 = str2double(defaultValue{1});
message = sprintf('I said it had to be a number.\nI will use %.2f and continue.', usersValue1);
uiwait(warndlg(message));
end
Talha Khan
Talha Khan 2015년 5월 4일
Thanks a lot #image Analyst

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by