【问题标题】:Matlab - Generating random coordinates for a matrixMatlab - 为矩阵生成随机坐标
【发布时间】:2013-02-08 14:15:12
【问题描述】:

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

有没有在 Matlab 中快速生成这个的方法?

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

谢谢, 伙计

【问题讨论】:

标签: matlab random matrix coordinates permutation


【解决方案1】:

您可以使用randperm 生成线性索引,并在需要时使用ind2sub 将其转换为[row,col]。

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 )
    

    【讨论】:

      【解决方案3】:

      您的想法不错,尽管您甚至不必将线性索引转换回行和列索引,但您可以将线性索引直接转换为二维数组。

      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
      

      【讨论】:

      • although you don't even have to convert your linear indices back to row and col indices,OP 专门要求一种方法来生成坐标,而不是线性索引
      • @slayton 我想你是对的,我认为 OP 只是在寻找索引方案,而不是试图为其他目的生成坐标。我应该删除这个答案吗?
      • 嗯,这个答案不错,我会保留它
      猜你喜欢
      • 2016-02-15
      • 1970-01-01
      • 1970-01-01
      • 2014-10-22
      • 2020-04-20
      • 2016-06-30
      • 2012-04-10
      • 2013-08-24
      • 1970-01-01
      相关资源
      最近更新 更多