Skip to content
Related Articles

Related Articles

Construct a Diagonal Matrix in R Programming – diag() Function
  • Last Updated : 03 Jun, 2020

diag() function in R Language is used to construct a diagonal matrix.

Syntax: diag(x, nrow, ncol)

Parameters:
x: value present as the diagnoal elements.
nrow, ncol: number of rows and columns in which elements are represented.

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


Output:

     [, 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

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

     [, 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
My Personal Notes arrow_drop_up
Recommended Articles
Page :