将矩阵的n个条目设置为零

时间:2014-07-02 18:05:26

标签: 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对我冒险,他们可以重复几次。如何以矢量化的方式(没有循环)?

对不能重复,但他们的元素可以,例如: (1,2),(2,1),(1,1),(2,2),(23,23),(86,52)适用于范围1:100和6对

3 个答案:

答案 0 :(得分:3)

您可以对整数进行采样,然后将整数映射到这样的对:

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

这使您无需创建要从中采样的整个列表。

答案 1 :(得分:1)

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

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

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

答案 2 :(得分:1)

以下是您想要的伪代码。

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
相关问题