0

I need to add one half of my matrix to the other half across the diagonal. In my matrix (shown below), I need the "1" in 63,25 to be added to the "2" in 25,63, and so on for all values in the matrix.

Then I need a way to clear out half of the matrix, either above or below the diagonal.

I tried:

sum(diag(lakes_matrix)) 

but this did not work.

 25 63 1567 40 50 60 70 80 25 0 2 0 0 0 0 0 0 63 1 0 0 0 0 0 0 0 1567 0 1 0 0 0 0 0 0 40 0 0 1 0 0 0 0 0 50 0 0 0 2 0 0 0 0 60 0 0 0 0 0 0 0 0 70 0 0 0 0 0 1 0 0 80 0 0 0 0 0 0 0 0 
0

1 Answer 1

3
m <- matrix(1:9, nrow = 3) m [,1] [,2] [,3] [1,] 1 4 7 [2,] 2 5 8 [3,] 3 6 9 
n <- m + t(m) # add transpose to original n [,1] [,2] [,3] [1,] 2 6 10 [2,] 6 10 14 [3,] 10 14 18 
n * upper.tri(n) # clear out the lower diagonal 
 [,1] [,2] [,3] [1,] 0 6 10 [2,] 0 0 14 [3,] 0 0 0 

So you can make a function

my_func <- function(m) { # do some assertions: m is matrix, square and numeric etc (m + t(m)) * upper.tri(m) } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.