Terminate while loop when user hits enter
24 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hi eveyone,
This is my while loop. It must end when user hits enter without entering a value . The loop allows for upto 3 successive blank entries before terminating. And, I cant get the n_points matrix to save entries without error.
How do I fix these?
Thank you for your time.
clear all
disp('Begin entering the data points')
t = 1;
x_point = input('enter x : ')
y_point = input('enter y : ')
n_points = [x_point,y_point];
while x_point ~= isempty(x_point) | y_point ~= isempty(y_point) % does not terminate immedeately when user presses enter without entering a value.
x_point = input('enter x : ')
y_point = input('enter y : ')
t = t+1
n_points(t,:) = [x_point,y_point];
end
0 commentaires
Réponse acceptée
Jan
le 11 Avr 2021
Modifié(e) : Jan
le 11 Avr 2021
Avoid repeating code:
disp('Begin entering the data points')
t = 0;
while true % Infinite loop
x_point = input('enter x : ');
if isempty(x_point)
break; % Stop the WHILE loop
end
y_point = input('enter y : ');
if isempty(y_point)
break; % Stop the WHILE loop
end
t = t + 1;
n_points(t, :) = [x_point, y_point];
end
Or:
disp('Begin entering the data points')
t = 0;
ready = false;
while ~ready
x_point = input('enter x : ');
if ~isempty(x_point)
y_point = input('enter y : ');
end
if ~isempty(x_point) && ~isempty(y_point)
t = t + 1;
n_points(t, :) = [x_point, y_point];
else
ready = true;
end
end
Plus de réponses (1)
Jonathan Clayton
le 10 Avr 2021
the code below looks at the number of elements that the user has inputed for that loop, and if that number is zero then the loop is broken.
if numel(x_point)+numel(y_point)==0
break
end
Add this code above n_points variable so that the empty vaibles are not added to your list.
4 commentaires
Voir également
Catégories
En savoir plus sur General Applications dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!