How to Create Anti-Diagonal Matrix in R
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
vector1 = c (1, 2, 3, 4, 5)
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
vector1 = c (1, 2.5)
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
Share your thoughts in the comments
Please Login to comment...