【问题标题】:Multiplying Matrix by itself in Java在Java中将矩阵自身相乘
【发布时间】:2017-01-13 12:42:08
【问题描述】:

我在乘以矩阵时遇到问题。我的代码看起来像这样,应该将矩阵自身相乘,但它不起作用,我不知道为什么。

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;

}

【问题讨论】:

  • 你得到了什么结果?
  • 您遇到了什么错误?什么不工作?你试过什么?
  • 请不要对您的问题进行垃圾邮件标记,并格式化您的代码,以便于阅读。这并不难,任何编辑器都会自动完成。
  • 为了能够multiply a matrix by itself,它必须是一个方阵。这也让您有机会在了解情况的情况下提供更好的异常处理。

标签: java matrix-multiplication


【解决方案1】:

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

所以你的代码无法编译。

你必须从这个int[][] 构造一个Matrix 对象。

【讨论】:

    【解决方案2】:
    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;
    }
    

    【讨论】:

    • 非常感谢!看起来它现在正在工作:)
    猜你喜欢
    • 2010-11-13
    • 1970-01-01
    • 2013-03-21
    • 1970-01-01
    • 2015-01-24
    • 2016-12-11
    • 1970-01-01
    • 2022-06-30
    相关资源
    最近更新 更多