In: Computer Science
In JAVA
How can you multiply two matrices that are different lengths.
the answer should be in 3d array so [][][]
how to multiply a 3d array with a 2d array and the result is in 3d array
for example:
double[][][] nums1 = { { {0.0, 0.1, 2.0}, {3.0,4.0,5.0} },
{ {6.0,7.0,8.0}, {9.0,10.0,11.0} } }
int [][] nums2 = { {1,2,3}, {4,5,6}, {7,8,9}}
and the results should be in [][][] <-- in this dimension
int[][][] answer = { { {18, 21,24}, {54,66,78} },
{ {90, 11, 132}, {126,156,186} } }
Thanks !
import java.util.Random;
public class MatrixMultiplication {
public static double[][] multiplyMatrix(double a[][], int b[][]) {
if(a[0].length != b.length) {
throw new IllegalArgumentException("Matrix size is not allowed for multiplication");
}
double product[][] = new double[a.length][b[0].length];
// multiply both matrix
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < b[0].length; j++) {
for (int k = 0; k < b.length; k++) {
product[i][j] = product[i][j] + a[i][k] * b[k][j];
}
}
}
return product;
}
public static void printMatrix(double mat[][]) {
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat[i].length; j++) {
System.out.printf("%10.2f", mat[i][j]);
}
System.out.println();
}
}
public static void main(String[] args) {
double[][][] nums1 = { { {0.0, 0.1, 2.0}, {3.0,4.0,5.0} },
{ {6.0,7.0,8.0}, {9.0,10.0,11.0} } };
int [][] nums2 = { {1,2,3}, {4,5,6}, {7,8,9}};
double [][][] result = new double[nums1.length][][];
for(int i=0; i<nums1.length; i++) {
result[i] = multiplyMatrix(nums1[i], nums2);
printMatrix(result[i]);
System.out.println();
}
}
}
************************************************** So, I have take a 2D matrix from 3D matrix, and then created the array which contains the 2D matrices in a 3D matrix. Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.
Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.