【问题标题】:Java, Matrices multiplication, How do I insert values into the matricesJava,矩阵乘法,如何将值插入矩阵
【发布时间】:2017-05-10 11:39:11
【问题描述】:

我正在尝试使用矩阵乘法,但我才刚刚开始学习编程。如何向我在主中创建的 4x4 和 4x4 矩阵添加值? (这不是我的代码,但我理解其中的大部分内容,除了 setElement 和 getElement 的使用,如果你能解释一下它应该做什么)我真的很感谢你的帮助

public class Matrix{
private float[][] elements;

private int rows;
private int cols;

public int getRows()
{
    return rows;
}

public int getCols()
{
    return cols;
}

public Matrix(int rows, int cols)
{
    this.rows = rows;
    this.cols = cols;
    elements = new float[rows][cols];
}

public void setElement(int row, int col, float value)
{
    elements[row][col] = value;
}

public float getElement(int row, int col)
{
    return elements[row][col];
}

public static Matrix mult(Matrix a, Matrix b)
{
    Matrix c = new Matrix(a.getRows(), b.getCols());

    for (int row = 0; row < a.getRows(); row++)
    {
        for (int col = 0; col < b.getCols(); col++)
        {
            float sum = 0.0f;
            for (int i = 0; i < a.getCols(); i++)
            {
                sum += a.getElement(row, i) * b.getElement(i, col);
            }
            c.setElement(row, col, sum);
        }
    }
    return c;
}

public static void main(String[] args)
{
    Matrix m = new Matrix(4,4);     
    Matrix m1 = new Matrix(4,4);

    Matrix multip = Matrix.mult(m, m1);

    multip = Matrix.mult(m, m1);
    System.out.println(multip);

}

}

【问题讨论】:

  • 如果您只需要一种方法的帮助,则无需发布孔类....
  • mult(Matrix b) 的代码不正确...
  • 看看thisthis就太好了
  • 对不起,我对此很陌生。那个更好吗?乘法是使用我现在留下的其他方法

标签: java matrix matrix-multiplication


【解决方案1】:

setElementgetElement 这两个名字可以很好地解释自己。 您在 Matrix 上调用 setElement 以指定该 Matrix 中给定行和列位置的元素的值。如果你想知道元素在给定位置的值,你会打电话给getElement

以下是您如何使用它们的示例:

Matrix m = new Matrix(2,2); // Make a 2x2 matrix
m.setElement(0, 0, 11.0);   // row #0, col #0 <- 11.0
m.setElement(0, 1, 12.0);   // row #0, col #1 <- 12.0
m.setElement(1, 0, 21.0);   // row #1, col #0 <- 21.0
m.setElement(1, 1, 22.0);   // row #1, col #1 <- 22.0

// This will print "Yes"
if (m.getElement(0, 0) == 11.0)
    System.out.println("Yes");
else 
    System.out.println("No");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-11
    • 2013-12-23
    • 2018-04-11
    • 2011-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多