我需要在空间中随机移动10个随机点(N,S,E,W) 例如 每个点必须随机选择方向(N,S,E,W)并移动固定距离并再次选择方向并移动固定距离(不停止) 请帮忙。
clear all;
X=200;
Y=200;
Num=10;
A=[1 2 3 4];
Loc_Nodes=zeros(2,Num);
for i=1:2
% Loc_Nodes(i,:) = randperm(X,Num);
% end
Loc_Nodes(1,:)=X*rand(1,Num);
Loc_Nodes(2,:)=Y*rand(1,Num);
end
scatter (Loc_Nodes(1,:),Loc_Nodes(2,:),'mo');
drawnow;
pause(0.1)
答案 0 :(得分:0)
你快到了。您目前正在努力定义运动应如何工作,如果它们只是NESW,那么最简单的方法是考虑与x和y坐标的关系。
特别是,向北移动一步是y=y+1; x=x+0;
,而向东一步是y=y+0; x=x+1;
等。您可以在矩阵中对此进行汇总,然后随机选择一行添加到每个点的坐标。
此代码使用相同的绘图逻辑,有关详细信息,请参阅注释:
num = 10; % number of points
pts = zeros(num, 2); % Set points coordinates initially to the origin, num x 2 matrix
movements = [0, 1; 1, 0; -1, 0; 0, -1]; % NESW movements in terms of x and y
stepsize = 1; % step size at each iteration
figure; % create new figure
for k = 1:20
% Get random movement row for each point, add it to current location
pts = pts + stepsize*movements(randi([1,4], num, 1),:);
% plot and pause
scatter(pts(:,1), pts(:,2), 'mo');
drawnow;
pause(0.1);
end
您可能需要修复轴限制,以使绘图不会遍布整个地方。
for k = 1:20
% Get random movement row for each point, add it to current location
pts = pts + stepsize*movements(randi([1,4], num, 1),:);
% plot and pause
scatter(pts(:,1), pts(:,2), 'mo');
drawnow;
xlim([-10,10]);
ylim([-10,10]);
pause(0.1);
end