필터 지우기
필터 지우기

Basic Function that Prompts User and then Calculates Accordingly

조회 수: 1 (최근 30일)
shiffraw dagnechaw
shiffraw dagnechaw 2018년 8월 22일
답변: Image Analyst 2018년 8월 24일
I'm trying to create a function that gives the user a prompt box that asks the user to choose subtraction or division. This is just a very basic version of what I'm trying to do. I'll paste my code below.
function[result1] = calculate1(x,y)
z = inputdlg({'Subtraction or Division'})
if z == 'subtraction'
x + 1
else
y + 1
end
end
  댓글 수: 2
Rik
Rik 2018년 8월 22일
Your output is not defined in this function, and you are using == instead of strcmp, which will likely result in unintended behavior.
Wycliff Dembe
Wycliff Dembe 2018년 8월 24일
In addition to using strcmp and defining result1 in the function you can also consider abstracting the input if there are only two or few input choices by creating question dialog box to avoid the case sensitivity and other user input errors. Ref: https://www.mathworks.com/help/matlab/ref/questdlg.html

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

답변 (2개)

Walter Roberson
Walter Roberson 2018년 8월 24일
inputdlg() returns a cell array of character vectors.
z = inputdlg({'Subtraction or Division'});
if strcmpi(z{1}, 'subtraction')
...
end
You should also consider using menu()
  댓글 수: 1
Steven Lord
Steven Lord 2018년 8월 24일
I second Walter's recommendation to use menu. If you must use inputdlg instead of menu (you're trying to complete a homework assignment that specifically instructs you to use inputdlg, for example) I recommend using a switch statement instead of an if statement. See the first example on the switch documentation page for a demonstration of switch, case, and otherwise.

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


Image Analyst
Image Analyst 2018년 8월 24일
Use questdlg():
promptMessage = sprintf('What do you want to do?');
titleBarCaption = 'Which Operation?';
buttonText = questdlg(promptMessage, titleBarCaption, 'Subtraction', 'Division', 'Quit', 'Subtraction');
if contains(buttonText, 'Quit')
% Bail out.
return;
elseif contains(buttonText, 'Subtraction')
% Do your subtraction code.
else
% Addition code...
end

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by