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일
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

You are awesome! I couldn't for the life of me figure out how to do it without break!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

질문:

2017년 5월 10일

댓글:

2017년 5월 10일

Community Treasure Hunt

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

Start Hunting!

Translated by