2017-04-07 21 views
0

我有一個矩陣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 
    } 
    } 
} 
+1

什麼是ABX?請爲我們提供一個最小**可重現**示例,即我們可以在R中運行而無需猜測上下文和數據。另請參見http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example –

+0

是的,您需要提供一個最小可重現的示例。只需使用隨機播種整數聲明a,b,X. – smci

+1

另外,它們的維數n有多大,以及我們對它們的值範圍知道些什麼?如果X不是太大,可以複製並設置'diag(X2)< - -Inf',現在最大值不能出現在主對角線上。如果它很大,你可以使用稀疏矩陣表示法。 – smci

回答

0

謝謝大家對你的貢獻。我想出瞭如何解決這個問題。如下所示;

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) 
相關問題