我有一个函数来计算每个2D矩阵行与矩阵中第一行的余弦相似度。然后将每行的余弦相似度添加到称为激活的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(" ");
}
根据评论建议,每当我尝试清空列表以便为下一行腾出时,它就会在Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
行显示activation.add(cosineSimilarity(probeVectorArr, contextVectorArr));
。如果我不清空它将会正常工作,这将导致每一行都被添加到列表中。 (矩阵包含每行相同的列数)...
任何人都可以提供帮助?谢谢!
答案 0 :(得分:0)
使用空列表开始每次迭代,您的contextVectorList
以及派生的contextVectorArr
包含恰好一行的行:
contextVectorList.add(RoundTo2Decimals(contextVector[i][j]));
因此,索引1
确实超出了范围。