In class we had to write a small code using Dot Product to find the sum of two arrays(array a and array b). I have written my code however when I run it it does not give me the answer. My professor said my loop was wrong however I do not think it is. Is the part that says i<a.length
not allowed in a for loop parameter? Because even if I set it to n it still does not give me the sum.
Here is my code:
public class arrayExample {
public static void main (String [] args) {
int[] a = {1,2,2,1};
int[] b = {1,2,2,1};
int n = a.length;
int sum = 0;
for (int i = 0; i < a.length; i++) {
sum += a[n] * b[n];
}
System.out.println(sum);
}
}
Dot product of two arrays. Specifically, If both a and b are 1-D arrays, it is inner product of vectors (without complex conjugation). If both a and b are 2-D arrays, it is matrix multiplication, but using matmul or a @ b is preferred.
Multiplication of two matrices involves dot products between rows of first matrix and columns of the second matrix. The first step is the dot product between the first row of A and the first column of B. The result of this dot product is the element of resulting matrix at position [0,0] (i.e. first row, first column).
To compute dot product of numpy nd arrays, you can use numpy. dot() function. numpy. dot() functions accepts two numpy arrays as arguments, computes their dot product and returns the result.
n
isn't the loop control variable, it's a.length
which is an out of bounds index. You probably meant
sum += a[i] * b[i];
And, although it does not matter directly, you probably meant your for
-loop to be
for (int i = 0; i < n; i++)
(I would assume that's the reason you have n
in the first place.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With