【问题标题】:Sample the maximum value on a matrix excluding value on main diagonal对矩阵上的最大值进行采样,不包括主对角线上的值
【发布时间】:2017-09-02 16:13:20
【问题描述】:

我有一个矩阵 X,其最大值沿主对角线。 首先,要对第 i 行进行采样,然后沿第 i 行选取最大值,不包括主对角线值,即 max != X[i,i]。

下面的代码通常会产生结果但经常有错误: Error in if (MAX < l[k]) { : missing value where TRUE/FALSE needed

# initial values
n = 10
pop = runif(n,min =0,max =1)
D = matrix(rnorm(n*n,0,0.2),nrow=n)

str_mat = abs(D)
for (l in 1:n) {
  str_mat[l,l] = 1
}

int_mat = matrix(rbinom(n*n,1,z),n,n) ##z takes the values 0.1 - 0.9
for (j in 1:n) {
  int_mat[j,j] = 1
}

X = (int_mat*str_mat)*pop
b = c(1:n)  #creating a vector with the length being the dimensions of the matrix
a = sample(b,1)## sampling one value from the vector
if (sum(int_mat[a,])< n)
{
    ### int_mat is a binary matrix
    break
}}

l = X[a,]

## Ensuring the maximum value picked is not on the main diagonal
MAX = 0
j = 1
for (k in 1:length(l)) {
  if(k!=a) {
    if (MAX<l[k]) {
      MAX = l[k]
      j = k
    }
  }
}

【问题讨论】:

  • 什么是 ABX?请为我们提供一个最小的 reproducible 示例,即我们可以在 R 中运行而无需猜测上下文和数据的东西。另见stackoverflow.com/questions/5963269/…
  • 是的,您需要提供一个最小的可重现示例。只需使用随机种子整数声明 a,b,X。
  • 另外,它们的维度 n 有多大,我们对它们的取值范围了解多少?如果 X 不太大,可以复制并设置diag(X2) &lt;- -Inf,现在最大值不会出现在主对角线上。如果它很大,你也许可以使用稀疏矩阵表示。
  • 谢谢@smci .. 我使用的是 10*10 矩阵。
  • 好的,但是您需要紧急提供一个带有数据的最小可重现示例。否则,这很可能会被否决并关闭。

标签: r matrix diagonal statistical-sampling


【解决方案1】:

感谢大家的贡献。我想出了如何解决这个问题。如下;

X=(int_mat*str_mat)*pop    ## creating a matrix of interaction, competition strength and  population densities             

repeat{
  IntRowsums=rowSums(int_mat)
  introwsums_greater=which(IntRowsums>2,arr.ind = T)
  if (length(introwsums_greater)>1){
    a= sample(introwsums_greater,1)
  }else{
    a=introwsums_greater
  }
  if (sum(int_mat[a,])< n){
    break
  }}

q= ABX[a,]
j_k=which(q!=q[a] & q!=0,arr.ind = T)     ## from the sampled row in str_mat check the position of all zeros
k=sample(j_k,1)

【讨论】:

    猜你喜欢
    • 2017-10-30
    • 1970-01-01
    • 1970-01-01
    • 2021-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多