0
0
MatlabHow-ToBeginner ยท 3 min read

How to Use eye Function in MATLAB: Syntax and Examples

In MATLAB, use the eye function to create an identity matrix, which is a square matrix with ones on the main diagonal and zeros elsewhere. You can specify the size by passing one or two arguments, like eye(n) for an n-by-n matrix or eye(m,n) for an m-by-n matrix.
๐Ÿ“

Syntax

The eye function creates identity matrices. Here are the common ways to use it:

  • eye(n): Creates an n-by-n identity matrix.
  • eye(m,n): Creates an m-by-n matrix with ones on the main diagonal and zeros elsewhere.
  • eye(size(A)): Creates an identity matrix with the same size as matrix A.
matlab
I1 = eye(3);
I2 = eye(2,4);
A = [1 2; 3 4];
I3 = eye(size(A));
Output
[ 1 0 0 0 1 0 0 0 1 ] [ 1 0 0 0 0 1 0 0 ] [ 1 0 0 1 ]
๐Ÿ’ป

Example

This example shows how to create a 4-by-4 identity matrix and a 3-by-5 matrix with ones on the diagonal using eye. It also demonstrates using eye with the size of an existing matrix.

matlab
I4 = eye(4);
I5 = eye(3,5);
B = [5 6 7; 8 9 10];
I6 = eye(size(B));

I4
I5
I6
Output
[ 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 ] [ 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 ] [ 1 0 0 0 1 0 ]
โš ๏ธ

Common Pitfalls

Common mistakes when using eye include:

  • Passing non-integer or negative values as size arguments, which causes errors.
  • Confusing eye with ones or zeros, which create matrices filled entirely with ones or zeros.
  • Expecting eye to create a matrix with ones off the main diagonal (it only sets ones on the main diagonal).
matlab
wrong = eye(3.5); % Incorrect: size must be integer
correct = eye(3); % Correct

wrong2 = eye(-2); % Incorrect: size cannot be negative
correct2 = eye(2); % Correct
Output
Error using eye Size inputs must be positive integers.
๐Ÿ“Š

Quick Reference

UsageDescription
eye(n)Create n-by-n identity matrix
eye(m,n)Create m-by-n matrix with ones on main diagonal
eye(size(A))Create identity matrix same size as A
โœ…

Key Takeaways

Use eye(n) to create an n-by-n identity matrix with ones on the diagonal.
eye(m,n) creates a rectangular matrix with ones on the diagonal and zeros elsewhere.
Size arguments must be positive integers; decimals or negatives cause errors.
eye creates identity matrices, not matrices filled entirely with ones or zeros.
You can use eye(size(A)) to match the size of an existing matrix A.