Skip to content

Instantly share code, notes, and snippets.

@Prince781
Last active August 29, 2015 14:08
Show Gist options
  • Select an option

  • Save Prince781/a6356347d852c24f7481 to your computer and use it in GitHub Desktop.

Select an option

Save Prince781/a6356347d852c24f7481 to your computer and use it in GitHub Desktop.
Basic matrix functionality.
#include <stdio.h>
#include <stdlib.h>
typedef struct mat {
int rows;
int cols;
int **e;
} mat;
mat *create_matrix(int i, int j);
mat *mat_mult(mat *m1, mat *m2);
void mat_rfill(mat *m, int max);
void mat_ifill(mat *m);
void mat_print(mat *m);
void destroy_matrix(mat *m);
int main(int argc, char *argv[])
{
mat *matA = create_matrix(3, 3);
mat *matI = create_matrix(3, 3);
mat *matB;
mat_rfill(matA, 30);
mat_ifill(matI);
matB = mat_mult(matA, matI);
printf("A = \n");
mat_print(matA);
printf("I = \n");
mat_print(matI);
printf("B = \n");
mat_print(matB);
destroy_matrix(matA);
destroy_matrix(matI);
destroy_matrix(matB);
return 0;
}
mat *create_matrix(int i, int j)
{
mat *m;
int i2;
m = malloc(sizeof(mat));
m->e = calloc(i, sizeof(int*));
for (i2=0; i2<i; ++i2)
m->e[i2] = calloc(j, sizeof(int));
m->rows = i;
m->cols = j;
return m;
}
mat *mat_mult(mat *m1, mat *m2)
{
mat *p;
int i, j, j2;
int sum;
if (m1->cols != m2->rows) {
fprintf(stderr, "Cannot multiply [%dx%d] by [%dx%d]\n",
m1->rows, m1->cols, m2->rows, m2->cols);
return NULL;
}
p = malloc(sizeof(mat));
p->e = calloc(m1->rows, sizeof(int*));
for (i=0; i<m1->rows; ++i) {
p->e[i] = calloc(m2->cols, sizeof(int));
for (sum=0, j2=0; j2<m2->cols; ++j2) {
for (j=0; j<m1->cols; ++j)
sum += m1->e[i][j] * m2->e[j][j2];
p->e[i][j2] = sum;
sum = 0;
}
}
p->rows = m1->rows;
p->cols = m2->cols;
return p;
}
void mat_rfill(mat *m, int max)
{
int i, j;
srand(time(NULL));
for (i=0; i<m->rows; ++i)
for (j=0; j<m->cols; ++j)
m->e[i][j] = (max ? rand()%max : rand());
}
void mat_ifill(mat *m)
{
int i, j;
for (i=0; i<m->rows; ++i)
for (j=0; j<m->cols; ++j)
m->e[i][j] = i == j;
}
void mat_print(mat *m)
{
int i, j;
for (i=0; i<m->rows; ++i) {
for (j=0; j<m->cols; ++j)
printf(" %4d", m->e[i][j]);
printf("\n");
}
}
void destroy_matrix(mat *m)
{
while (--m->rows >= 0)
free(m->e[m->rows]);
free(m->e);
free(m);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment