tags:

views:

147

answers:

3

I spent part of yesterday and today tracking down a bug in some Matlab code. I had thought my problem was indexing (with many structures that I didn't define and am still getting used to), but it turned out to be an overflow bug. I missed this for a very specific reason:

>> uint8(2) - uint8(1)

ans =

    1

>> uint8(2) - uint8(2)

ans =

    0

>> uint8(2) - uint8(3)

ans =

    0

I would have expected the last one to be something like -1 (or 255). In the middle of a big vector, the erroneous 0s were difficult to detect, but a 255 would have stood out easily.

Any tips on how to detect these problems easily in the future? (Ideally, I'd like to turn off the overflow checking to make it work like C.) Changing to double works, of course, but if I don't realize it's a uint8 to begin with, that doesn't help.

+7  A: 

You can start by turning on integer warnings:

intwarning('on')

This will give you a warning when integer arithmetic overflows.

Beware though, as outlined here, this does slow down integer arithmetic so only use this during debug.

dbrien
+1  A: 

See INTWARNING function to control warnings on integer operations.

http://www.mathworks.com/access/helpdesk/help/techdoc/ref/intwarning.html

yuk
+4  A: 

Another option (in addition to turning on integer overflow warnings as others have suggested) is to use the CLASS function to test the class of your data and recast it accordingly. Here's an example:

if strcmp(class(data),'uint8')  %# Check if data is a uint8
  data = double(data);          %# Convert data to a double
end

You could also use the ISA function as well:

if ~isa(data,'single')  %# Check if data is not a single
  data = single(data);  %# Convert data to a single
end
gnovice
If you do not know where your data is coming from, you should definitely do very careful input testing like this.
Jonas

related questions