Plotting random points within Boundary
Afficher commentaires plus anciens
Hello everyone,
I could use your help to improve the following code. Its about creating a map with random positions of points.
How to put points only inside of country borders?

C = get(handles.number_cities, 'String');
C = str2double(C);
if(isnan(C)), errordlg('Parameters must be numerical.','Mapping Error');
elseif(C <= 0), errordlg('Number of cities must be greater than zero','Mapping Error');
else
M = zeros(C,2); % Map initialization
for id_C = 1:1:C
M(id_C,1) = randi(100); % Random map
M(id_C,2) = randi(100);
end
Réponse acceptée
Plus de réponses (1)
If you have the perimeter coordinates, you can create a bunch of random numbers and then eliminate the ones outside of the perimeter using inpolygon.
If you don't have the perimeter coordinates, one way of getting them is with the borders function on the file exchange.
Example:
clf()
[lat,lon] = borders('Bosnia and Herzegovina');
plot(lon,lat,'k-')
axis equal
hold on
grid on
% Produce n random coordinates within the
% extent of latitude and longitude
n = 100;
xy = inf(n,2);
in = false;
while ~all(in)
% Determine which random coordinates are within
% the perimeter
in = inpolygon(xy(:,1),xy(:,2),lon,lat);
% Replace external coordinates with new rand values
xy(~in,1) = rand(sum(~in),1) * range(lon) + min(lon);
xy(~in,2) = rand(sum(~in),1) * range(lat) + min(lat);
end
% Add random coordinates
plot(xy(:,1), xy(:,2), 'rx')
xlabel('lon')
ylabel('lat')
title(char([1041 1086 1089 1085 1072 32 1080 32 1061 1077 1088 1094 1077 1075 1086 1074 1080 1085 1072]))

2 commentaires
azra hosic
le 14 Jan 2021
Adam Danz
le 14 Jan 2021
Check out the link in the second sentence of my answer.
Catégories
En savoir plus sur 3-D Visualization dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

