How to end loop after key is press
119 ビュー (過去 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!