- input - https://www.mathworks.com/help/matlab/ref/input.html
- strcmpi - https://www.mathworks.com/help/matlab/ref/strcmpi.html
- while loop - https://www.mathworks.com/help/ecoder/ug/while-loop.html
while Loop on user input
조회 수: 2 (최근 30일)
이전 댓글 표시
Hi i am new for Matlab may i know to create a loop function when user input ?
purchase type L for Laptop and D for Desktop
if user input L or D
will disply Laptop or ether Desktop depent on input
if user input invild data will show invild input and loop to puchase type ask for input puchase type again
purchase_type = input("Enter type of purchase (L for Laptop / D for Desktop): ", "s");
if purchase_type >= ("L for laptop , D for Desktop ");
else
purchase_type = "invalid";
end
if strcmp(purchase_type, "invalid") == false
fprintf("Invalid type of puchase_type! %s\n");
else
fprintf input = ("Enter type of purchase (L for Laptop / D for Desktop) %s\n"});
end
댓글 수: 0
답변 (1개)
ag
2025년 3월 12일
Hi Fushen,
Below is a modified version of your code:
% Initialize the purchase_type variable
purchase_type = '';
% Loop until a valid input is received
while true
% Prompt for user input
purchase_type = input("Enter type of purchase (L for Laptop / D for Desktop): ", "s");
% Check if the input is valid
if strcmpi(purchase_type, 'L')
fprintf("You selected: Laptop\n");
break; % Exit the loop
% similar logic for other case
else
fprintf("Invalid input!");
end
end
For more details, please refer to the following MathWorks documentations:
Hope this helps!
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!