我需要在預定義大小的矩陣上創建一個隨機,非重複座標集的列表(大小爲n)。Matlab - 爲矩陣生成隨機座標
有沒有一種在Matlab中生成這種快速方法?
我最初的想法是創建一個大小爲n的列表,其大小爲(寬x長),並將它們轉換回Row和Col值,但在我看來太多了。
謝謝, 蓋伊
我需要在預定義大小的矩陣上創建一個隨機,非重複座標集的列表(大小爲n)。Matlab - 爲矩陣生成隨機座標
有沒有一種在Matlab中生成這種快速方法?
我最初的想法是創建一個大小爲n的列表,其大小爲(寬x長),並將它們轉換回Row和Col值,但在我看來太多了。
謝謝, 蓋伊
可以使用randperm
成產生線性索引,並將其轉換到[行,列]如果需要使用ind2sub
。
x = rand(7,9);
n = 20;
ndx = randperm(numel(x), n);
[row,col] = ind2sub(size(x), ndx);
只要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)
你的想法是好的,但你甚至不用到你的線性指數轉換回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
如果'n'大於矩陣中元素的數量會發生什麼?重複可以接受嗎? – slayton 2013-02-22 21:05:37
我已經將項目上傳到git:https://github.com/guywald/allele_fixation – 2014-02-08 17:29:44