我有一个矩阵的一维表示形式:

double *A1d;


您可以假定此数据结构为malloc'd,并用双精度值填充且长度为MATRIX_SIZE * MATRIX_SIZE

我想将此数据结构转换为类型为double**的行/列长度为MATRIX_SIZE的二维方阵

我正在寻找类似的东西:

double** A2D = vector_to_matrix(int sz, double* matrix_1d);

最佳答案

double** vector_to_matrix(int sz, double* matrix_1d) {
  // The output 2d matrix to be returned.
  double** matrix_2d = (double**)malloc(sz * sizeof(double*));

  // Allocate memory.
  for (int i = 0; i < sz; i++)
    matrix_2d[i] = (double*)malloc(sz * sizeof(double));

  // Copy from 1d matrix.
  for (int i = 0; i < sz; i++)
    for (int j = 0; j < sz; j++) matrix_2d[i][j] = matrix_id[i * sz + j];

  return matrix_2d;
}

关于c++ - 将double *一维矩阵转换为double ** 2D方阵,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29498573/

10-09 18:21
查看更多