3 /* xbt_matrix_t management functions */
5 /* Copyright (c) 2006 Martin Quinson. All rights reserved. */
7 /* This program is free software; you can redistribute it and/or modify it
8 * under the terms of the license (GNU LGPL) which comes with this package. */
10 #include "xbt/sysdep.h"
12 #include "xbt/matrix.h"
14 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(matrix,xbt,"2D data storage");
16 /** \brief constructor */
17 xbt_matrix_t xbt_matrix_new(int lines, int rows,
18 const unsigned long elmsize,
19 void_f_pvoid_t * const free_f) {
20 xbt_matrix_t res=xbt_new(s_xbt_matrix_t, 1);
23 res->elmsize = elmsize;
25 res->data = xbt_malloc(elmsize*lines*rows);
29 /** \brief destructor */
30 void xbt_matrix_free(xbt_matrix_t mat) {
34 for (i=0; i < (mat->lines * mat->rows) ; i++) {
35 (*(mat->free_f))( (void*)& (mat->data[i*mat->elmsize]) );
43 /** \brief Freeing function for containers of xbt_matrix_t */
44 void xbt_matrix_free_voidp(void *d) {
45 xbt_matrix_free( (xbt_matrix_t) *(void**)d );
49 /** \brief Display the content of a matrix (debugging purpose)
50 * \param coords: boolean indicating whether we should add the coords of each cell to the output*/
51 void xbt_matrix_dump(xbt_matrix_t matrix, const char*name, int coords,
52 void_f_pvoid_t display_fun) {
55 fprintf(stderr,">>> Matrix %s dump (%d x %d)\n",name,matrix->lines,matrix->rows);
56 for (i=0; i<matrix->lines; i++) {
58 for (j=0; j<matrix->rows; j++) {
60 fprintf(stderr," (%d,%d)=",i,j);
63 display_fun(xbt_matrix_get_ptr(matrix,i,j));
67 fprintf(stderr,"<<< end_of_matrix %s dump\n",name);
70 void xbt_matrix_dump_display_double(void*d) {
71 fprintf(stderr,"%.2f",*(double*)d);
74 /** \brief Creates a new matrix of double filled with zeros */
75 xbt_matrix_t xbt_matrix_double_new_zeros(int lines, int rows) {
76 xbt_matrix_t res = xbt_matrix_new(lines, rows,sizeof(double),NULL);
79 for (i=0; i<lines; i++)
80 for (j=0; j<rows; j++)
81 xbt_matrix_get_as(res,i,j,double) = 0;
85 /** \brief Creates a new matrix of double being the identity matrix */
86 xbt_matrix_t xbt_matrix_double_new_id(int lines, int rows) {
87 xbt_matrix_t res = xbt_matrix_double_new_zeros(lines, rows);
90 for (i=0; i<lines; i++)
91 xbt_matrix_get_as(res,i,i,double) = 1;
95 /** \brief Creates a new matrix of double randomly filled */
96 xbt_matrix_t xbt_matrix_double_new_rand(int lines, int rows) {
97 xbt_matrix_t res = xbt_matrix_new(lines, rows,sizeof(double),NULL);
100 for (i=0; i<lines; i++)
101 for (j=0; j<rows; j++)
102 xbt_matrix_get_as(res,i,j,double) = (double)rand();
106 /** \brief Creates a new matrix being the multiplication of two others */
107 xbt_matrix_t xbt_matrix_double_new_mult(xbt_matrix_t A,xbt_matrix_t B) {
108 xbt_matrix_t result = xbt_matrix_double_new_zeros(A->lines, B->rows);
111 for (i=0; i<result->lines; i++)
112 for (j=0; j<result->rows; j++)
113 for (k=0; k<B->lines; k++)
114 xbt_matrix_get_as(result,i,j,double) +=
115 xbt_matrix_get_as(A,i,k,double) * xbt_matrix_get_as(B,k,j,double);