Question

How can I calculate the variance of each cell in a matrix after a loop?

I have this so far:

  m = matrix(0,10,10)
  n = 100   
  v = 1

  rad2 <- function(matrix, repeats, v) {
  idx <- sample(length(matrix), repeats, replace = TRUE) # indices
  flip <- sample(c(-1, 1), repeats, replace = TRUE) # subtract or add
  newVal <- aggregate(v * flip ~ idx, FUN = sum) # calculate new values for indices
  matrix[newVal[[1]]] <- matrix[newVal[[1]]] + newVal[[2]] # add new values
  variance = M2/(n-1)
  return(matrix)
}

So now if I do:

rad2(m, n, v)
       [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]    0    0    0    1    0   -2    1   -2    1     0
 [2,]    1    1    0    0    0    0   -1    2    0    -2
 [3,]   -1    1   -1    1    0    0    0    1   -1    -1
 [4,]    0    0    1    0    1    0    1    1    1    -1
 [5,]    0    1    1   -2    0    0    1    0   -1    -1
 [6,]   -2   -3    0    1    1    0    0    1    0    -2
 [7,]    0    0    0    1    0    2   -1    0   -1     1
 [8,]    2    0   -1    0   -1   -1   -1    0   -1     0
 [9,]    0    0    1    1   -1    1    1    0    0     1
[10,]    0   -3    1    0   -2    0    0   -2   -1     0 

I want to calculate the variance in each cell after 100 iterations of this function. The output can be in a table or in a vector. There should be 100 values in the end. How can I do this?

edit:

If I do this instead:

n=10
for (i in 1:n) {
 tmp <- rad(m) 
 m <- tmp
 outv <- unlist(sapply(m, function(x) var(m)))
 finalv <- outv
}

I get an output in finalv. But how can I replace the variance value for each cell after each loop in the matrix instead of just writing it over and over again?

Was it helpful?

Solution

I believe this should do what you want. Just some simple for functions.

newdata=matrix(NA,100,100)
output=NULL
for (i in 1:100){newdata[i,]=as.numeric(rad2(m, n, v))}
for (n in 1:100){output[n]=mean(newdata[,n])}
matrix(output,10,10)

A more universal way

newdata=matrix(NA,length(m),length(m))
output=NULL
for (i in 1:length(m)){newdata[i,]=as.numeric(rad2(m, n, v))}
for (b in 1:length(m)){output[b]=mean(newdata[,b])}
matrix(output,dim(m)[1],dim(m)[2]) 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top