gpt4 book ai didi

Java,矩阵乘法,如何将值插入矩阵

转载 作者:太空宇宙 更新时间:2023-11-04 11:30:09 25 4
gpt4 key购买 nike

我正在尝试让矩阵乘法发挥作用,我才刚刚开始学习编程。如何向我在 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);

}

}

最佳答案

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

关于Java,矩阵乘法,如何将值插入矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43891427/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com