2016-03-28 90 views
0

假设我们可以如下生成数字:如何生成,无需更换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语句来完成,但有没有更好的解决办法?

+1

你想保留还是摆脱重复?使用'rows'选项查看['unique'](http://www.mathworks.com/help/matlab/ref/unique.html?refresh=true)。 – Suever

+0

@Suever我想用新的随机点替换它们 – Remy

回答

0

要做到这一点,我会简单地创建所有排列xy,然后随机选择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 
+0

这是一个很好的解决方案谢谢 – Remy

+0

@Remy任何理由你没有选择它作为答案? – Suever

+0

没问题,这是一个错误 – Remy