Question

Thanks to some great help in this answer I wrote a some code that is supposed to

  1. select a random cell in the matrix mat rnum
  2. Change the cell from zero to one or vice versa
  3. make the opposite change in the corresponding cell in the opposite triangle
  4. check condition 2 to see if the new matrix with the change is lower than the original matrix
  5. return the new matrix if condition is lower, if not return original martix
  6. repeat this with a new rnum each time until the overall condition1 is met

Where mat is:

mat <- matrix(rep(0, 100), nrow = 10)
mat[lower.tri(mat, diag = TRUE)] <- 1

while( condition1 > threshold) {

rnum <- sample(1:100, 1)
if(mat[rnum] > 0){
mat2 <- mat
mat2[rnum] <- 0
mat2[length(mat2) - rnum + 1] <- 1
return(mat2)
}else{
mat2 <- mat
mat2[rnum] <- 1
mat2[length(mat2) - rnum + 1] <- 0
return(mat2)
        }   
if(condition2(mat2) < 
   condition2(mat) ) {
mat <- mat2
}else{
mat
    }
}

the condition is not key here, for sake of argument condition1 & condition2 it could be the sum of the top row i.e. sum(mat[,1]) but I get the following error:

Error: no function to return from, jumping to top level

Could someone point me to my flaw?

Was it helpful?

Solution

One of the errors I found is that on your else block, mat2 is not defined. Because of that if random numbers take me to the else block in first iteration, the code error :

Error in mat2[rnum] <- 1 : object 'mat2' not found

The error that you have mentioned is occurring because the while loop is only a statement, there is no enclosing function in your code and hence the return(mat2) statement is incorrect. You can only use return if you want to return from a function. In your case there is no function and hence the error

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top