Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why (A - B) .^ 2 is not equal to (B - A) .^ 2 in MATLAB?

Tags:

matlab

Suppose I have a quantization function which quantize a 8bit gray scale image :

function mse = uni_quan(I, b)
   Q = I / 2 ^ (8 - b);
   Q = uint8(Q);
   Q = Q * 2 ^ (8 - b);
   mse = sum(sum((I - Q) .^ 2, 1), 2) / numel(I);
end

This function perform a uniform quantization on image I and convert it into a b bit image, then scale it in 0-255 range, Now I want to calculate MSE (Mean Square Error) of this process

But the result for

mse = sum(sum((I - Q) .^ 2, 1), 2) / numel(I);

and

mse = sum(sum((Q - I) .^ 2, 1), 2) / numel(I);

is different. Can anyone please point me out whats the problem?
Thanks

like image 246
frogatto Avatar asked Mar 06 '14 08:03

frogatto


People also ask

Is used to check if two elements are not equal in MATLAB?

A == B returns a logical array with elements set to logical 1 ( true ) where arrays A and B are equal; otherwise, the element is logical 0 ( false ). The test compares both real and imaginary parts of numeric arrays. eq returns logical 0 ( false ) where A or B have NaN or undefined categorical elements.

How do you find not equal to in MATLAB?

The ~ operator means logical negation, and the ~= operator means not equals.

How do you show two matrices are equal in MATLAB?

tf = isequal( A,B ) returns logical 1 ( true ) if A and B are equivalent; otherwise, it returns logical 0 ( false ).

What does double == mean in MATLAB?

Description. double is the default numeric data type (class) in MATLAB®, providing sufficient precision for most computational tasks. Numeric variables are automatically stored as 64-bit (8-byte) double-precision floating-point values. For example: x = 10; whos x.


1 Answers

The problem is the type of the matrixes. You are combining two unsigned matrixes. So if Q-I<0 then the result is 0 and it is different from I-Q.

In order to use uint8, you can compute MSE in two steps:

%Compute the absolute difference, according to the sign
difference = Q-I;
neg_idx = find(I>Q);
difference(neg_idx) = I(neg_idx)-Q(neg_idx);

%Compute the MSE
mse = sum(sum((difference) .^ 2, 1), 2) / numel(I);
like image 71
phyrox Avatar answered Nov 15 '22 06:11

phyrox