【发布时间】: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);
}
}
【问题讨论】:
标签: java matrix matrix-multiplication