【发布时间】:2015-12-31 07:42:59
【问题描述】:
我的班级有这个作业,我必须创建一个矩阵乘法程序。条件如下:
实现两个 n × n 矩阵相乘的两种算法。假设 n 是 2 的幂:
- 简单的 O(n^3) 矩阵乘法算法。
- Strassen 的矩阵乘法算法。
评估您的不同算法,并撰写一份简短报告。为不同的 n (4, 10, 20,100) 值创建测试矩阵。使用随机数生成矩阵。计算算法的运行时间。您的报告应包括运行时间和结论。
这是我目前的代码:
public class MatrixMultiplication
{
public static void main(String[] args)
{
Random rand = new Random();
int rows = rand.nextInt(7) + 2;
int columns = rand.nextInt(7) + 2;
System.out.println("The matrix has " + rows + " randomized rows");
System.out.println("The matrix has " + columns + " randomized column");
System.out.println();
double[][] a = new double[rows][columns];
double[][] b = new double[columns][rows];
System.out.println("The first matrix has the values: ");
Matrix m1 = new Matrix(a);
System.out.println("---------------------------------");
System.out.println("The second matrix has the values: ");
Matrix m2 = new Matrix(b);
System.out.println();
Matrix productRegular = m1.multiply(m2);
}
}
这是我的另一堂课:
import java.util.Random;
class Matrix
{
double[][] arrayA;
double[][] arrayB;
private Matrix(double[][] a, double[][] b)
{
arrayA = a;
arrayB = b;
}
public Matrix(double[][] array) //Create matrix values
{
Random rand = new Random();
for(int i = 0; i < array.length; i++)
{
for(int j = 0; j < array[i].length; j++)
{
array[i][j] = rand.nextInt(10);
System.out.print(array[i][j] + " | ");
}
System.out.println();
}
}
public double multiply(double[][] a, double[][] b)
{
double[][] c = new double[a.length][b[0].length];
System.out.println("Product of A and B is");
for(int i = 0; i < a.length; i++)
{
for(int j = 0; j < b[0].length; j++)
{
for(int k = 0; k < a[0].length; k++)
{
c[i][j] += a[i][k] * b[k][j];
System.out.println(c[i][j] + " | ");
}
}
System.out.println();
}
return c;
}
}
我知道我必须为乘法方法传递一个对象/矩阵,但我该怎么做呢?我的代码中还有其他问题,但我现在想专注于传递对象。
【问题讨论】:
-
你的矩阵类应该只包含一个数组,你的多个方法应该只有一个参数。
标签: java algorithm matrix data-structures multiplication