[英]Java, Matrices multiplication, How do I insert values into the matrices
我試圖讓矩陣乘法工作,我只是開始學習編程。 如何將值添加到我在main中創建的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);
}
}
名稱setElement
和getElement
幾乎可以解釋自己。 你叫setElement
一個Matrix
在一個給定的行和列位置來指定元素的值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");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.