假设我们可以如下生成数字:如何生成,无需更换MATLAB中随机2D点
% Generating random points
NP = 30; % number of points
x = randi([0 10],1,NP);
y = randi([0 10],1,NP);
P = [x;y]; % group the points as columns in a matrix
找到重复点可以使用循环或if语句来完成,但有没有更好的解决办法?
假设我们可以如下生成数字:如何生成,无需更换MATLAB中随机2D点
% Generating random points
NP = 30; % number of points
x = randi([0 10],1,NP);
y = randi([0 10],1,NP);
P = [x;y]; % group the points as columns in a matrix
找到重复点可以使用循环或if语句来完成,但有没有更好的解决办法?
要做到这一点,我会简单地创建所有排列x
和y
,然后随机选择NP
这些排列组合。
NP = 30;
% All permutations of X and Y
[xx,yy] = meshgrid(0:10, 0:10);
% Grab NP of these permutations
indices = randperm(numel(xx), NP);
% Construct P from just these permutations
P = [xx(indices); yy(indices)].';
而只是为了验证它们实际上是独一无二的。
isequal(P, unique(P, 'rows', 'stable'))
1
你想保留还是摆脱重复?使用'rows'选项查看['unique'](http://www.mathworks.com/help/matlab/ref/unique.html?refresh=true)。 – Suever
@Suever我想用新的随机点替换它们 – Remy