Initializing Eigen matrix to zeros, the wrong way.

Alec Jacobson

April 30, 2013

weblog/

I recently found a pretty silly bug in the way I was initializing an Eigen matrix to be all zeros. Say, my matrix was A, then I wrote this (admittedly in haste) to resize to an m by n matrix of zeros using:
A.resize(m,n);
A *= 0;
This worked most of the time. As should be expected if A is initialized to numbers. But unfortunately, the resize doesn't initialize the values to anything, and some of the random leftovers in memory will be, when interpreted as floats, not-a-numbers (NaNs). Thus when I thought I was zeroing them out I was keeping the NaNs: 0*NaN = NaN. Luckily, this is also why NaN-related bugs are so easy to trace. Of course the correct thing to do is explicit set each value to zero. Eigen even has a dedicated function:
A.setZero(m,n);