r语言 - 使矩阵的n个元素为零

  • 本文关键字:元素 r语言 algorithm
  • 更新时间 :
  • 英文 :


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

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

pair不能重复,但它们的元素可以,例如:(1、2),(2,1),(1,1),(2,2),(23日23),(86年52)是适当的输出范围1:10 0和6对

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

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

如果您想要将矩阵中的某些元素归零,有一种更简单的方法。你可以直接输入

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

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

下面是您想要的伪代码。

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

最新更新