将向量设置为矩阵算法有助于 C++

发布于 2024-12-23 09:30:35 字数 602 浏览 3 评论 0原文

我有一个包含 M*N 个元素的数组 X,我试图使用相同的数据创建一个大小为 M x N 的矩阵 A。我使用 gsl 作为矩阵,并将 X 声明为数组。我遇到了麻烦,并且矩阵中不断出现重叠。

这是我正在尝试做的一个例子:

Vector X[4*2]
1,2,3,4,5,6,7,8

Matrix A 4X2
1, 2 
3, 4
5, 6
7, 8

//heres one of my many fail attempts as an example
//creation of array X here
X[n*m] = someCbasedformulafromtheweb(n, m);
//gsl matrix allocation for matrix A N x M
gsl_matrix * A = gsl_matrix_alloc(n, m);
for(int i=0; i<n; i++) { 
    for(int j=0; j<m; j++) { 
        // setting the x[i*j] entry to gsl_matrix A at positions i , j
        gsl_matrix_set (A,i,j, x[i*j]);
    }
}

I have a array X that has M*N elements, I'm trying to create a matrix A of size M x N with this same data. I'm using gsl for the matrix and X is declared as an array. I'm having trouble and I keep getting overlap in the matrix.

Here is an example of what I am trying to do:

Vector X[4*2]
1,2,3,4,5,6,7,8

Matrix A 4X2
1, 2 
3, 4
5, 6
7, 8

//heres one of my many fail attempts as an example
//creation of array X here
X[n*m] = someCbasedformulafromtheweb(n, m);
//gsl matrix allocation for matrix A N x M
gsl_matrix * A = gsl_matrix_alloc(n, m);
for(int i=0; i<n; i++) { 
    for(int j=0; j<m; j++) { 
        // setting the x[i*j] entry to gsl_matrix A at positions i , j
        gsl_matrix_set (A,i,j, x[i*j]);
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

染柒℉ 2024-12-30 09:30:35

我没有 gsl 可以玩,但这行不通?

for (i=0 ; i<4 ; ++i)
  for (j=0 ; j<2 ; ++j)
    X[2*i + j] = gsl_matrix_get (&A, i, j));

I don't have gsl to play with, but wouldn't this work?

for (i=0 ; i<4 ; ++i)
  for (j=0 ; j<2 ; ++j)
    X[2*i + j] = gsl_matrix_get (&A, i, j));
遮了一弯 2024-12-30 09:30:35

你的问题是在这一行:

gsl_matrix_set (A,i,j, x[i*j]);

这是事情的表:

i | j | x[i*j]
0 | 0 | x[0]
0 | 1 | x[0]
1 | 0 | x[0]
1 | 1 | x[1]
2 | 0 | x[0]
2 | 1 | x[2]
3 | 0 | x[0]
3 | 1 | x[3]

相反,你需要使用:

gsl_matrix_set (A,i,j, x[2*i+j]);

i | j | x[2*i+j]
0 | 0 | x[0]
0 | 1 | x[1]
1 | 0 | x[2]
1 | 1 | x[3]
2 | 0 | x[4]
2 | 1 | x[5]
3 | 0 | x[6]
3 | 1 | x[7]

Your problem is at this line:

gsl_matrix_set (A,i,j, x[i*j]);

Here is the table of things:

i | j | x[i*j]
0 | 0 | x[0]
0 | 1 | x[0]
1 | 0 | x[0]
1 | 1 | x[1]
2 | 0 | x[0]
2 | 1 | x[2]
3 | 0 | x[0]
3 | 1 | x[3]

Instead you need to use:

gsl_matrix_set (A,i,j, x[2*i+j]);

i | j | x[2*i+j]
0 | 0 | x[0]
0 | 1 | x[1]
1 | 0 | x[2]
1 | 1 | x[3]
2 | 0 | x[4]
2 | 1 | x[5]
3 | 0 | x[6]
3 | 1 | x[7]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文