Open In App

How to Create Anti-Diagonal Matrix in R

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss how to create an anti-diagonal matrix with its working example in the R programming language.

Anti-Diagonal Matrix: The anti-diagonal matrix is a square matrix where all entries are zero except for those on the anti-diagonal. That is to say, the diagonal goes from the lower-left corner to the upper-right corner. We can create a matrix in R, by using matrix() function.

Matrix function: 

Syntax: matrix(vector)

where, vector is the input vector.

We can create an antidiagonal matrix by using the following syntax:

diag(vector)[length(vector):1,]

diag(vector) will set the elements in the diagonal format. length(vector) will get the matrix size.

Example 1:

In this example, we will create 5*5 anti-diagonal matrix using the diag() function in the R programming language.

R




# create a vector with 5 elements
vector1 = c(1, 2, 3, 4, 5)
 
# display anti-diagonal matrix
print(diag(vector1)[length(vector1):1, ])


Output:

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

Example 2:

In this example, we will create 2*2 anti-diagonal matrix with the float values passed with the diag() function in the R language,

R




# create a vector with 2 elements
vector1 = c(1, 2.5)
 
# display anti-diagonal matrix
print(diag(vector1)[length(vector1):1, ])


Output:

     [,1] [,2]
[1,]    0  2.5
[2,]    1  0.0

Last Updated : 24 Dec, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads