Hello,
I'm trying to write a program for matrix multiplication
I keep getting an error....
Please help
class Matrix {
private int numRows, numColumns;
private double x[][];
public Matrix(int m, int n){
numRows = m;
numColumns = n;
x = new double[numRows][numColumns];
for(int i = 0; i < numRows; i++)
for(int j = 0; j< numColumns; j++)
x[i][j] = 0;
}
public void setElement(int i, int j, double y){
x[i-1][j-1]=y;
}
public static Matrix product(Matrix[] A){
int nRows = A[0].numRows, nColumns = A[0].numColumns;// Why must you add 0 in between brackets??
Matrix B = new Matrix(nRows,nColumns );
for (int i = 0; i < A.length;i++)
for (int k = 0; k < nColumns;k++)
for (int j = 0; j < nRows; j++)
B.x[j][12-k] *= A[i].x[12-k][j];// why does A have A[i] but B doesn't?}
return B;
}
public void print(){
System.out.println(" number of rows: " + numRows + " / number of columns: " + numColumns);
for (int i = 0; i <numRows; i ++){
for (int j = 0; j < numColumns; j++){
System.out.format("%5.0f",x[i][j]);}
System.out.println();
}
}
}
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
public class TestMatrix {
static int generateNumber(int i, int j, int k){
int n = i+j+k;
if(n*n % 3 == 0) return n%5;
else return 0;
}
public static void main(String[] args){
final int numMatrices = 7;
Matrix[] matrix = new Matrix[numMatrices];
// create & initialize matrices
for(int h=0; h<numMatrices; h++){
int numRows = 13-h, numColumns = 12-h;
matrix[h] = new Matrix(numRows, numColumns);
for(int i=0; i<numRows; i++)
for(int j=0; j<numColumns; j++)
matrix[h].setElement(i+1, j+1, generateNumber(i,j,h));
}
Matrix prod = Matrix.product(matrix);
prod.print();
}
}