How do I correct this code to not use the 'break' command?

function P = cities(N,border,hub)
SB = size(border);
SH = size(hub);
if length(N) ~= 1
error('N cannot be a matrix')
elseif N <= 0
error('N must be larger than 0')
elseif mod(N,1) ~= 0
error('N must be an integer')
elseif SH(2) ~= 2 || SH(1) ~= 1
error('Input "border" must be a 1x2 matrix')
elseif SB(2) ~= 2
error('Input "border" must be a two column array')
else
xb = border(:,1)'; %Column 1 of border
yb = border(:,2)'; %Column 2 of border
for i= 1 : N
while (1)
xrand=min(xb)+(max(xb)-min(xb)).*rand(1);%In general, you can generate N random numbers in the interval (a,b) with the formula r = a + (b-a).*rand(N,1).
yrand=min(yb)+(max(yb)-min(yb)).*rand(1);%Used min and max to make the boundary guess a little better
if inpolygon(xrand,yrand,xb,yb)==1; %Exit While loop when inside polygon
break
end
end
Prand(i,:)=[xrand yrand]; %Populate random locations matrix
end
P=[hub;Prand]; %Combine input hub with random locations for output
end

 採用された回答

Walter Roberson
Walter Roberson 2017 年 5 月 10 日

1 投票

keep_searching = true;
while keep_searching
xrand=min(xb)+(max(xb)-min(xb)).*rand(1);%In general, you can generate N random numbers in the interval (a,b) with the formula r = a + (b-a).*rand(N,1).
yrand=min(yb)+(max(yb)-min(yb)).*rand(1);%Used min and max to make the boundary guess a little better
if inpolygon(xrand,yrand,xb,yb)==1; %Exit While loop when inside polygon
keep_searching = false;
end
end

1 件のコメント

Brandon Coker
Brandon Coker 2017 年 5 月 10 日
You are awesome! I couldn't for the life of me figure out how to do it without break!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by