1

I have a matrix that has 223 rows and 11 columns.I want to split this matrix into packets(each packet will have 10 rows from the matrix) so at the end I should have 22 packets (I will dismiss the last 3 rows). After I have the packets I want to perform a cross validation algorithm on my packets and I was thinking to put all my packets in a HaskMap that will have as key one packet and value the rest of them. So it would look like this

key = pack1, value = pack2,...,pack22
key = pack2, values = pack1, pack3,...pack22
.............................................
key = pack22, values = pack1,...,pack21

Before creating the map I have problems in spliting the matrix into packets Here is my code:

        int k = 0;
        ArrayList<ArrayList<double[]>> allPacks = new ArrayList<ArrayList<double[]>>();
        ArrayList<double[]> batch = new ArrayList<double[]>();
        for (int i=0;i<matrix.length;i+=10) {
            System.out.println(i);
            batch.add(matrix[i]);
            k++;
            if (k % 10 == 0) {
                allPacks.add(batch);
                batch.clear();
            }
        }

If I print the size of allPacks is 2. I don't get it.Any help?

GeR
  • 135
  • 1
  • 7
  • Could you add all relevant code (minimal working example) -- what is `matrix`, for example? – Mick Mnemonic May 01 '15 at 12:20
  • I said `matrix` has `223 rows` and `11 columns`. I hardcoded it so it would be aburde to paste in here 223 line of code. Basically it has `double` values – GeR May 01 '15 at 12:23

1 Answers1

2

Your main problem is that you are adding the same batch every time.

This should fix it:

    ArrayList<ArrayList<double[]>> allPacks = new ArrayList<ArrayList<double[]>>();
    for (int i = 0; i < matrix.length - 10; i += 10) {
        System.out.println(i);
        ArrayList<double[]> batch = new ArrayList<double[]>();
        for (int j = 0; j < 10; j++) {
            batch.add(matrix[i + j]);
        }
        allPacks.add(batch);
    }
OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
  • I get `ArrayIndexOutOfBoundException` – GeR May 01 '15 at 12:37
  • @Georgiana - Sorry - edited - now using `i < matrix.length - 10`. You could also use `for (int j = 0; j < 10 && i + j < matrix.length; j++) {` but that would make your last batch small. – OldCurmudgeon May 01 '15 at 12:40
  • Thanks, now it works! Any idea on how I could create that `HashMap` about I was talking at the begining? – GeR May 01 '15 at 12:42
  • @Flash is that a solution on creating the HashMap? – GeR May 01 '15 at 12:45
  • @Georgiana - You could make `allPacks` a `Map` and use `allPacks.put(batch.get(0),batch)` or something like that. – OldCurmudgeon May 01 '15 at 13:07
  • Using an array (`double[]`) as the key in the map [will not work](http://stackoverflow.com/questions/16839182/can-a-java-array-be-used-as-a-hashmap-key). Perhaps you could use a running sequence number as the key? – Mick Mnemonic May 01 '15 at 13:27