Creating an identity matrix in Matlab
The eye()
function in MATLAB generates an identity matrix of any specified size.
eye(n)
Here, n
sets both the number of rows and columns in the matrix.
For example, typing eye(2) creates a 2-by-2 identity matrix:
>> eye(2)
ans =
1 0
0 1
Likewise, typing eye(3) produces a 3-by-3 identity matrix:
>> eye(3)
ans =
1 0 0
0 1 0
0 0 1
Note: In an identity matrix, only the main diagonal contains ones, while all other elements are zero.
The eye()
function can also accept two parameters:
eye(x, y)
In this format, x
specifies the number of rows and y
the number of columns.
For instance, typing eye(3,5) creates a 3-by-5 matrix with ones along the main diagonal:
>> eye(3,5)
ans =
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0