Actually, what the early code was doing was it picked the first non-zero element of every row, find it's index in A and then append the index in IA. This is done according to the wiki page of Sparse Matrix. Yesterday, I found a new approach that would not require finding of elements first but will directly append the index of first non-zero element of every row.

The implementation is failing because it diden't know what to do with rows that have no non-zero elements. The fix is straightforward fo r this I think.