我已经分配了一个大的 gsl_matrix 并且想用已知的浮点值分配它的所有元素。有没有办法在不为每个元素使用 gsl_matrix_set 的情况下做到这一点?我正在寻找与 Fortran 的 reshape 函数等效的函数来初始化矩阵。
A = reshape( (/0, 1, 2, 3, 4, 5, 6, 7,
0, 1, 2, 3, 4, 5, 6, 7,
0, 1, 2, 3, 4, 5, 6, 7,
0, 1, 2, 3, 4, 5, 6, 7,
0, 1, 2, 3, 4, 5, 6, 7,
0, 1, 2, 3, 4, 5, 6, 7,
0, 1, 2, 3, 4, 5, 6, 7,
0, 1, 2, 3, 4, 5, 6, 7/), (/ 8, 8/) )
最佳答案
矩阵只支持所有值的有限设置,即通过gsl_matrix_set_all
、gsl_matrix_set_zero
或gsl_matrix_set_identity
。
但是,您可以创建和初始化一个数组,然后使用 gsl_matrix_view_array
、gsl_matrix_const_view_array
、gsl_matrix_view_array_with_tda 从该数组创建一个矩阵 View
或 gsl_matrix_const_view_array_with_tda
。 (矩阵 View 在 GSL 中很常见。例如,它们用于表示 gsl_matrix_submatrix
返回的子矩阵。)矩阵 View 是一个结构,它包含一个字段 matrix
您执行您希望应用的 gsl_matrix 方法。
例如,用gcc matrixview.c -lgsl -lgslcblas
编译以下文件matrixview.c
:
#include <stdio.h>
#include <gsl/gsl_matrix.h>
#define rows 2
#define cols 3
int main () {
const double data[rows*cols] = {
0.0, 0.1, 0.2,
1.0, 1.1, 1.2,
};
const gsl_matrix_const_view mat = gsl_matrix_const_view_array( data, rows, cols );
for ( size_t row = 0; row < rows; ++row ) {
for ( size_t col = 0; col < cols; ++col ) {
printf( "\t%3.1f", gsl_matrix_get( &mat.matrix, row, col ) );
}
printf( "\n" );
}
}
关于c - 初始化 GSL 矩阵的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39480181/