[英]Java, Matrices multiplication, How do I insert values into the matrices
I am trying to get the matrix multiplication to work, I'm only beginning to learn programming. 我试图让矩阵乘法工作,我只是开始学习编程。 How can I add values to the 4x4 and 4x4 matrices I created in the main?
如何将值添加到我在main中创建的4x4和4x4矩阵? (This is not my code but I understand most of it, except the use of setElement & getElement if you could please explain to me what it's supposed to do) I would really appreciate the help
(这不是我的代码,但我理解其中的大部分,除了使用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);
}
} }
The names setElement
and getElement
pretty much explain themselves. 名称
setElement
和getElement
几乎可以解释自己。 You call setElement
on a Matrix
to specify a value for the element at a given row-and-column position in that Matrix
. 你叫
setElement
一个Matrix
在一个给定的行和列位置来指定元素的值Matrix
。 And you would call getElement
if you wanted to know the value of the element at a given position. 如果你想知道给定位置元素的值,你可以调用
getElement
。
Here's a example of how you'd use them: 以下是您如何使用它们的示例:
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");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.