- 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
6 views (last 30 days)
Show older comments
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 Comments
Answers (1)
ag
on 12 Mar 2025
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 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!