2013-02-22 646 views
1

我需要在预定义大小的矩阵上创建一个随机,非重复坐标集的列表(大小为n)。Matlab - 为矩阵生成随机坐标

有没有一种在Matlab中生成这种快速方法?

我最初的想法是创建一个大小为n的列表,其大小为(宽x长),并将它们转换回Row和Col值,但在我看来太多了。

谢谢, 盖伊

+0

如果'n'大于矩阵中元素的数量会发生什么?重复可以接受吗? – slayton 2013-02-22 21:05:37

+0

我已经将项目上传到git:https://github.com/guywald/allele_fixation – 2014-02-08 17:29:44

回答

3

可以使用randperm成产生线性索引,并将其转换到[行,列]如果需要使用ind2sub

x = rand(7,9); 
n = 20; 
ndx = randperm(numel(x), n); 
[row,col] = ind2sub(size(x), ndx); 
2

只要n小于元件的数量在基质很简单:

% A is the matrix to be sampled 
% N is the number of coordinate pairs you want 
numInMat = numel(A); 

% sample from 1:N without replacement 
ind = randperm(numInMat, N); 

% convert ind to Row,Col pairs 
[r, c] = ind2sub(size(A), ind) 
0

你的想法是好的,但你甚至不用到你的​​线性指数转换回ROW和COL指数,你可以做线性索引直接进入一个二维数组。

idx = randperm(prod(size(data))) 

其中数据是您的矩阵。这将生成1和prod(size(data))之间的随机整数向量,即每个元素的一个索引。

例如

n = 3; 
data = magic(n); 
idx = randperm(prod(size(data))); 
reshape(data(idx), size(data)) %this gives you your randomly indexed data matrix back 
+0

'尽管您甚至不必将线性索引转换回行和列索引,但是OP特别要求方式来产生坐标,而不是线性索引 – slayton 2013-02-22 21:17:08

+0

@slayton我想你是对的,我已经认为OP只是寻找索引方案,而不是为了某种其他目的而生成坐标。我应该删除这个答案吗? – alrikai 2013-02-22 21:20:03

+0

恩,这不是一个坏的答案我会保留它 – slayton 2013-02-22 22:17:11