Home > Mobile >  Why this for loop results zero
Why this for loop results zero

Time:01-16

I am writing a for loop accumulation in R. Why the final result is zero?

Is there anything I can do to fix it? thanks.

mse =numeric()

for (i in 1:nrow(m1$v)){ 

   i_d = 128-i
    for (j in 1:ncol(m1$v)){
      
      j_d = 128-j
      lam_hij = m1$v[i,j]
      lam_ij = km[i_d,j_d]
      mse_ = ( lam_hij -lam_ij )^2
      if (is.na(mse_)&&isTRUE(is.na(mse_))){mse_=0}
      mse = mse   mse_
      
      
    
    }
   i = i 1
       
}
mse

I would like to see something other than zero

CodePudding user response:

Two problems:

  1. you don't show data.
  2. you don't show output

I think what is probably happening can be see in this tiny bit of console dialog:

 > 1 numeric()
 numeric(0)

So the result is not actually zero but rather an empty (length=0) numeric vector. Adding something to nothing is arguably undefined and so one might have expected NA as the result, but certainly not 1 in this instance.

You could try setting mse to 0 and re-running your code.

CodePudding user response:

Two problems:

  1. you don't show data.
  2. you don't show output

I think what is probably happening can be see in this tiny bit of console dialog:

 > 1 numeric()
 numeric(0)

So the result is not actually zero but rather an empty (length=0) numeric vector. Adding something to nothing is arguably undefined and so one might have expected NA as the result, but certainly not 1 in this instance.

  • Related