I want to find the minimum and the maximum from a matrix from each column. My function
public static void findMinMax(double[][] matrix) {
ArrayList<Double> column = new ArrayList<Double>();
ArrayList<Double> minmax = new ArrayList<Double>();
ArrayList<ArrayList<Double>> minMaxValues = new ArrayList<ArrayList<Double>>();
for (int j=0;j<matrix[1].length;j++) {
column.clear();
minmax.clear();
for (int i=0;i<matrix.length;i++) {
column.add(matrix[i][j]);
}
double max = Collections.max(column);
double min = Collections.min(column);
minmax.add(min);
minmax.add(max);
try {
System.out.println("adding to final minmax " + j);
minMaxValues.add(minmax);
System.out.println(minMaxValues);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
System.out.println(minMaxValues);
}
The problem is that at the last iteration it adds to minMaxValues
only the last minmax
ArrayList.
Here is an example of the output
adding to final minmax 0
[[-3.5, 4.5]]
adding to final minmax 1
[[-3.5, 4.5], [-3.5, 4.5]]
adding to final minmax 2
[[-3.5, 4.5], [-3.5, 4.5], [-3.5, 4.5]]
adding to final minmax 3
[[-3.5, 4.2], [-3.5, 4.2], [-3.5, 4.2], [-3.5, 4.2]]
adding to final minmax 4
[[-3.5, 4.2], [-3.5, 4.2], [-3.5, 4.2], [-3.5, 4.2], [-3.5, 4.2]]
adding to final minmax 5
[[-3.5, 4.2], [-3.5, 4.2], [-3.5, 4.2], [-3.5, 4.2], [-3.5, 4.2], [-3.5, 4.2]]
adding to final minmax 6
[[-3.5, 4.2], [-3.5, 4.2], [-3.5, 4.2], [-3.5, 4.2], [-3.5, 4.2], [-3.5, 4.2], [-3.5, 4.2]]
adding to final minmax 7
[[-3.9, 4.2], [-3.9, 4.2], [-3.9, 4.2], [-3.9, 4.2], [-3.9, 4.2], [-3.9, 4.2], [-3.9, 4.2], [-3.9, 4.2]]
adding to final minmax 8
[[-3.9, 4.2], [-3.9, 4.2], [-3.9, 4.2], [-3.9, 4.2], [-3.9, 4.2], [-3.9, 4.2], [-3.9, 4.2], [-3.9, 4.2], [-3.9, 4.2]]
adding to final minmax 9
[[-3.9, 4.2], [-3.9, 4.2], [-3.9, 4.2], [-3.9, 4.2], [-3.9, 4.2], [-3.9, 4.2], [-3.9, 4.2], [-3.9, 4.2], [-3.9, 4.2], [-3.9, 4.2]]
adding to final minmax 10
[[-3.9, 4.5], [-3.9, 4.5], [-3.9, 4.5], [-3.9, 4.5], [-3.9, 4.5], [-3.9, 4.5], [-3.9, 4.5], [-3.9, 4.5], [-3.9, 4.5], [-3.9, 4.5], [-3.9, 4.5]]
As you can see it works fine until minmax 10 where I don't understand what happens. Can anyone help me?
asked Apr 28, 2015 at 4:43
1 Answer 1
You need to reinitialize ArrayList<Double> minmax
for every iteration. Otherwise your result list will just contain 11 references to the same list, containing the last values that you put in.
You need to move
ArrayList<Double> minmax = new ArrayList<Double>();
inside your loop.
answered Apr 28, 2015 at 4:54
2 Comments
dres
Thanks, that was the problem. I'm still trying to understand why :)
Robby Cornelissen
Try to wrap your head around the fact that your
minMaxValues
just contains 11 references to the same minmax
list. That list is in the state that you leave after the last iteration, hence containing the values of the last iteration.lang-java
matrix[1].length
evaluate to? 11?minmax
list. The contents of the list itself are overwritten in every iteration.