random position within a sequare

3 次查看(过去 30 天)
m h
m h 2016-2-9
回答: Aditya 2025-5-28
Hello;
I have a a number of users N and I want to randomly distribute them over a square range of [-10,10]. I used the random function but most of the point end up at the same line. Also, I need to distribute r users near to specific N users with specific distance (between chosen N and r). Can any one explain for me how could I do this?
Thank you in advance.

回答(1 个)

Aditya
Aditya 2025-5-28
Hi m h,
In order to achieve this, you can follow the below steps:
1. Generate random positions for N users within the square range [-10,10] using the rand() function.
N = 10; % Number of users
range = [-10, 10]; % Square boundary
% Generate random positions in 2D space
X_N = range(1) + (range(2) - range(1)) * rand(N,1);
Y_N = range(1) + (range(2) - range(1)) * rand(N,1);
2. Randomly select r users from N to determine which users will have nearby companions.
r = 5; % Number of nearby users
selected_idx = randperm(N, r); % Select r random indices
3. Generate a random angle for each r user to ensure random placement around its paired N user.
angles = 2 * pi * rand(r,1); % Generate random angles between 0 and 2π
4. Place each r user at a specific distance using cos(angle) and sin(angle)
specific_distance = 2; % fixed distance
X_r = X_N(selected_idx) + specific_distance * cos(angles); % Shift X
Y_r = Y_N(selected_idx) + specific_distance * sin(angles); % Shift Y
5. Check minimum distance constraint from all N users to avoid overlap. (You can update this constraint based on the requirement)
for i = 1:r
for j = 1:N
if j ~= selected_idx(i)
dist = sqrt((X_r(i) - X_N(j))^2 + (Y_r(i) - Y_N(j))^2);
if dist < specific_distance % If too close, regenerate position
angle = 2 * pi * rand();
X_r(i) = X_N(selected_idx(i)) + specific_distance * cos(angle);
Y_r(i) = Y_N(selected_idx(i)) + specific_distance * sin(angle);
end
end
end
end
6. Plot both N and r users distinctly
figure; hold on;
scatter(X_N, Y_N, 50, 'b', 'filled'); % N users (blue)
scatter(X_r, Y_r, 50, 'r', 'filled'); % r users (red)
legend('N Users', 'r Users (Fixed Distance)');
xlabel('X');
ylabel('Y');
title('Randomly Distributed Users with specific Distance');
grid on;
hold off;
I hope this helps!

类别

Help CenterFile Exchange 中查找有关 Random Number Generation 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by