nbro
nbro

Reputation: 15837

Check if a matrix is an identity matrix in Matlab

I need to check if a matrix is an identity matrix. I know there's a function which check if a matrix is a diagonal matrix, that is, isdiag. I know I can do the following to check if a matrix a is an identity matrix:

isequal(a, eye(size(a, 1)))

Is there a function like isdiag tha does it directly for me?

Upvotes: 6

Views: 4377

Answers (2)

Mochan
Mochan

Reputation: 84

sum(sum(A - eye(size(A,1)) < epsilon)) == 0

Subtract by identity and check if any elements are greater than epsilon.

Upvotes: 2

Suever
Suever

Reputation: 65430

As others have said, you don't necessarily want to check for exact equality to the identity matrix. Also using eye can potentially take up an unnecessary amount of memory for sufficiently large matrices. I would recommend using diag to get around that.

isdiag(a) && all(abs(diag(a) - 1) < tolerance)

Upvotes: 2

Related Questions