Ian
Ian

Reputation: 11

Can't compare the norm of a vector to 1 in matlab

I'm trying to find out wether a matrix is orthonormal. I begin by checking if the vectors are normal by doing

for j=1:2;
    if norm(S:,j) ~= 1;
        return; % Not normal vector
    end
end

But when norm returns 1.0000 comparing that to 1 is true and the function returns, which is not what i want. Any ideas?

Thx

Upvotes: 1

Views: 115

Answers (2)

Jonas
Jonas

Reputation: 74940

Orthonormal matrices have the property that you get the identity matrix when you multiply by the transpose. Thus, instead of doing a loop, you can simply write

%# multiply by the transpose and subtract identity
test = S*S'-eye(size(S));  %#       ' (SO formatting)

%# check whether the result is not too different from zero
isOrthonormal = all(abs(test(:)) < 1E-10); 

Upvotes: 4

ptomato
ptomato

Reputation: 57910

You can't compare floating point values for equality. You should read What Every Computer Scientist Should Know About Floating Point Arithmetic.

The solution is to check if abs(norm(s:,j) - 1) is larger than some minimum acceptable difference.

Upvotes: 6

Related Questions