Matlab 区域内点的随机移动
我需要做10个随机点,在空间中随机移动(N,S,E,W) 例如,每个点必须随机选择一个方向(N、S、E、w)并移动固定距离,然后再次选择一个方向并移动固定距离(不停止)Matlab 区域内点的随机移动,matlab,matlab-figure,Matlab,Matlab Figure,我需要做10个随机点,在空间中随机移动(N,S,E,W) 例如,每个点必须随机选择一个方向(N、S、E、w)并移动固定距离,然后再次选择一个方向并移动固定距离(不停止) 你就快到了。您目前正在努力定义运动应该如何工作,如果它们只是NESW,那么最简单的方法就是考虑它与x和y坐标的关系 特别是,向北移动一步是y=y+1;x=x+0而向东一步为y=y+0;x=x+1等。您可以在矩阵中对此进行总结,然后随机选择一行添加到每个点的坐标中 此代码使用相同的打印逻辑,有关详细信息,请参见注释: num =
你就快到了。您目前正在努力定义运动应该如何工作,如果它们只是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
帮什么忙?请阅读,我会尝试提出一个MATLAB代码(当你试图澄清你的问题),但考虑使用(这是一个演示,找到它在主页上),因为它是建立你想做的。
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