0

I have a matrix X with its maximum value along the main diagonal. Firstly, want to sample one row i, and pick the maximum value along row i excluding the main diagonal value i.e max != X[i,i].

The code below usually produces results but often has an error: 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
    }
  }
}
smci
  • 32,567
  • 20
  • 113
  • 146
Gilbert
  • 3
  • 4
  • 1
    What is ABX? Please provide us with a minimal **reproducible** example, i.e. something we can run in R without having to guess the context and the data. See also http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Joris Meys Apr 07 '17 at 10:17
  • Yes, you need to supply a minimal reproducible example. Just declare a,b,X using random-seeded integers. – smci Apr 07 '17 at 11:02
  • 1
    Also, how large is their dimension n, and what do we know about their range of values? If X is not too large, you can make a copy and set `diag(X2) <- -Inf`, now the maximum cannot occur on the main diagonal. And if it is large, you could maybe use sparse-matrix representation. – smci Apr 07 '17 at 11:04
  • Thanks @smci .. I'm using 10*10 matrix . – Gilbert Apr 07 '17 at 11:12
  • Ok but you need to urgently supply a minimal reproducible example with data. Otherwise this is likely to get downvoted and closed. – smci Apr 07 '17 at 19:33

1 Answers1

0

Thanks everyone for your contribution. I figured out how to go about the problem. The is as below;

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)
Gilbert
  • 3
  • 4