如果您需要一个密集矩阵,那么分配一大块大小为 M x N 的 array[] 并将其包装在一个 Matrix 类中会更容易,该类可以将 matrix(r, c) 转换为 array[r*C + c]。
这样您将只对内部array[] 执行一次数组复制操作。
类似这样的:
编辑:使用System.arraycopy()添加行主矩阵连接:
package example;
import java.util.Arrays;
import java.util.Random;
public class Matrix {
private double[] array;
int R;
int C;
Matrix(int R, int C) {
this.R = R;
this.C = C;
this.array = new double[R * C];
}
Matrix(double[] array, int R, int C) {
this.R = R;
this.C = C;
this.array = array;
}
Matrix(Matrix that) {
this.R = that.R;
this.C = that.C;
array = Arrays.copyOf(that.array, that.array.length);
}
public void set(int r, int c, double value) {
assert (r >= 0 && r < R);
assert (c >= 0 && c < C);
array[C * r + c] = value;
}
public double get(int r, int c) {
assert (r >= 0 && r < R);
assert (c >= 0 && c < C);
return array[C * r + c];
}
public static Matrix concatRows(Matrix m1, Matrix m2) {
double[] array = concat(m1.array, m2.array);
Matrix m = new Matrix(array, m1.R + m2.R, m1.C);
return m;
}
private static double[] concat(double[] array2, double[] array3) {
int aLen = array2.length;
int bLen = array3.length;
double[] C = new double[aLen + bLen];
System.arraycopy(array2, 0, C, 0, aLen);
System.arraycopy(array3, 0, C, aLen, bLen);
return C;
}
public void print() {
for (int r = 0; r < R; r++) {
for (int c = 0; c < C; c++) {
double v = get(r, c);
System.out.print(String.format("%.3f ", v));
}
System.out.println();
}
System.out.println();
}
public static void main(String[] args) {
double[] a1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Matrix m1 = new Matrix(a1, 3, 3);
m1.print();
double[] a2 = { 3, 2, 1, 6, 5, 4 };
Matrix m2 = new Matrix(a2, 2, 3);
m2.print();
Matrix m3 = Matrix.concatRows(m1, m2);
m3.print();
}
}
输出:
1.000 2.000 3.000
4.000 5.000 6.000
7.000 8.000 9.000
3.000 2.000 1.000
6.000 5.000 4.000
1.000 2.000 3.000
4.000 5.000 6.000
7.000 8.000 9.000
3.000 2.000 1.000
6.000 5.000 4.000
基本上,除非您可以确保该矩阵是不可变的,否则您只能求助于整个矩阵的深拷贝。所以顺序仍然是O(N),其中矩阵的N = ROWS * COLS。