In a matrix Z of elements (i,j) how to assign the value 1 when i=j? (software R)

Asked

Viewed 163 times

3

Under the following condition:

ifelse(??, 1, Z/(1+1))

What to put in place of "??" so that R understands that when i=j in the matrix Z, I want to assign the value 1?

  • 2

    By i=j you mean the index i = the index j? If it is, Daniel’s answer with diag is the most appropriate.

1 answer

5


I do not see a simple form of resolution from your question. But I propose two forms of resolution:

Assign the desired diagonal value directly.

a <- matrix(rep(0,100), nrow = 10)
diag(a) <- 1

Analyze position to assign value.

a <- matrix(rep(0,100), nrow = 10)
for(i in 1:dim(a)[1]){
  for(j in 1:dim(a)[2]){
    if(i == j){
      a[i,j] <- 1
    }
  }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.