/** * Create a sparse array from a dense array * * @param arr The dense array * @return The sparse array, with zeroes removed */ public static SparseRealArray fromArray(double[] arr) { SparseRealArray sa = new SparseRealArray(arr.length); for (int i = 0; i < arr.length; i++) { if (arr[i] != 0) { sa.put(i, arr[i]); } } return sa; }
/** * Convert to a sparse real array */ public SparseRealArray toRealArray() { final SparseRealArray sparseRealArray = new SparseRealArray(n, defaultValue, 0.0); for (Map.Entry<Integer, Integer> entry : entrySet()) { sparseRealArray.put(entry.getKey(), entry.getValue()); } return sparseRealArray; }
/** * Create from a string of the form "idx=val,...,idx=val" * * @param string The string * @param n The length of the array * @param defaultValue The default value * @param sep The seperator * @return The array object * @throws SparseArrayFormatException If the string is not formatted as a * sparse array */ public static SparseRealArray fromString(String string, int n, double defaultValue, String sep) throws VectorFormatException { String[] entries = string.split(sep); final SparseRealArray SparseRealArray = new SparseRealArray(n); for (String entry : entries) { if (entry.matches("\\s*")) { continue; } String[] values = entry.split("="); if (values.length != 2) { throw new VectorFormatException("Bad sparse array value " + entry); } try { SparseRealArray.put(new Integer(values[0]), new Double(values[1])); } catch (NumberFormatException x) { throw new VectorFormatException(x); } } return SparseRealArray; }
@Override public Vector<Double> subvector(int offset, int length) { final SparseRealArray sv = new SparseRealArray(n); final ObjectIterator<Entry> iter = int2DoubleEntrySet().fastIterator(); while(iter.hasNext()) { final Int2DoubleMap.Entry e = iter.next(); if(e.getIntKey() >= offset && e.getIntKey() < offset + length) { sv.put(e.getIntKey(), e.getDoubleValue()); } } return sv; } }