How to end loop after key is press
118 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Scott MacKenzie
2021-7-15
编辑:Scott MacKenzie
2021-7-15
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 个评论
Scott MacKenzie
2021-7-15
编辑:Scott MacKenzie
2021-7-15
I've deleted this comment, as I see in your next comment that you've now got things working just fine.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Exploration 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!