I am currently working on trying to add and multiply two matrices together and print the results. I had done the multiplication right or at least I am certain however I cannot test the results as I do not know how to print it. Everything seemed fine and I just needed to figure out how to print results but as soon as I placed in the addition of the matrices I ran into multiple issues. Here is the blank code I was given beforehand to finish in with what was necessary to add, multiply and print the matrices:
public class Matrix {
public static void matrix_add(double[][] a, double[][] b) {
// add matrices
}
public static void matrix_multi(double[][] a, double[][] b) {
// multiply matrices
}
public static void main(String[] args) {
double ar1[][] =
{{.7,.2,.1},
{.3, .6, .1},
{.5, .1, .4}};
double ar2[][] =
{{.2, .3, .5},
{.1, .2, .1},
{.1, .3, .4}};
matrix_add(ar1, ar2);
System.out.println();
matrix_multi(ar1, ar2);
}
}
Here are my results after of which I am certain my calculations are correct for addition and multiplying the matrices:
public class operationson2Darrays {
public static void matrix_add(double[][] ar1, double[][] ar2) {
// add matrices
double[][] ar4 = new double[ar1.length][ar1[0].length];
for(int i=0;i<ar1.length;i++){
for(int j=0;j<ar1[0].length;j++){
ar4[i][j] = ar1[i][j] + ar2[i][j];
}
}
public static void matrix_multi(double[][] ar1, double[][] ar2) {
// multiply matrices
int i, j, k;
int row1 = ar1.length;
int col1 = ar1[0].length;
int row2 = ar2.length;
int col2 = ar2[0].length;
int[][] ar3 = new int[row1][col2];
for (i = 0; i < row1; i++) {
for (j = 0; j < col2; j++) {
for (k = 0; k < col1; k++) {
ar3[i][j] += ar1[i][k] * ar2[k][j];
}
}
}
}
public static void main(String[] args) {
double ar1[][] =
{{.7, .2, .1},
{.3, .6, .1},
{.5, .1, .4}};
double ar2[][] =
{{.2, .3, .5},
{.1, .2, .1},
{.1, .3, .4}};
matrix_add(ar1, ar2);
System.out.println();
matrix_multi(ar1, ar2);
}
}
}
I am currently running into lots of issues the first being that ar1 and ar2 are already being defined in scope. I understand what that means but I do not have the slightest clue how to fix it. It is also expecting tokens in this line : public static void main(String[] args) {... ?I am confused o what it is supposed to be excepting and lastly it is saying that this line is expecting a method call?: matrix_multi(ar1, ar2);
I am starting to get very confused and assuming my calculations are correct for each section if I remove the adding matrices all of a sudden all of the issues disappear. I would appreciate any help on these errors that I am receiving and how I can go about fixing this and also how I would be able to print the results of the matrices.