在Java中将Matrix单独乘以

时间:2017-01-13 12:42:08

标签: java matrix-multiplication

我有一个问题乘以矩阵。我的代码看起来像这样,应该自己乘以矩阵,但它不起作用,我不知道为什么。

class Matrix {
    // Constructor: create a matrix with only zeroes.
    public Matrix(int numRows, int numColumns) {
        this.values = new double[numRows][numColumns];
        this.numRows = numRows;
        this.numColumns = numColumns;
    }

    public int getNumRows() {
        return this.numRows;
    } 

    public int getNumColumns() {
        return this.numColumns;
    }

    public double getValue(int row, int column) {
        return this.values[row][column];
    } 

    public void setValue(int row, int column, double value) {
        this.values[row][column] = value;
    }

    public Matrix multiply(Matrix b) {
        // to be implemented

        int [][] result = new int[Matrix b.length][Matrix b[0].length];
        for (int i = 0; i < Matrix b.length; i++) { 
            for (int j = 0; j < Matrix b[0].length; j++) { 
                for (int k = 0; k < Matrix b[0].length; k++) { 
                    result[i][j] += Matrix b[i][k] * Matrix b[k][j];
                }
            }
        }
        return result
    }
}

public void print() {
    for (int i = 0; i < this.numRows; i++) {
        for (int j = 0; j < this.numColumns; j++) {
            System.out.print(this.values[i][j] + " ");
        }
        System.out.println();
    }
} 

private double[][] values;
private int numRows;
private int numColumns;

}

2 个答案:

答案 0 :(得分:0)

您的public Matrix multiply(Matrix b)方法应返回Matrix类型的对象,但您执行return result;,结果为数组:int [][] result = new int[Matrix b.length][Matrix b[0].length];

所以你的代码无法编译。

您必须从此Matrix构建一个int[][]对象。

答案 1 :(得分:0)

public Matrix multiply(Matrix a, Matrix b) {
    Matrix m = new Matrix(a.getNumRows(), b.getNumColumns());
    for (int i = 0; i < m.getNumRows(); i++)
        for (int j = 0; j < b.getNumColumns(); j++)
            for (int k = 0; k < a.getNumRows(); k++)
                m.setValue(i, j, a.getValue(i, k) * b.getValue(k, j));
    return m;
}
相关问题