Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dot product with arrays

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);
    }
}
like image 681
Sophia Ali Avatar asked Sep 12 '13 23:09

Sophia Ali


People also ask

What is the dot product of an array?

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.

Can you dot product a matrix?

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).

How do you get the dot product of two numpy arrays?

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.


1 Answers

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.)

like image 123
arshajii Avatar answered Sep 18 '22 01:09

arshajii