Replace matrix value (R)

Asked

Viewed 597 times

1

I need to replace the value that appears on the main diagonal of my matrix with another, how to proceed?

  • A single main diagonal value? Take a look at the function documentation diag. It would be nice to present the structure of your data for reproduction.

  • That’s right, Rafael. It’s just that I did an operation in the matrix, but this operation isn’t diagonal. Then I want to replace by 1 (which was the previous diagonal value, before the operation).

  • Would any replace or ifelse command work?

  • saves the value of the diagonal on an object, performs the operation and then replaces it. my idea is something like: valor <- diag(M) --> realizar a operação --> diag(M) <- valor

  • I don’t understand your idea Rafael. Could you explain me better?

  • 1

    you have your matrix M, stores diagonal values in an object valor <- diag(M), then you carry out the necessary operation in the matrix. As you said yourself, the diagonal values will change, then you return with the original values diag(M) <- valor

  • And how do I enter this value in the matrix? This I haven’t been able to understand yet

  • 1

    Then the command diag(M) <- valor will insert the value in the matrix. I will put as response some commands to exemplify

  • Rafael, it worked. Thank you very much!

  • I hadn’t re-ordered the matrix, so I hadn’t seen any changes. Thanks anyway!

  • @Letdc this question you have already asked on another topic. https://answall.com/questions/213452/em-uma-matriz-z-de-elementos-i-j-como-atribuir-o-valor-1-quando-i-j-software

Show 6 more comments

1 answer

2


M <- matrix(rpois(25, lambda = 4), ncol = 5)
M
 [,1] [,2] [,3] [,4] [,5]
[1,]    4    3    4    3    6
[2,]    3    2    6    1    6
[3,]    3    4    6    4    1
[4,]    9    3    3    4    4
[5,]    3    5    6    3    8

valor <- diag(M)
valor
[1] 4 2 6 4 8

M <- (M**M)*10
M
           [,1]  [,2]   [,3] [,4]      [,5]
[1,]       2560   270   2560  270    466560
[2,]        270    40 466560   10    466560
[3,]        270  2560 466560 2560        10
[4,] 3874204890   270    270 2560      2560
[5,]        270 31250 466560  270 167772160

diag(M) <- valor
M
           [,1]  [,2]   [,3] [,4]   [,5]
[1,]          4   270   2560  270 466560
[2,]        270     2 466560   10 466560
[3,]        270  2560      6 2560     10
[4,] 3874204890   270    270    4   2560
[5,]        270 31250 466560  270      8

Browser other questions tagged

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