2013-02-22 328 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