當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


R語言 diag()用法及代碼示例


R語言中的diag()函數用於構造對角矩陣。

用法: diag(x, nrow, ncol)

參數:
x:值作為診斷元素出現。
nrow, ncol:表示元素的行數和列數。

範例1:


# R program to illustrate
# diag function
  
# Calling the diag() function with 
# some number which will act as
# rows as well as columns number
diag(3)
diag(5)

輸出:

     [, 1] [, 2] [, 3]
[1, ]    1    0    0
[2, ]    0    1    0
[3, ]    0    0    1

     [, 1] [, 2] [, 3] [, 4] [, 5]
[1, ]    1    0    0    0    0
[2, ]    0    1    0    0    0
[3, ]    0    0    1    0    0
[4, ]    0    0    0    1    0
[5, ]    0    0    0    0    1

範例2:


# R program to illustrate
# diag function
  
# Calling the diag() function
diag(5, 2, 3)
diag(10, 3, 3)

輸出:

     [, 1] [, 2] [, 3]
[1, ]    5    0    0
[2, ]    0    5    0

     [, 1] [, 2] [, 3]
[1, ]   10    0    0
[2, ]    0   10    0
[3, ]    0    0   10

相關用法


注:本文由純淨天空篩選整理自Kanchan_Ray大神的英文原創作品 Construct a Diagonal Matrix in R Programming – diag() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。