i want x,y coordinates which are randomly generated between 1 to 300 ,condition is distance between every coordinate is >20. how to proceed further
이전 댓글 표시
i=5 ; %% no. of random coordinates
xc = round((1 + (60-1)*rand(i,1)),0); %% random X- coordinates
yc = round((1 + (40-1)*rand(i,1)),0); %% random Y- coordinates
c = [xc,yc] ; %% storing random coordinates in a matrix
d = pdist(c); %% pdist finds distance between each and every coordinate (all possible distances)
z= squareform(d);%% it gives a 5*5 matrix containing distances
v = 500; %%
n = size(z,1);
z(1:(n+1):end) = v; %% replacing diagonal elements by some scalar because all diag elements wiil be zero
index = find(z<20) %% find which index number in matrix which are less than 20
채택된 답변
추가 답변 (1개)
Image Analyst
2018년 12월 14일
You can use a strategy where you get a point, then use sqrt() to get the distances from all prior points. If it's farther away than 20 from all of them, then keep it, otherwise throw it away and try a new point.
pointsToPlace = 5 ; % # of random coordinates we need to place
% Preallocate points
x = zeros(1, pointsToPlace);
y = zeros(1, pointsToPlace);
loopCounter = 1;
maxIterations = 10000; % Number of tries before giving up.
numberPlaced = 0; % No points placed yet.
while numberPlaced < pointsToPlace && loopCounter < maxIterations
% Get new coordinate
xProposed = round((1 + (60-1)*rand()),0); %% random X- coordinates
yProposed = round((1 + (40-1)*rand()),0); %% random Y- coordinates
if loopCounter == 1
% First one automatically gets added of course.
numberPlaced = 1;
x(numberPlaced) = xProposed;
y(numberPlaced) = yProposed;
else
% Compute distance to all prior coordinates.
distances = sqrt((xProposed - x(1:numberPlaced)) .^ 2 + (yProposed - y(1:numberPlaced)) .^2);
% If less than 20, add it
if min(distances > 20)
numberPlaced = numberPlaced + 1;
x(numberPlaced) = xProposed;
y(numberPlaced) = yProposed;
end
end
loopCounter = loopCounter + 1;
end
fprintf('Placed %d points after %d iterations\n', numberPlaced, loopCounter-1);
plot(x, y, 'b*', 'LineWidth', 2, 'MarkerSize', 14);
grid on;
xlim([0, 60]);
ylim([0, 40]);
xlabel('X', 'FontSize', 20);
ylabel('Y', 'FontSize', 20);

카테고리
도움말 센터 및 File Exchange에서 Linear Predictive Coding에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
