public class Homework2 {
public static void main(String[] args){
int num1 = (int) (Math.random()*(10-3+1)+3);
int num2 = (int) (Math.random()*(10-3+1)+3);
double[][] doubMatrix1 = new double[num1][num2];
double[][] doubMatrix2 = new double[num1][num2];
double[][] doubMatrix3 = new double[num1][num2];
doubMatrix1 = getdoubMatrix(num1,num2);
doubMatrix2 = getdoubMatrix(num1,num2);
doubMatrix3 = addMatrices(doubMatrix1, doubMatrix2, num1, num2);
printDoubMatrix("First matrix", doubMatrix1);
printDoubMatrix("Second matrix", doubMatrix2);
printDoubMatrix("Result of adding", doubMatrix3);
doubMatrix2 =transposeMatrix(num1,num2);
}
public static double[][] getdoubMatrix(int num1,int num2){
double[][] tempArray = new double[num1][num2];
for(int i = 0;i < tempArray.length;i++)
for(int j = 0;j < tempArray[i].length;j++)
{
tempArray[i][j] = Math.random() * (100);
}
return tempArray;
}
public static double[][] addMatrices(double[][] doubMatrix1, double[][] doubMatrix2,int num1,int num2)
{
double[][] tempArray = null;
if(doubMatrix1.length == doubMatrix2.length)
if(doubMatrix1[0].length == doubMatrix2[0].length)
{
tempArray = new double[num1][num2];
for(int i = 0; i< doubMatrix1.length;i++)
for(int j = 0; j< doubMatrix1[i].length;j++ )
{
tempArray[i][j] = doubMatrix1[i][j] + doubMatrix2[i][j];
}
}
else
{
return tempArray = new double[0][0];
}
return tempArray;
}
public static void printDoubMatrix(String text,double[][] doubMatrix1){
System.out.println(text);
for(int i = 0; i< doubMatrix1.length;i++)
for(int j = 0; j< doubMatrix1[i].length;j++ )
System.out.printf("%f\n", doubMatrix1[i][j]);
}
public static double[][] transposeMatrix(int num1, int num2){
double[][] tempArray = new double[num2][num1];
for(int i = 0;i < tempArray.length;i++)
for(int j = 0;j < tempArray[i].length;j++)
{
tempArray[i][j] = tempArray[j][i];
System.out.printf("%f\n", tempArray[i][j]);
}
return tempArray;
}
}
I have a problem when running this program, there was no error but when I run it it said the array index is out of bound, the problem is at the transpose method, can anyone tell me how to fix this problem?
The assignment in the for-loop of
transposemethod should be like: –rather than: –
In the above code, you are assigning the value from a newly created array
tempArrayto itself only. It doesn’t make sense. It will not affect the array. Also it will throw anArrayIndexOutOfBoundsexception ifrow != colYou need to use the matrix you want to transpose.
Since you are invoking this method for
doubleMatrix2And your two matrix are like: –
So it makes sense to assign
doubleMatrix[j][i]totempArray[i][j]. Because number of rows and columns are reversed in the two matrices.