【问题标题】:Setting n entries of matrix to zero将矩阵的 n 个条目设置为零
【发布时间】:2014-08-23 15:41:33
【问题描述】:

我想将矩阵的n 条目设置为零,下面是我通过生成唯一的整数对来解决这个问题的尝试。

如何从均匀分布(x,y) 中生成唯一的整数对,例如,如果我们想要三对 x 和 y 在 1:1000 范围内,那么解决方案之一是: (1,888),(743,743),(743,4)
如果我使用cbind(sample(1:1000,100,replace=TRUE),sample(1:1000,100,replace=TRUE)) 生成100 对,我冒着风险,它们可能会重复几次。如何以矢量化方式制作(无循环)?​​

对不能重复,但它们的元素可以,例如: (1,2),(2,1),(1,1),(2,2),(23,23),(86,52) 是 1:100 范围和六对的正确输出

【问题讨论】:

  • 澄清一下,您允许对重复,例如(1,2) (1,2),但不允许一对元素重复,例如(1,1), (2,2)?
  • @Randy Lai 不,我想要相反的
  • replace=TRUE 是否表示您正在抽样更换?如果是这样,您可以在区间[1, 1000*1000]中随机选择而不替换,然后将它们转换为对。
  • 哦,既然您使用的是replace=TRUE。我以为你允许这对重复。
  • @Patrick87 抱歉,我误读了您的评论...

标签: r algorithm


【解决方案1】:

您可以对整数进行采样,然后将整数映射到如下所示的对:

v <- sample.int(1000^2, size = 100, replace = F)
foo <- function(x) cbind(((x-1) %/% 10) + 1, ((x-1) %% 10) + 1)
foo(v)

这使您不必创建整个列表来采样。

【讨论】:

    【解决方案2】:

    如果您想要将矩阵的某些条目归零,则有一种更简单的方法。你可以这样做

    A[sample.int(1000*1000, 100, replace=FALSE)] = 0
    

    A 是您的矩阵。 由于元素是按列提取的,因此您不必将索引转换为 (row, col) 对。

    【讨论】:

    • 接受讨论,见下面问题的cmets
    【解决方案3】:

    以下是您想要的伪代码。

    Store M x N matrix --> ArrayM of one dimension and size M x N
    
    For i = 1 to n    // n is the number of zeros you want
    
        Generate RandomInteger in the interval [1, M x N - i]
        Set aside the (row,col) coordinates of the element as a Zero element
        ReCreate ArrayM, now of size M x N - 1 containing remaining elements (and their original x,y addresses)
        // you dont have to recreate it, you can implement it using some linked list
    
     Loop i
    

    【讨论】:

      猜你喜欢
      • 2016-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-15
      相关资源
      最近更新 更多