Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

populating a matrix by rows

Tags:

r

matrix

I would like to populate a matrix by row based on a function which gives the seq() of a number seq(1) 1 seq(2) 1 2 and so on

    matrixinp = matrix(data=NA, nrow=6, ncol=6) 

> print(matrixinp) 
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]   NA   NA   NA   NA   NA   NA
[2,]   NA   NA   NA   NA   NA   NA
[3,]   NA   NA   NA   NA   NA   NA
[4,]   NA   NA   NA   NA   NA   NA
[5,]   NA   NA   NA   NA   NA   NA
[6,]   NA   NA   NA   NA   NA   NA
    
    # display matrix 
    print(matrixinp) 
    
    # fill the elements with some  
    # 90 in a matrix 
    for (i in 1:6){
      aaa<-seq(i)
      print(aaa)
      for(j in 1:6){ 
        matrixinp[j,] = aaa
      } 
    }

This gave me this:

> print(matrixinp)
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    2    3    1    2    3
[2,]    1    2    3    1    2    3
[3,]    1    2    3    1    2    3
[4,]    1    2    3    1    2    3
[5,]    1    2    3    1    2    3
[6,]    1    2    3    1    2    3

but I would like this:

> print(matrixinp)
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    NA   NA   NA   NA   NA
[2,]    1    2    NA   NA   NA   NA
[3,]    1    2    3    NA   NA   NA
[4,]    1    2    3    4    NA   NA
[5,]    1    2    3    4    5    NA
[6,]    1    2    3    4    5    6
like image 873
Paolo Lorenzini Avatar asked Jul 10 '26 16:07

Paolo Lorenzini


1 Answers

I bet a one-liner can solve this, R is a vectorized language.

matrixinp <- matrix(data=NA, nrow=6, ncol=6)
matrixinp[lower.tri(matrixinp, diag = TRUE)] <- rep(1:6, 6:1)

matrixinp
#>      [,1] [,2] [,3] [,4] [,5] [,6]
#> [1,]    1   NA   NA   NA   NA   NA
#> [2,]    1    2   NA   NA   NA   NA
#> [3,]    1    2    3   NA   NA   NA
#> [4,]    1    2    3    4   NA   NA
#> [5,]    1    2    3    4    5   NA
#> [6,]    1    2    3    4    5    6

Created on 2024-09-17 with reprex v2.1.0

Wait, I won the bet.
The trick is to know that R's matrices are column major, therefore with the index matrix lower.tri the values will go the right places.

like image 174
Rui Barradas Avatar answered Jul 13 '26 10:07

Rui Barradas