RobMcC
RobMcC

Reputation: 412

Produce a triangular matrix of integers increasing by 1

I am trying to produce a matrix of variable dimensions of the form below (i.e. integers increasing by 1 at a time, with a lower triangle of NAs)

NA  1  2  3  4 
NA NA  5  6  7
NA NA NA  8  9
NA NA NA NA  10
NA NA NA NA  11

I have used the below code

sample_vector <- c(1:(total_nodes^2))
sample_matrix <- matrix(sample_vector, nrow=total_nodes, byrow=FALSE)
sample_matrix[lower.tri(sample_matrix, diag = TRUE)] <- NA

However the matrix I get with this method is of the form:

NA  2  3  4  5
NA NA  8  9  10
NA NA NA  14 15
NA NA NA NA  20
NA NA NA NA  25

Upvotes: 1

Views: 49

Answers (2)

IRTFM
IRTFM

Reputation: 263332

I'm using the diag function to construct a matrix and upper.tri to turn it into a "target" aas well as a logical indexing tool:

 upr5 <- upper.tri(diag(5))
 upr5
 upr5[upr5] <- 1:sum(upr5)
 upr5[upr5==0] <- NA   # would otherwise have been zeroes
 upr5
     [,1] [,2] [,3] [,4] [,5]
[1,]   NA    1    2    4    7
[2,]   NA   NA    3    5    8
[3,]   NA   NA   NA    6    9
[4,]   NA   NA   NA   NA   10
[5,]   NA   NA   NA   NA   NA

Upvotes: 1

MrFlick
MrFlick

Reputation: 206197

How about this

total_nodes <- 5
sample_matrix <- matrix(NA, nrow=total_nodes, ncol=total_nodes)
sample_matrix[lower.tri(sample_matrix)]<-1:sum(lower.tri(sample_matrix))
sample_matrix <- t(sample_matrix)
sample_matrix
#     [,1] [,2] [,3] [,4] [,5]
# [1,]   NA    1    2    3    4
# [2,]   NA   NA    5    6    7
# [3,]   NA   NA   NA    8    9
# [4,]   NA   NA   NA   NA   10
# [5,]   NA   NA   NA   NA   NA

Upvotes: 4

Related Questions