2016-05-19 4 views
0

私は、各2D行列行と行列の最初の行とのコサイン類似度を計算する関数を持っています。各行のコサイン類似度は、起動と呼ばれるarraylistに追加されます。コメントは、私は次の行のための方法を作るために、リストを空にしようとした時はいつでも、それはラインactivation.add(cosineSimilarity(probeVectorArr, contextVectorArr));Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1表示されます、示唆したようにループ内でarraylistを空にしようとすると配列が外に出る

List <Double> probeVectorList = new ArrayList <Double>(); 
Double[] probeVectorArr = new Double[countMatrix2[0].length]; 
List <Double> contextVectorList = new ArrayList <Double>(); 
Double[] contextVectorArr = new Double[countMatrix2[0].length]; 
List <Double> activation = new ArrayList <Double>(); 

//display matrix 
for (int i = 0; i < countMatrix2.length; i++) { 

    System.out.print(arrKeyWords[i]+" "); //print keywords 

    for (int j = 0; j < countMatrix2[0].length; j++) { 

     if (i==0) 
     { 
      probeVectorList.add(RoundTo2Decimals(contextVector[i][j])); //set the first row as probe vector 
      probeVectorArr = probeVectorList.toArray(new Double[0]); 
     } 

      System.out.print(RoundTo2Decimals(contextVector[i][j])+", "); //print the entire matrix with rounded decimals 

      //compute activation 
      contextVectorList.add(RoundTo2Decimals(contextVector[i][j])); //here, in every iteration, the rows will be added into the list 
      contextVectorArr = contextVectorList.toArray(new Double[0]); //convert list to array 

      activation.add(cosineSimilarity(probeVectorArr, contextVectorArr)); //compute cosine similarity between the first row(static) and the subsequent row (cosineSimilarity function will take in 2 vector as input) 

      } 

      //array out of bounds exception appears when attempting to calculate cosine similarity whenever I empty the array/list to make way for new rows 
      Arrays.fill(contextVectorArr, null); //empty array to make way for new rows 
      contextVectorList.clear(); //empty list to make way for new rows 

      System.out.println(" "); 
     } 

:ここ

はコードです。私がそれを空にしないと、すべての行がリストに追加される結果になります。 (行列にはすべての行に同じ列の列が含まれていません)...

誰でも手助けできますか?ありがとう!

+2

これを[mcve]に減らしてください。ここにはたくさんの不要なコードがあります。私はそうすることで、あなたが問題を見つけることができると思っています。もしそうでないと、人々があなたを助けやすくなり、後の読者にとってより有用になります。 –

答えて

0

空のリストで各反復を開始し、あなたのcontextVectorList、ひいては派生contextVectorArr、正確に一つの要素ラインによって追加が含まれています。

contextVectorList.add(RoundTo2Decimals(contextVector[i][j])); 

したがって、インデックス1が範囲外、確かに、あります。

関連する問題