I've got the following code, I'm trying to get it to multiply array a by array b and produce array c. I've browsed several questions on here and for some reason I can't get the array to produce the correct results, I believe because it's not multiplying the right indices by one another. Any help would be greatly appreciated, as I am still trying to grasp how array multiplication works. Here is the code:
class Main
{
public static void main (String[] args)
{
int[][]a =
{
{1,2,3,4},
{5,6,7,8},
{9,10,11,12},
//print array a
};
for(int i = 0; i < a[0].length-1; i++)
{
for(int j = 0; j < a[0].length; j++)
{
System.out.print(a[i][j] + " ");
}
System.out.println();
}
int[][]b =
{
{-1,-2,-3},
{-4,-5,-6},
{-7,-8,-9},
{-10,-11,-12},
};
System.out.println();
//print array b
for(int i = 0; i < b.length; i++)
{
for(int j = 0; j < b.length-1; j++)
{
System.out.print(b[i][j] + " ");
}
System.out.println();
}
System.out.println();
int[][]c = new int[a.length][b[0].length];
if(b.length == a[0].length)
{
for(int i = 0; i < a.length; i++)
{
for (int j = 0; j < b[0].length; j++)
{
for (int k = 0; k < a[0].length; k++)
{
c[i][j] = a[i][k]*b[k][j];
}
}
}
}
else
{
System.out.println("Dimension requirements not satisfied for accurate calculation");
}
for(int i = 0; i < c.length; i++)
{
for(int j = 0; j < c.length; j++)
{
System.out.print(c[i][j] + " ");
}
System.out.println();
}
}
}
Change c[i][j] = a[i][k]*b[k][j]; to c[i][j] += a[i][k]*b[k][j];
The answer by #Jeffrey Chen is correct because in the matrix multiplication each row of the first matrix multiply by each column of second matrix
In your case row 1 of matrix a is 1, 2, 3, 4
Column 1 of matrix b is -1, -4, -7, -10
So the answer is (1*-1)+(2*-4)+(3*-7)+(4*-10)
= -1-8-21-40 = -70
Then the first row of matrix a multiply by second column of matrix b
(1*-2)+(2*-5)+(3*-8)+(4*-11)
= -2-10-24-44 = -80
And so on
So the following is correct
c[i][j] += a[i][k] * b[k][j];
Related
How can I find the total sum for each two dimensional array row? I'm completely stuck...
public static void main(String[] args) {
int [][] grid = new int [10][10];
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
grid[i][j] = (int)(Math.random()*99);
}
}
for(int i = 0; i < 10; i++) {
for(int j = 0; j < 10; j++) {
System.out.print("1.");
System.out.printf("%5d ", grid[i][j]);
}
System.out.println();
}
}
My current output is:
How can I show the total sum for each row in the end of the row and show column numbers
For the sum of a row, this should do. In a similar way within the i loop, if you need to count the column as well;
for(int i = 0; i < 10; i++) {
int jSum = 0;
for(int j = 0; j < 10; j++) {
jSum += grid[i][j];
System.out.print("1.");
System.out.printf("%5d ", grid[i][j]);
}
System.out.printf(" %5d", jSum);
System.out.println();
}
On the column numbering:
Either you just pust put a static print in the beginning (like print "1 2 3 4..."), or you put the following with the j loop:
if (i == 0) System.out.printf("%5d ", j); // only prints in first loop / row - print 1,2,3,4,5....
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 4 years ago.
I'm trying to write a code that multiplies two given matrices together and displays the results. Here is the code I have down so far:
public static void main(String[] args) {
double firstMatrix[][] = {{1, 2}, {3, 4}, {5, 6}};
double secondMatrix[][] = {{1, 2, 3}, {4, 5, 6}};
double[][] thirdMatrix = multiplyMatrix((firstMatrix), (secondMatrix));
System.out.println("The product of the matrices is ");
for (int i = 0; i < thirdMatrix.length; i++) {
for (int j = 0; j < thirdMatrix[0].length; j++) {
System.out.print(firstMatrix[i][j] + " ");
if (i == 1 && j == 2) {
System.out.print(" * ");
} else {
System.out.print(" ");
}
}
for (int j = 0; j < thirdMatrix[0].length; j++) {
System.out.print(secondMatrix[i][j] + " ");
if (i == 1 && j == 2) {
System.out.print(" = ");
} else {
System.out.print(" ");
}
}
for (int j = 0; j < thirdMatrix[0].length; j++) {
System.out.printf("%.1f", thirdMatrix[i][j]);
}
System.out.println();
}
}
public static double[][] multiplyMatrix(double[][] a, double[][] b) {
double c[][] = new double[3][3];
for (int i = 0; i < c.length; i++) {
for (int j = 0; j < b.length; j++) {
for (int k = 0; k < a.length; k++) {
c[i][j] += ((a[i][k]) * (b[k][j]));
}
}
}
return c;
}
But when I try to execute the program I receive an Array Index out of Bounds Error which shouldn't be the case since my for loops are making sure not to step out of bounds from the array. I don't understand where to change my code because it looks fine until I try to execute. Any help is really appreciated.
If 1st matrix's dimensions is mxn and the 2nd's nxp then the product's dimensions mxp. Right?
So this 2nd level of the triple loop should iterate through the 2nd dimension of the product array:
for (int j = 0; j < b.length; j++)
should be:
for (int j = 0; j < b[0].length; j++)
b[0].length is the number of columns of the matrix b.
Also the 3d level of the triple loop should be:
for (int k = 0; k < b.length; k++)
b.length is the number of rows of the matrix b which is equal to the number of columns of the matrix a.
Edit
In a generalized version you could change this:
double c[][] = new double[3][3];
to
double c[][] = new double[a.length][b[0].length];
public static void main(String[] args) {
double firstMatrix[][] = {{1, 2}, {3, 4}, {5, 6}};
double secondMatrix[][] = {{1, 2, 3}, {4, 5, 6}};
double[][] thirdMatrix = multiplyMatrix((firstMatrix), (secondMatrix));
System.out.println("The product of the matrices is ");
for (int i = 0; i < thirdMatrix.length; i++) {
for (int j = 0; j < firstMatrix[0].length; j++) {// check this one
System.out.print(firstMatrix[i][j] + " ");
if (i == 1 && j == 2) {
System.out.print(" * ");
} else {
System.out.print(" ");
}
}
for (int j = 0; j < thirdMatrix.length; j++) {
if (i <= 1) {// you need are condition to stop
System.out.print(secondMatrix[i][j] + " ");
if (i == 1 && j == 2) {
System.out.print(" = ");
} else {
System.out.print(" ");
}
}
}
for (int j = 0; j < thirdMatrix[0].length; j++) {
System.out.print(thirdMatrix[i][j]);
}
System.out.println();
}
}
public static double[][] multiplyMatrix(double[][] a, double[][] b) {
double c[][] = new double[3][3];
for (int i = 0; i < c.length; i++) {
// Change b.length to b[0].length;
for (int j = 0; j < b[0].length; j++) {
// Change a.length to a[0].length;
for (int k = 0; k < a[0].length; k++) {
c[i][j] += ((a[i][k]) * (b[k][j]));
}
}
}
return c;
}
I just wanna print my empty array by for loops.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
What is wrong?
int NYEARS = 5;
int NRATES = 3;
double[][] balancee = new double[NYEARS][NRATES];
for (int i = 0; i < NYEARS; i++) {
for (int j = 0; j < NRATES; j++) {
System.out.print(balance[NYEARS][NRATES] + " ");
System.out.println();
}
}
You should be using the loop indices to access the array elements, not the array dimensions:
for (int i = 0; i < NYEARS; i++) {
for (int j = 0; j < NRATES; j++) {
System.out.print(balance[i][j] + " ");
System.out.println();
}
}
I would prefer generally foreach when I don't need making arithmetic operations with their indices
for (double[] x : balancee) {
for (double y : x) {
System.out.print(y + " ");
}
System.out.println();
}
More importantly, I hope you get why you cannot use balance[NYEARS][NRATES].
Your solution will cause java.lang.ArrayIndexOutOfBoundsException: 5 you have also a typo balance instead you mean balancee:
So Instead you have to use balancee.length and balancee[i].length and not balance[NYEARS][NRATES], so you have to use balancee[i][j] like this :
for (int i = 0; i < balancee.length; i++) {
for (int j = 0; j < balancee[i].length; j++) {
System.out.print(balancee[i][j] + " ");
System.out.println();
}
}
Just use the built-in Arrays.deepToString()
int[][] foo = { null, {}, { 1 }, { 2, 3 } };
System.out.println(Arrays.deepToString(foo));
Output
[null, [], [1], [2, 3]]
int NYEARS = 5; //This is the size
int NRATES = 3; //This is the size
double[][] balancee = new double[NYEARS][NRATES]; //<-- balancee vs balance
for (int i = 0; i < NYEARS; i++) {
for (int j = 0; j < NRATES; j++) {
System.out.print(balance[NYEARS][NRATES] + " "); //<-- use i and j instead of size.
System.out.println();
}
}
I try to convert 1D to 2D array, but I keep getting java.lang.ArrayIndexOutOfBoundsException, and I have tried whatever I could find on the stackoverflow or internet, but I do not understand why I have this issue?
public class Arrayto2DArray {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int[] a = {0,1, 6, 83, 4, 5, 12, 7};
int[][] b = new int[4][4];
for (int i = 0; i < b.length; i++) {
for (int j = 0; j < b[i].length; j++) {
b[i][j]=0;
System.out.print(b[i][j]);
}
System.out.println();
}
System.out.println("--------------------------");
for (int i = 0; i < 4; i++) {
for (int j = 0; j < b[i].length; j++) {
try{
b[i][j] = a[i+j*4];
}catch(Exception e){
e.printStackTrace();
System.out.println(e);
}
}
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
System.out.print(b[i][j]);
}
System.out.println();
}
}
}
I kind of know why I get this error and it because of this line
b[i][j] = a[i+j*4];
but I cannot come up any formula better than this.
Consider the second for-loop
Lets say when i = 3 and j= 3
a[i+j*4] evaluates to a[15] which is out of the array
When you declare you 2-d array, you specified int[][] b = new int[4][];, meaning that the first inner for loop for (int j = 0; j < b[i].length; j++) should result in a NullPointerException since b[i].length has no predefined length. Before intering the inner for loop, you should define the size of each b[i] like b[i] = new int[somenumber]
In regards to convert the 1d loop to a 2d, you need to define the rule around spliting it into the 2-d array. Then accordingly the second for loop need modification
EDIT:You modified your code to have an int[4][4] array, which means you have 16 placeholders. Your 1-d array contain only 8 placeholders. It depends on how you want to sort the array, like it can be
b 0 1 2 3
0 0 1 6 83
1 4 5 12 7
2 0 0 0 0
3 0 0 0 0
or any other pattern
Assuming the length of 1-d array is 8 and the total index of 2-d array is 16, the following is more of a general solution:
public static void main(String[] args) {
// TODO code application logic here
int[] a = { 0, 1, 6, 83, 4, 5, 12, 7 };
int[][] b = new int[4][4];
for (int i = 0; i < b.length; i++) {
for (int j = 0; j < b[i].length; j++) {
b[i][j] = 0;
System.out.print(b[i][j] + "\t");
}
System.out.println();
}
System.out.println("--------------------------");
for (int i = 0; i < 4; i++) {
for (int j = 0; j < b[i].length; j++) {
try {
if ((j + i * 4) < a.length)
b[i][j] = a[j + i * 4];
} catch (Exception e) {
e.printStackTrace();
System.out.println(e);
}
}
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
System.out.print(b[i][j] + "\t");
}
System.out.println();
}
}
What is wrong is your 2D array is a 4*4, so that means for each index, there will be 4 elements i.e. say values. So there would be a total of 16 values, so you would need a 1D array with 16 elements for the above code to work. Right now you have only 8 values in your 1D array.
I think your code should change like this
public class Arrayto2DArray {
public static void main(String[] args) {
// TODO code application logic here
int[] a = {0,1, 6, 83, 4, 5, 12, 7};
int[][] b = new int[4][2];
for (int i = 0; i < b.length; i++) {
for (int j = 0; j < b[i].length; j++) {
b[i][j]=0;
System.out.print(b[i][j]);
}
System.out.println();
}
System.out.println("--------------------------");
for (int i = 0; i < 4; i++) {
for (int j = 0; j < b[i].length; j++) {
try{
b[i][j] = a[i+j*4];
}catch(Exception e){
e.printStackTrace();
System.out.println(e);
}
}
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 2; j++) {
System.out.print(b[i][j]+" ");
}
System.out.println();
}
}
}
Your correct formula should be like.
int[] a = {0,1, 6, 83, 4, 5, 12, 7};
int[][] b = new int[4][2];
int k=0;
for (int i = 0; i < b.length; i++) { // Column of 2D array
for (int j = 0; j < b[0].length; j++) { // Row of 2D array
b[i][j]= a[k++];
System.out.println(b[i][j]);
}
}
Edit:
For general case, If your row is fixed at 4 but column is not fixed than your 2D conversion formula should be like below.
int col = a.length / 4;
int remainder = a.length % 4;
if (remainder > 0) {
col = col + 1; // Get the correct column size.
}
int[][] b = new int[4][col];
int k = 0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < col; j++) {
if (k < a.length) {
b[i][j] = a[k];
System.out.println(b[i][j]);
}
k++;
}
}
My professor wants me to print out the matrices side by side with the "+" between the two matrices and then a "=" sign. In the end he wants us to add the matrices together.
This is the work so far.
So the result would come out as:
1 2 3 9 8 7 10 10 10
4 5 6 + 6 5 4 = 10 10 10
7 8 9 3 2 1 10 10 10
enter code here public static void main(String[] args) {
int matrix1[][] = {{1,2,3},{4,5,6},{6,7,8}};
int matrix2[][] = {{9,8,7},{6,5,4},{3,2,1}};
int result1;
int[][] result2 = new int[2][3];
for (int i = 0; i < matrix1.length; i++) {
for (int j = 0; j < matrix1[0].length; j++) {
System.out.printf(matrix1[i][j] + " ");
System.out.print("");
}
System.out.println("");
}
for (int i = 0; i < matrix2.length; i++) {
for (int j = 0; j < matrix2[0].length; j++) {
System.out.printf(matrix2[i][j] + " ");
}
System.out.println("");
}
}
My problem is, how could I print it side by side with the solutions?
Consider the two printing loops for your matrices:
for (int i = 0; i < matrix1.length; i++) {
for (int j = 0; j < matrix1[0].length; j++) {
System.out.printf(matrix1[i][j] + " ");
}
System.out.println("");
}
for (int i = 0; i < matrix2.length; i++) {
for (int j = 0; j < matrix2[0].length; j++) {
System.out.printf(matrix2[i][j] + " ");
}
System.out.println("");
}
They print matrix 1, then 2 - and so the matrices will be below each other.
If you want the matrices side by side, you need to print line 1 of every matrix, then - after a new line - line 2 of every matrix, etc. By re-arranging how the loops go through the matrices, you could have your new layout.
You unfortunately cannot print them one at a time, you need to take it row by row. This solution requires both matrix1 and matrix2 to be of equal height. But here's a template that should get you started.
for (int i = 0; i < matrix1.length; i++) {
for (int j = 0; j < matrix1[i].length; j++) {
}
if (i == matrix1/2) {
} else { //One part of if handles when "+" is needed, other one doesn't
}
for (int j = 0; j < matrix2[i].length; j++) {
}
if (i == matrix1/2) {
}
for (int j = 0; j < ???; j++) {
}
}