从矩阵中提取特定列,并将其作为新矩阵存储在C中

从矩阵中提取特定列,并将其作为新矩阵存储在C中,c,memcpy,lapack,blas,C,Memcpy,Lapack,Blas,我有一个存储为动态数组的矩阵,即double*inputMat。我知道它的行数和列数,通过它我可以提取任何特定的列。现在的问题是,我有一组列要提取并存储到另一个动态数组中。如何做到这一点?我正在编写代码的一部分以供参考: double *extractMatrix(double *inputMat,int rows, int *columnIndex, int columnTotal) { double *outputMat=malloc(sizeof(double)*rows

我有一个存储为动态数组的矩阵,即double*inputMat。我知道它的行数和列数,通过它我可以提取任何特定的列。现在的问题是,我有一组列要提取并存储到另一个动态数组中。如何做到这一点?我正在编写代码的一部分以供参考:

double *extractMatrix(double *inputMat,int rows, int *columnIndex, int columnTotal)
{      
   double *outputMat=malloc(sizeof(double)*rows*columnTotal);
   for(int i=0; i<columnTotal; i++)
       memcpy(outputMat, &inputMat[rows*columnIndex[i]],rows*sizeof(double));
   return outputMat;
}
double*extractMatrix(double*inputMat,int行,int*columnIndex,int columnTotal)
{      
double*outputMat=malloc(sizeof(double)*行数*列总数);

对于(int i=0;i您的基本目标是对double数组(实际上是指向double的指针)进行索引,就像它是一个2D数组一样。您希望在函数中提取某列
columnIndex
,并动态分配一块内存来保存组成该列的值(
值数)并返回指向新分配块的指针

您的方法是正确的,您的索引刚刚关闭。在
for
循环本身中处理索引要容易得多。基本方法是:

int n = 0;
for (int i = colindex; i < rows * cols; i += cols)
    output[n++] = input[i];
(这是9个值中模拟3x3阵列的第2列)


仔细检查一下,如果有任何问题,请告诉我。

Nothing。cols表示inputMat中的列数。在当前场景中不需要它。我将删除它。请查看编辑的版本。
memcpy(outputMat,
目的地始终相同,应该根据
i
更改。如果您将
double*
作为参数传递,为什么需要
列总数
呢?
大小
不是更合适吗?您基本上有一个double数组(虽然从技术上讲是指向double的指针)。您只需使用指针,
size
columnIndex
)。然后您可以根据自己的喜好对其进行索引以提取列。@chux。如何更改它?我们可以使用memcpy(outputMat+rowsisizeof(double),…)迭代的内存地址outputMat@DavidC.Rankin:columnTotal表示columnIndex的大小,即outputMat中的列数,而rows是inputMat/outputMat中的行数。它在内存分配中很有用。我想从输入数组的不同区域复制内存块(列)。我听说memcpy比“for-loop”索引。由于我正在处理的矩阵非常大(大小>=500x500),使用常规的“for-loop”复制可能会稍微慢一点特别是当我在实际算法中多次调用此函数时。我想要的是合并不同的列。我不知道如何使用memcpy。我需要一些迭代器之类的东西,比如显式地将其复制到“n”之后元素。我不知道您是从哪里获得信息的,但是您不能
memcpy
非顺序字节,因此当每个列值由
cols*sizeof val
字节分隔时,使用
memcpy
从内存块中拾取列根本不会有任何好处。我是否理解您的问题?现在,如果您需要将500多列2D数组中的500列转换为单独的500列2D数组,然后是的,
memcpy
很有用,因为您可以一次
memcpy
500个值(因为相邻列的值是相邻的),但要拾取非相邻列则没有任何用处。
#include <stdio.h>
#include <stdlib.h>

int *getcol (const int *a, const int rows, const int col, const int ncols)
{
    int sz = rows * ncols,
        n = 0,   /* output index */
        *out = malloc (rows * sizeof *a);

    if (out)
        for (int i = col; i < sz; i += ncols)  /* index with loop vars */
            out[n++] = a[i];                   /* assign column values */

    return out;
}

int main (void) {

    int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 },
        rows = 3,                   /* simulate a 3x3 with 9 values */
        cols = sizeof a / (rows * sizeof *a),
        colidx = 1,                 /* zero based index of wanted column */
        *output = NULL;

    if ((output = getcol (a, rows, colidx, cols))) {
        for (int i = 0; i < rows; i++)
            printf (" %2d\n", output[i]);
        free (output);  /* don't forget to free memory */
    }

    return 0;
}
$ ./bin/array_idx_1d_as_2d
  2
  5
  8