When can’t MATLAB add up?
I have got a nice, shiny 64bit version of MATLAB running on my nice, shiny 64bit Linux machine and so, naturally, I wanted to be able to use 64 bit integers when the need arose. Sadly, MATLAB had other ideas. On MATLAB 2010a:
a=int64(10); b=int64(20); a+b ??? Undefined function or method 'plus' for input arguments of type 'int64'.
It doesn’t like any of the other operators either
>> a-b ??? Undefined function or method 'minus' for input arguments of type 'int64'. >> a*b ??? Undefined function or method 'mtimes' for input arguments of type 'int64'. >> a/b ??? Undefined function or method 'mrdivide' for input arguments of type 'int64'.
At first I thought that there was something wrong with my MATLAB installation but it turns out that this behaviour is expected and documented. At the time of writing, the MATLAB documentation contains the lines
Note Only the lower order integer data types support math operations. Math operations are not supported for int64 and uint64.
So, there you have it. When can’t MATLAB add up? When you ask it to add 64 bit integers!
Update: Just had an email from someone who points out that Octave (Free MATLAB Clone) can handle 64bit integers just fine
octave:1> a=int64(10); octave:2> b=int64(20); octave:3> a+b ans = 30 octave:4>
Update 2: Since I got slashdotted, people have been asking why I (or, more importantly, the user I was helping) needed 64bit integers. Well, we were using the NAG Toolbox for MATLAB which is a MATLAB interface to the NAG Fortran library. Some of its routines require integer arguments and on a 64bit machine these must be 64bit integers. We just needed to do some basic arithmetic on them before passing them to the toolbox and discovered that we couldn’t. The work-around was simple – use int32s for the arithmetic and then convert to int64 at the end so no big deal really. I was simply surprised that arithmetic wasn’t supported for int64s directly – hence this post.
Update 3: In the comments, someone pointed out that there is a package on the File Exchange that adds basic arithmetic support for 64bit integers. I’ve not tried it myself though so can’t comment on its quality.
Update 4: Someone has made me aware of an interesting discussion concerning this topic on MATLAB Central a few years back: http://www.mathworks.com/matlabcentral/newsreader/view_thread/154955
Update 5 (14th September 2010): MATLAB 2010b now has support for 64 bit integers.