Home > Net >  Multiplying two matrices in C
Multiplying two matrices in C

Time:10-01

I am trying to program a simple function that just prints out the product of two matrices, the following is what i came up with. But its not working, and I just can`t figure out why. It produces the wrong result. This is the output I get:

5.000000 12.000000 13.000000
21.000000 40.000000 41.000000
0.000000 0.000000 0.000000
0.000000 0.000000 0.000000
I was hoping someone could maybe tell me what the issue with this code is.

#include <stdio.h>

typedef struct {
int rows;
int cols;
double *data;
 } matrix;

void mult(matrix a, matrix b){
    int m = a.rows;
    int n = b.cols;
    for(int i = 0; i < m; i  ){
        for (int j = 0; j < n; j  )
        { 
          double c = 0;            
          for (int k = 0; k < a.cols; k  )
            {
                c  = *(a.data  i*a.rows  k) * *(b.data k*b.rows   j);
            }
            printf("%lf ", c);
              
        }
        puts("");
        
    }

}

int main(){
matrix a;
a.rows = 4;
a.cols = 2;
double data[] = {1,2, 
                 3,4,
                 5,6,
                 7,8
                 };
a.data = data;
matrix b;
b.rows = 2;
b.cols = 3;
double data2[] = {3,2,1,
                  5,6,7
                  };
b.data = data2;
mult(a,b);
}

CodePudding user response:

You have on issue on how to get element, perhaps using a double data[][] can be easier

void mult(matrix a, matrix b){
    int m = a.rows;
    int n = b.cols;
    for(int i = 0; i < m; i  ){
        for (int j = 0; j < n; j  )
        {
            double c = 0;
            for (int k = 0; k < a.cols; k  )
            {
                c  = a.data[i * a.cols   k] *
                     b.data[k * b.cols   j];
            }
            printf("%lf ", c);
        }
        puts("");
    }
}
  • Related