Reputation: 7349
I have allocated a large gsl_matrix and would like to allocate all its elements with known float values. Is there a way to do it without using gsl_matrix_set for each element? I am looking for the equivalent of fortran's reshape function to initialize a matrix.
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/) )
Upvotes: 1
Views: 2197
Reputation: 960
Matrices only support limited setting of all values, that is by gsl_matrix_set_all
, gsl_matrix_set_zero
or gsl_matrix_set_identity
.
However, you can create and initialise an array and then create a matrix view from that using gsl_matrix_view_array
, gsl_matrix_const_view_array
, gsl_matrix_view_array_with_tda
or gsl_matrix_const_view_array_with_tda
. (Matrix views are common in GSL. For example, they are used to express sub-matrices returned by gsl_matrix_submatrix
.) The matrix view is a struct which contains a field matrix
upon which you execute the gsl_matrix methods you wish to apply.
For example, compile with gcc matrixview.c -lgsl -lgslcblas
the following file 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" );
}
}
Upvotes: 2