2017-05-10 71 views
1

我想让矩阵乘法工作,我只是开始学习编程。我如何将值添加到我在主要创建的4x4和4x4矩阵中? (这不是我的代码,但我了解大部分,除了使用setElement & getElement的,如果您能向我解释什么它应该做的),我真的很感激帮助Java,矩阵乘法,我如何将值插入矩阵

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); 

} 

}

+0

无需发布孔类,如果你只需要帮助,一个方法.... –

+0

为'MULT(矩阵B的代码)'是**不正确** ...... –

+0

如果你看看[this](http://stackoverflow.com/help/how-to-ask)和[this](http:/ /stackoverflow.com/help/mcve) –

回答

0

名称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"); 
+0

这使得总体感,谢谢! – Stefan