I am having a problem with my function and loop and not sure why.
var a = ['1,0,1', '0,1,0', '1,1,1'];
var b = [1, 1, 1];
function myFunction() {
for (i = 0; i < a.length; i++) {
var user = a[i].split(',');
var cs = cosinesim(user, b);
document.getElementById("cs").innerHTML += String(user) + ' ' + String(cs) + '<br>';
cs = 0;
user = '';
}
}
function cosinesim(A, B) {
var dotproduct = 0;
var mA = 0;
var mB = 0;
for (i = 0; i < A.length; i++) {
dotproduct += (parseInt(A[i]) * parseInt(B[i]));
mA += (parseInt(A[i]) * parseInt(A[i]));
mB += (parseInt(B[i]) * parseInt(B[i]));
}
mA = Math.sqrt(mA);
mB = Math.sqrt(mB);
if ((mA * mB) == 0) {
var similarity = 0
} else {
var similarity = (dotproduct) / (mA * mB)
}
return similarity;
}
<p id="cs"></p>
<button onclick="myFunction()">Click</button>
I am trying to get the function to loop through the a array and print out the cosine similarity for each element in the array, however it only prints the first? If I remove the cs variable and calculations, the function prints out all the users. I am not sure why adding the cosine function within the function causes it to only run once?
Any help appreciated, thanks.
i = 0withvar i = 0in your loops