So I'm trying to multiply matrices in c. However when I try to multiply the numbers in the two arrays, and put them in an answer array its always zero. heres the code for the method, thanks.
My matrix struct:
typedef struct matrix {
int r;
int c;
double **mat;
} *matrix_t;
My matrix multiplying method:
matrix_t mat_mult(matrix_t a, matrix_t b)
{
int i, j, k;
double x, temp1, temp2;
double tempsol = 0.0;
x = temp1 = temp2 = 0;
matrix_t answer;
if(a -> c == b -> r)
{
answer = mat_new(a -> r, b -> c);
for(i = 0; i < a -> r; i++)
for( j = 0; j < b -> c; j++)
{
for( k = 0; k < a -> c; k++)
{
tempsol += a->mat[i][k] * b->mat[k][j];
answer-> mat[i][j] = tempsol;
}
}
return answer;
}
else if(a -> r == b -> c)
{
answer = mat_new(a -> c, b -> r);
return answer;
}
else
{
printf("Matrices could not be multiplied");
exit(1);
return;
}
}
heres the code for my mat_new as well
matrix_t mat_new(int r,int c)
{
int i = 0;
double **a;
matrix_t matrix_a;
a = (double**)malloc(r *sizeof(double *));
for(i = 0; i < r; i++)
{
a[i] = (double*)malloc(c *sizeof(double));
}
matrix_a = (matrix_t) malloc ( sizeof(struct matrix));
matrix_a -> mat = a;
matrix_a -> r = r;
matrix_a -> c = c;
return matrix_a;
}