Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matrix Multiplication In C

Tags:

c

math

matrix

I'm trying to solve a matrix multiplication problem with C. Matrix sizes given in problem (2x2) I wrote this code but it doesn't print result as I expect. I think I'm missing a point about rules of C.

What is my mistake in this code ?

#include <stdio.h>
int main() {
    int matA[2][2]={0,1,2,3};
    int matB[2][2]={0,1,2,3};
    int matC[2][2];
    int i, j, k;
    for (i = 0; i < 2; i++) {
        for(j = 0; j < 2; j++) {
            for(k = 0; k < 2; k++) {
                matC[i][j] += matA[i][k] * matB[k][j];
            }
            printf("%d\n",matC[i][j]);
        } 
    }
}

Printing Result:

2 
3 
4195350
11
like image 948
C Beginner Avatar asked Apr 15 '12 13:04

C Beginner


1 Answers

Here is the matrix multiplication code I use:

for(i=0;i<M;i++){
    for(j=0;j<K;j++){
        matC[i][j]=0;
        for(k=0;k<N;k++){
            matC[i][j]+=matA[i][k]*matB[k][j];
        }
    }
}

big thing is setting the answer matrix to zero (as the rest have said without code).

like image 97
Youssef G. Avatar answered Nov 08 '22 19:11

Youssef G.