You can specify multiple indexes to replace at once, so you can avoid
a for loop entirely like this:
M <- matrix(nrow = 10, ncol = 10)
M[1:4, 5: 6] <- M[5: 6, 1:4] <- m[1, 2]
M[1:4, 7] <- M[ 7, 1:4] <- m[1, 3]
M[1:4, 8:10] <- M[8:10, 1:4] <- m[1, 4]
M[5:6, 7] <- M[ 7, 5:6] <- m[2, 3]
M[5:6, 8:10] <- M[8:10, 5:6] <- m[2, 4]
M[ 7, 8:10] <- M[8:10, 7] <- m[3, 4]
M
You could also specify it directly with function 'matrix', it is
somewhat ugly though:
M <- matrix(c(
NA, NA, NA, NA, m[1,2], m[1,2], m[1,3], m[1,4],
m[1,4], m[1,4],
NA, NA, NA, NA, m[1,2], m[1,2], m[1,3], m[1,4],
m[1,4], m[1,4],
NA, NA, NA, NA, m[1,2], m[1,2], m[1,3], m[1,4],
m[1,4], m[1,4],
NA, NA, NA, NA, m[1,2], m[1,2], m[1,3], m[1,4],
m[1,4], m[1,4],
m[1,2], m[1,2], m[1,2], m[1,2], NA, NA, m[2,3], m[2,4],
m[2,4], m[2,4],
m[1,2], m[1,2], m[1,2], m[1,2], NA, NA, m[2,3], m[2,4],
m[2,4], m[2,4],
m[1,3], m[1,3], m[1,3], m[1,3], m[2,3], m[2,3], NA, m[3,4],
m[3,4], m[3,4],
m[1,4], m[1,4], m[1,4], m[1,4], m[2,4], m[2,4], m[3,4], NA,
NA, NA,
m[1,4], m[1,4], m[1,4], m[1,4], m[2,4], m[2,4], m[3,4], NA,
NA, NA,
m[1,4], m[1,4], m[1,4], m[1,4], m[2,4], m[2,4], m[3,4], NA,
NA, NA
), nrow = 10, ncol = 10, byrow = TRUE)
M
If it interests you, you could take a look at package 'Matrix', it
contains classes for specific types of matrices, including upper
triangular matrices. This package helps to improve speed of linear
algebra computations and reduce the memory size of matrices.
On Mon, Sep 5, 2022 at 10:46 PM Jinsong Zhao <jszhao at yeah.net>
wrote:>
> Hi there,
>
> I have a matrix likes:
> > m
> [,1] [,2] [,3] [,4]
> [1,] NA 1 2 3
> [2,] 1 NA 6 5
> [3,] 2 6 NA 4
> [4,] 3 5 4 NA
>
> I hope to expand it to 10 by 10 matrix, M, likes:
> > M
> [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
> [1,] NA NA NA NA 1 1 2 3 3 3
> [2,] NA NA NA NA 1 1 2 3 3 3
> [3,] NA NA NA NA 1 1 2 3 3 3
> [4,] NA NA NA NA 1 1 2 3 3 3
> [5,] 1 1 1 1 NA NA 6 5 5 5
> [6,] 1 1 1 1 NA NA 6 5 5 5
> [7,] 2 2 2 2 6 6 NA 4 4 4
> [8,] 3 3 3 3 5 5 4 NA NA NA
> [9,] 3 3 3 3 5 5 4 NA NA NA
> [10,] 3 3 3 3 5 5 4 NA NA NA
>
> I use the following code:
>
> M <- matrix(NA, 10, 10)
>
> for (i in 1:10) {
> for (j in 1:10) {
> if (i %in% 1:4 & j %in% 5:6) M[i,j] <- M[j,i] <- m[1,2]
> if (i %in% 1:4 & j == 7) M[i,j] <- M[j,i] <-m[1,3]
> if (i %in% 1:4 & j %in% 8:10) M[i,j] <- M[j,i] <-m[1,4]
> if (i %in% 5:6 & j == 7) M[i,j] <- M[j,i] <-m[2,3]
> if (i %in% 5:6 & j %in% 8:10) M[i,j] <- M[j,i] <-m[2,4]
> if (i == 7 & j %in% 8:10) M[i,j] <- M[j,i] <-m[3,4]
> }
> }
>
> Is there any convenience way to do it? Thanks!
>
> Best,
> Jinsong
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.