public synchronized int addColumn(Vector col) {
if (isFinished)
throw new IllegalStateException(
"Cannot add columns to a MatrixBuilder that is finished");
DoubleVector column = Vectors.asDouble(col);
if (column.length() > numRows)
numRows = column.length();
// Vector instances can take on the maximum possible array size when the
// vector length isn't specified. This ruins the matrix size
// specification since the matrix shouldn't actually be that big.
// However, because this is an implementation artifact, we can't check
// for it explicitly with an exception. Therefore, put in an assert to
// indicate what is likely going on if asserts are enabled for debugging
// they symptoms.
assert column.length() != Integer.MAX_VALUE : "adding a column whose " +
"length is Integer.MAX_VALUE (was likley left unspecified in the " +
" constructor).";
// Special case for sparse Vectors, for which we already know the
// non-zero indices for the column
if (column instanceof SparseVector) {
SparseVector s = (SparseVector)column;
int[] nonZero = s.getNonZeroIndices();
nonZeroValues += nonZero.length;
System.out.println(nonZero.length);
try {
matrixDos.writeInt(nonZero.length);
for (int i : nonZero) {
double val = column.get(i);
matrixDos.writeInt(i); // write the row index
matrixDos.writeFloat((float)val);
}
} catch (IOException ioe) {
throw new IOError(ioe);
}
}
// For dense Vectors, find which values are non-zero and write only
// those
else {
int nonZero = 0;
for (int i = 0; i < column.length(); ++i) {
double d = column.get(i);
if (d != 0d)
nonZero++;
}
// Update the matrix count
nonZeroValues += nonZero;
try {
matrixDos.writeInt(nonZero);
// Write the number of non-zero values in the column
for (int i = 0; i < column.length(); ++i) {
double value = column.get(i);
if (value != 0d) {
matrixDos.writeInt(i); // write the row index
matrixDos.writeFloat((float)value);
}
}