【发布时间】:2016-05-19 06:44:46
【问题描述】:
我有一个函数来计算每个二维矩阵行与矩阵中第一行的余弦相似度。然后将每行的余弦相似度添加到称为激活的数组列表中。
代码如下:
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(" ");
}
正如 cmets 所建议的,每当我尝试清空列表为下一行让路时,它都会在 activation.add(cosineSimilarity(probeVectorArr, contextVectorArr)); 行上显示 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1。如果我不清空它,它将正常工作,这将导致每一行都被添加到列表中。 (矩阵每行包含相同的列数)...
有人可以帮忙吗?谢谢!
【问题讨论】:
-
请将其简化为minimal reproducible example - 这里有很多不必要的代码。我怀疑这样做,你会发现问题......如果你不这样做,它会让人们更容易帮助你,并且对以后的读者更有用。
标签: java arrays arraylist multidimensional-array