3
votes

I want to create a minimum value which compares the lower and upper triangular matrix of a matrix. For example

 A = matrix( c(2, 4, 3, 1, 5, 7,4,2,4), nrow=3, ncol=3,byrow = TRUE)  
 B= matrix(c(0,1,3,1,0,2,3,2,0), nrow=3, ncol=3,byrow= TRUE) 

I would like to create a matrix like this with diagonal elements set to 0 and the rest to be minimum of upper and lower elements. For example (A(1,2), A(2,1)) which is min(4,1) =1. This results in matrix B. Can anyone suggest how to achieve this manipulation?

2

2 Answers

3
votes

I think you want to use pmin:

A <- matrix( c(2, 4, 3, 1, 5, 7,4,2,4), nrow=3, ncol=3,byrow = TRUE)  
diag(A) <- 0
output <- pmin(A, t(A))
output
 [,1] [,2] [,3]
[1,]    0    1    3
[2,]    1    0    2
[3,]    3    2    0
2
votes

Do it like this:

B = ifelse(A<t(A),A,t(A))
diag(B) = 0

> B
     [,1] [,2] [,3]
[1,]    0    1    3
[2,]    1    0    2
[3,]    3    2    0

First get the minimum between A and transpose A, then set the diagonal elements to 0.