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

 Akzeptierte Antwort

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 Kommentar

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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by