向R中的矩阵添加可调整的随机噪声 [英] Adding adjustable random noise to a matrix in R

查看:321
本文介绍了向R中的矩阵添加可调整的随机噪声的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个矩阵生成函数,它生成 1 s的下三角和 0s 的上三角。

I have a matrix generating function that produces lower-triangle of 1s and upper-triangle of 0s.

我想知道是否可能添加一些可调的随机噪声(从某些分布中得出随机的 0 1 )输出矩阵,以使随机 0 s随机替换底部 1 s和随机的 1 s随机替换一些顶部的 0 s?

I was wondering if it might be possible to add some adjustable random noise (from some distribution that gives random 0 and 1) to the outputted matrix such that the random 0s randomly replace some of the bottom 1s, and random 1s randomly replace some of the top 0s?

lower_mat <- function(r, c) {
  m <- matrix(0, nrow=r,ncol=c)
  m[lower.tri(m)] <- 1
  m
}


lower_mat(5,4)
#      [,1] [,2] [,3] [,4]
# [1,]    0    0    0    0
# [2,]    1    0    0    0
# [3,]    1    1    0    0
# [4,]    1    1    1    0
# [5,]    1    1    1    1


推荐答案

如果要假设您要从较低到较高交换一定数量的职位,您可以

If you want to assume that you are swapping from lower to upper a certain number of positions, you could do

swap_upper_lower <- function(m, n) {
  tops <- which(upper.tri(m))
  bots <- which(lower.tri(m))
  stopifnot(length(bots)>=n && length(tops)>=n)
  tops <- sample(tops, n)
  bots <- sample(tops, n)
  vals <- m[tops]
  m[tops] <- m[bots]
  m[bots] <- vals
  m
}

mm <- lower_mat(5,4)
swap_upper_lower(mm, 3)

这会将3个值从下三角交换到上三角

That will swap 3 values from the lower triangle to the upper triangle

如果您希望将其视为交换0和1的位置,则可以代替

If you would prefer to think of it as swapping the positions of 0's and 1's you could instead do

swap_0_1 <- function(m, n) {
  ones <- which(m==1)
  zers <- which(m==0)
  stopifnot(length(ones)>=n && length(zers)>=n)
  ones <- sample(ones, n)
  zers <- sample(zers, n)
  vals <- m[ones]
  m[ones] <- m[zers]
  m[zers] <- vals
  m
}

请注意,这将对角线上的值与其他函数不同。

Note this will treat values on the diagonal differently than the other function.

这篇关于向R中的矩阵添加可调整的随机噪声的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆