I'm trying to add two different sparse martices together to achieve one large matrix with all the values from the other matrix. But if they both have a value at a specific key, the values should be added together. What I can't figure out is how to reference the new matrix that is being created so I can put new the new values into it to then return.
Asked
Active
Viewed 258 times
1 Answers
0
I would suggest something like this- note that this is untested code.
public static SparseMatrix add(SparseMatrix a, SparseMatrix b) {
if (a.rows != b.rows || a.cols != b.cols) {
// They must be the same dimensions.
return null;
}
return new SparseMatrix(a.rows, a.cols).add(a).add(b);
}
private SparseMatrix add(SparseMatrix a) {
// Walk all of his.
for (Integer i : a.matrix.keySet()) {
// Do I have one of these?
if (matrix.containsKey(i)) {
// Yes! Add them together.
TreeMap<Integer, Double> mine = matrix.get(i);
TreeMap<Integer, Double> his = a.matrix.get(i);
// Walk all values in there
for (Integer j : his.keySet()) {
// Do I have one of these?
if (mine.containsKey(j)) {
// We both have this one - add them.
mine.put(j, mine.get(j) + his.get(j));
} else {
// I do not have this one.
mine.put(j, his.get(j));
}
}
} else {
// I do not have any of these - copy them all in.
matrix.put(i, new TreeMap(a.matrix.get(i)));
}
}
return this;
}

OldCurmudgeon
- 64,482
- 16
- 119
- 213