在存储为
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 对此不提供本机支持,因此您必须找到支持它的库,或者手动定义它。
伪代码:
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
我已经评论了你面临的两个大问题。
我很确定
m
和 n
应该是新数组的维度(即 m
应该是 rows
的项目数,n
应该是 cols 中的项目数)而不是源数组的维度,就像您的示例中的情况一样,因为a)如果您已经知道要从中选择哪些索引,则不需要知道源数组的维度(并且可能允许假设这些将是有效的)和 b)如果您不知道 rows
和 columns
的大小,它们就没用,因为您无法迭代它们。
因此,在这个假设下,算法可能如下所示:
B[i,j] = A[ rows[i], cols[j] ];