How to end loop after key is press
113 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Addison Collins
el 15 de Jul. de 2021
Editada: Addison Collins
el 15 de Jul. de 2021
Hello everyone,
I am attempting to make it so I can have as many iterations as I want in the for loop. I want to choose when I am done using ginput rather than relying on a preset number ("num" in the code below). This would mean running the loop until I press a key, after which the loop is exited. I have attached an image of the plot.
EDIT: I edited the code posted below to reflect my final script that works. If enter is pressed, ginput will not throw an error, and the loop will be exited. If another key is pressed, the loop will also stop. NOTE that when a different key other than 'ENTER' is used to break from the loop, an additional point will be plotted wherever the cursor is located. I am too lazy to fix this at the moment.
clc;clear;close all
rng default
xq = rand(500,1)*5;
yq = rand(500,1)*5;
f = figure;
j = 1;
plot(xq,yq,'b+'); hold on;
axis equal
while true
try % ginput(number) throws error when 'ENTER' is pressed
[xv(j), yv(j)] = ginput(1);
plot(xv(j),yv(j),'ro','MarkerFaceColor','r','MarkerSize',3)
if j > 1
plot(xv(j-1:j),yv(j-1:j),'LineWidth',2,'color','red') % polygon
end
j=j+1;
catch
break;
end
% In case something other than enter is pressed
if f.CurrentCharacter > 0
break;
end
end
in = inpolygon(xq,yq,xv,yv);
figure
plot(xv,yv,'LineWidth',2,'color','red') % polygon
axis equal
hold on
plot(xq(in),yq(in),'r+') % points inside
plot(xq(~in),yq(~in),'bo') % points outside
0 comentarios
Respuesta aceptada
Scott MacKenzie
el 15 de Jul. de 2021
Editada: Scott MacKenzie
el 15 de Jul. de 2021
Here's an arrangement I've used with good success in the past. The loop executes indefinitely until a key is pressed.
f = figure;
% other code
while true
% put your loop code here
if f.CurrentCharacter > 0
break;
end
end
5 comentarios
Scott MacKenzie
el 15 de Jul. de 2021
Editada: Scott MacKenzie
el 15 de Jul. de 2021
I've deleted this comment, as I see in your next comment that you've now got things working just fine.
Más respuestas (0)
Ver también
Categorías
Más información sobre Data Exploration en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!