【问题标题】:Vectorization of indexing a 2d array with an array in C用 C 中的数组索引二维数组的向量化
【发布时间】:2014-11-29 20:46:37
【问题描述】:

我可以用 C 中的向量来索引一个二维数组,如下所示:

int main()
{
double mat[5][3] = {{5.5,2.1,1.9},
                    {6.5,7.0,8.8},
                    {5.4,3.1,8.9},
                    {9.0,0.1,2.4},
                    {5.9,8.0,0.7}};
int in[4] = {3,4,2,1};
double smat[4][3];
int i,j;

for(i=0;i<4;i++)
for(j=0;j<3;j++)
{
{
    smat[i][j] = mat[in[i]][j];
}
}

printf("%.1f\n",smat[1][0]); //mat[4][0]=5.9
printf("%.1f\n",smat[0][2]); //mat[3][2]=2.4
printf("%.1f\n",smat[3][1]); //mat[1][1]=7.0

return 0;
}

代码成功返回:

5.9
2.4
7.0

问题:我们可以在 C 中向量化两个 for 循环操作,而不使用循环吗?

【问题讨论】:

  • “矢量化”是什么意思?请记住,C 不是 MATLAB。
  • 检查生成的程序集,也许你的编译器已经将它向量化了。
  • @Park:怎么查?我通过使用 Intel Parallel Studio 键入“cl mycode.c”来编译它。

标签: c arrays


【解决方案1】:

在 C 中使用 for-loop 操作的示例(使用函数 memcpy()):

#include <stdio.h>

double mat[5][3] = {{5.5,2.1,1.9},
                    {6.5,7.0,8.8},
                    {5.4,3.1,8.9},
                    {9.0,0.1,2.4},
                    {5.9,8.0,0.7}};
int in[4] = {3,4,2,1};
double smat[4][3];

void main()
{
    int i;
    for(i = 0; i < 4; i++)
        memcpy(smat[i], mat[in[i]], sizeof(double)*3);

    printf("%.1f\n",smat[1][0]); //mat[4][0]=5.9
    printf("%.1f\n",smat[0][2]); //mat[3][2]=2.4
    printf("%.1f\n",smat[3][1]); //mat[1][1]=7.0
}

(如果你是这个意思。)

【讨论】:

    猜你喜欢
    • 2021-10-02
    • 2020-07-30
    • 2016-09-19
    • 2014-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 2012-04-10
    相关资源
    最近更新 更多