简体   繁体   English

Matlab-生成矩阵的随机坐标

[英]Matlab - Generating random coordinates for a matrix

I need to create a list (of size n) of random, non-repeating set of coordinates on a matrix of predefined size. 我需要在预定义大小的矩阵上创建一个随机的,非重复的坐标集的列表(大小为n)。

Is there a fast way to generate this in Matlab? 有没有一种快速的方法可以在Matlab中生成它?

My initial idea was to create a list of size n with permutations the size of (width x length) and to translate them back to Row and Col values, but it seems to me too much. 我最初的想法是创建一个大小为n的列表,其排列的大小为(宽度x长度),然后将它们转换回Row和Col值,但在我看来似乎太多了。

Thanks, Guy 谢了,兄弟们

You can use randperm to generate a linear index, and convert it to [row,col] if needed using ind2sub . 您可以使用randperm生成线性索引,并在需要时使用ind2sub将其转换为[row,col]。

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

As long as n is less than the number of elements in the matrix this is simple: 只要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 )

Your idea is a good one, although you don't even have to convert your linear indices back to row and col indices, you can do linear indexing directly into a 2D array. 您的想法很不错,尽管您甚至不必将线性索引转换回行索引和col索引,但您可以将线性索引直接转换为2D数组。

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

where data is your matrix. 数据是您的矩阵。 This will generate a vector of random integers between 1 and prod(size(data)) , ie one index for each element. 这将生成一个介于1和prod(size(data))之间的随机整数的矢量,即每个元素一个索引。

eg 例如

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM