如何通过在c中选择行和列来查找二维数组的子集?

问题描述 投票:0回答:2

在存储为

double *d
(主要列)的(m x n)数组中,选择一系列行和/或列的最快方法是什么:

double *filter(double *mat, int m, int n, int rows[], int cols[]);

调用为:

double *B;
int rows[]= {1,3,5}; int cols[]={2,4};
B = filter(A, 5, 4, rows, cols); 

预计将返回 A 的 3×2 子集,其中包含元素 (1,2)、(1,4)、(3,2)...

c matrix filter
2个回答
2
投票

c 对此不提供本机支持,因此您必须找到支持它的库,或者手动定义它。

伪代码:

a=length of rows     // no built in c functionality for this either, 
b=length of cols     // use a sentinel, or pass to the function
nmat = allocate (sizeof(double)*a*b) on the heap
for (i=0; i<a; ++i)
   for (j=0; j<b; ++j)
      // Note the column major storage convention here (bloody FORTRAN!)
      nmat[i + j*b] = mat[ rows[i] + cols[j]*n ];
return nmat
// caller responsible for freeing the allocated memeory

我已经评论了你面临的两个大问题。


0
投票

我很确定

m
n
应该是新数组的维度(即
m
应该是
rows
的项目数,
n
应该是 cols 中的项目数)而不是源数组的维度,就像您的示例中的情况一样,因为a)如果您已经知道要从中选择哪些索引,则不需要知道源数组的维度(并且可能允许假设这些将是有效的)和 b)如果您不知道
rows
columns
的大小,它们就没用,因为您无法迭代它们。

因此,在这个假设下,算法可能如下所示:

  • 为 m x n 数组分配内存
  • 对于 0..m 中的每个 i,0..n 中的 j
    • B[i,j] = A[ rows[i], cols[j] ];
© www.soinside.com 2019 - 2024. All rights reserved.