矩陣宣告
#include <gsl/gsl_matrix.h>
gsl_matrix *m = gsl_matrix_alloc(6,5); //橫列數,直行數
double a[] = {1,2,3,4,5,
2,4,6,8,10,
3,6,9,12,15,
4,8,12,16,20,
5,10,15,20,25,
6,12,18,24,30};
SetMat(m,a) //賦值
PrintMat(m); // 輸出
/*
typedef struct
{
size_t size1; // # of rows
size_t size2; // # of columns
size_t tda;
double * data; // the location of the first element of the matrix in memory
gsl_block * block;
int owner;
} gsl_matrix;
*/
void SetMat(gsl_matrix *m, double n[]){
//if( m->size1*m->size2 != (int)(sizeof(n)/sizeof(n[0]))){
// printf("Error: Set Matrix Mismatchd! gsl_len is %d and input array is %d.\\n",
// m->size1*m->size2,
// (int)(sizeof(n)/sizeof(n[0])));
// exit(0);
//}
for(int i=0;i<m->size1;i++){
for(int j=0;j<m->size2;j++){
gsl_matrix_set (m, i, j, *n++);
}
}
}
或是
// more easy way!
double a[] = {1,2,3,4,5,
2,4,6,8,10,
3,6,9,12,15,
4,8,12,16,20,
5,10,15,20,25,
6,12,18,24,30};
gsl_matrix_view m = gsl_matrix_view_array(a, 6, 5); // 橫列數,直行數
PrintMat(&m.matrix); // 輸出
矩陣輸出
void PrintMat(gsl_matrix *m){
printf("Print Matrix: \\n");
for(int i=0; i<m->size1;i++){
for(int j=0;j<m->size2;j++){
//printf(j==m->size2-1 ? "%6.3f\\n" : "%6.3f ", gsl_matrix_get(m,i,j));
printf(j==m->size2-1?"%6.2f\\n":"%6.2f\\t", gsl_matrix_get(m,i,j));
}
}
}