I want to multiply two arrays in java. Is there any function for that or how can I do that?
int[] a = new int[]{1,2,3};
int[] b = new int[]{1,2,3};
int[] c = a * b; ?
I researched a bit but could not find.
CodePudding user response:
There is no built in functionality for this. However, it can be done manually, using streams, libraries, or a number of other approaches.
The easiest and most straightforward approach is to use a for loop.
static int[] arrayMultiply(int[] a, int[] b) {
int newLength = Math.min(a.length, b.length);
int[] c = new int[newLength];
for (int index = 0; index < newLength; index ) {
c[index] = a[index] * b[index];
}
return c;
}
CodePudding user response:
In mathematics matrix multiplication, the number of columns in the first matrix must be equal to the number of rows in the second matrix. Then the row elements of first matrix multiply by column elements in second matrix to get resulting matrix. Although this is much different, can get results of this is one-dimensional array like this.
[1 2 3] * [1 2 3] = [1x1 1x2 1x3] = [1 2 3]
int a[] = {1,2,3};
int b[] = {1,2,3};
int c[] = new int[a.length];
for(int i=0; i<a.length; i ){
c[i] = a[0]*b[i];
System.out.print(c[i] " ");
}
If you are going to have mathematical matrix multiplications, this will be the correct way.