creating n by n matrix with 1 in main diagonal and common value say 0.012 in the other cells using R software

北城余情 提交于 2020-08-10 18:50:23

问题


I want to create an n by n matrix that looks like this if n=4 and my alpha=0.01 then my matrix using R software

I would appreciate if i can get something using this working to reproduce the matrix above

     n=5
    i=0
    alpha=0.01
    R=matrix(nrow=n,ncol=n)
    while(i<n){
      R[i+1,]=alpha
      i=i+1}
    R

but with the above code, all my diagonals are 0.01. What am i doing wrong?


回答1:


You can create a matrix of 0.01's and set the diagonal to 1:

 n <- 5
 alpha <- 0.01
 diagonal_val <- 1
 m <- matrix(alpha, n, n)
 diag(m) <- diagonal_val

Update The OP requested to elaborate on the brute-force approach to create matrices:

n <- 5
alpha <- 0.01
R <- matrix(NA, n,n)
for (i in 1:n){
  for (j in 1:n){
    if (i==j){
      R[i,j] <- 1.
    } else {
      R[i,j] <- alpha
    }
  }
}

Output

> m
     [,1] [,2] [,3] [,4] [,5]
[1,] 1.00 0.01 0.01 0.01 0.01
[2,] 0.01 1.00 0.01 0.01 0.01
[3,] 0.01 0.01 1.00 0.01 0.01
[4,] 0.01 0.01 0.01 1.00 0.01
[5,] 0.01 0.01 0.01 0.01 1.00


来源:https://stackoverflow.com/questions/63020355/creating-n-by-n-matrix-with-1-in-main-diagonal-and-common-value-say-0-012-in-the

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!