while Loop on user input

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

Answers (1)

ag
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!

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 3 Feb 2021

Edited:

on 12 Mar 2025

Community Treasure Hunt

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

Start Hunting!