Pushkar Pradhan wrote:

> I'm working on something similar, try the below,

> they are 1-D matrices e.g. a 4X4 matrix will be accessed like this:

> a[0], a[1], ... a[15].

> If you want I have other functions like print_matrix also.

> /*

> ** Generate a random matrix

> */

> double * gen_matrix(int numRows, int numCols, int initialize)

> {

>

> double *x = NULL;

> long i;

>

> x = (double*)calloc( (numRows*numCols), sizeof(double) );

> if(x == NULL) {

> exit(-1);

> }

>
why do you use calloc if you initialize it right after, anyway?

> /* initialize to zero */

> if(!initialize) {

> for(i = 0; i < numRows*numCols; i++) {

> x[i] = 0.0;

> /*printf("%d %g\n", i, x[i]);*/

> }

> }

> else {

> /* seed rand() with time so it starts randomly */

> srand( (unsigned)time(NULL) );

>

> for(i = 0; i < numRows*numCols; i++) {

> x[i] = i;

> /*printf("%d %g\n", i, x[i]);*/

> }

> }

>

> return x;

>

> }
You could also have some fun and make a matrix type:

struct matrix

{

double* content;

unsigned int cols;

}

gen_matrix would be (I made it a litte more flexible, so it wouldn't exit on

failure):

struct matrix* gen_matrix(unsigned int rows, unsigned int cols)

{

struct matrix *matrix_ptr;

matrix_ptr = malloc(sizeof *matrix_ptr);

if ( matrix_ptr == NULL )

return ( NULL );

matrix_ptr->content = malloc(sizeof *matrix_ptr->content * rows *

cols);

if ( matrix_ptr->content == NULL )

{

free(matrix_ptr);

return ( NULL );

}

/* do any initialization of the content */

matrix_ptr->cols = cols;

return ( matrix_ptr );

}

Of course you could include the type it creates in both the name of the

structure and function (double vs int).

Now it is easier to use the indexes with getters and setters (uses 1-base

indexing, btw):

double get_matrix_value(struct matrix *matrix_ptr, unsigned int row,

unsigned int col)

{

if ( row == 0 || col == 0 )

return ( 0.0 ); /* set an error here */

return ( matrix_ptr->content[matrix_ptr->cols * (row - 1) + (col -

1)] );

}

Of course I don't check on out of bounds, so you would have to tweak this to

your needs (e.g. add the rows property to the structure as well, and check

for overflow).

Hope this helps,

--

Martijn

http://www.sereneconcepts.nl