-1
function complexity2imgloop_90(filename)
j=imread(filename); 

m=max(j(:))

x=m-1
u=-x

When I run the code above, 'x' results correctly in 255, but 'u' results in zero. No matter what I do I cant get 'u' to be negative 'x'. This only happens when working with an image and not with a matrix as an input.

Kevin Workman
  • 41,537
  • 9
  • 68
  • 107
ha554an
  • 103
  • 6

2 Answers2

2

That's because j is an image that is most likely belonging to a data type that is unsigned. This means negative values are not supported and get truncated to zero. If you desire negative number support, cast the variable to a supported type that can handle this... such as double, or perhaps int8. However, I'm assuming you'll want to use this for floating point applications, so double should be fine:

function complexity2imgloop_90(filename)
j=imread(filename); 
j = double(j); %// Change here
m=max(j(:));

x=m-1;
u=-x;

....

Minor Note

Using i and j as variables is very bad practice. Those are reserved for the complex variable i = sqrt(-1);, j = sqrt(-1);. Shadowing i or j is not recommended because it makes it more difficult to create complex numbers. You would essentially have to type in sqrt(-1) to facilitate the same behaviour. There are also other disadvantages to doing this.

Take a look at this Stack Overflow post by Shai Bagon for more details: Using i and j as variables in Matlab

Community
  • 1
  • 1
rayryeng
  • 102,964
  • 22
  • 184
  • 193
1

This is because when you read in the image, it is likely being read in as an 8-bit unsigned integer (uint8). To check this, type this

class(j)

    uint8

This means that any operations on this, will also be coerced into being an unsigned integer. Therefore when you attempt to set x to -254, it can't be done because x is an unsigned integer. You first need to convert x to either a floating point number (double or single) or a signed integer (int8)

u = -int8(x);

    -254

u = -double(x);

    -254
Suever
  • 64,497
  • 14
  • 82
  • 101