简体   繁体   中英

Matrix Multiplication In C

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

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).

The problem is that in the line

matC[i][j] += matA[i][k] * matB[k][j];

you are adding things to matC, but when you create it, you don't initialize it, so it has garbage.

You sould do something like:

int matC[2][2] = {0} which will initialize all the matrix with 0's

matC initially contains some garbage values. Iniatialize the martix to all zeroes. This might solve your problem

You can have matrix multiplication of any given size by user in the following manner :

#include<stdio.h>
void main()
{
    int r1, c1, r2, c2;

    printf("Enter number of rows and columns for matrix A : ");
    scanf("%d %d",&r1,&c1);

    printf("Enter number of rows and columns for matrix B : ");
    scanf("%d %d",&r2,&c2);

    int a[r1][c1], b[r2][c2], ab[r1][c2], ba[r2][c1],i,j,k,temp;

    if(c1==r2 && r1==c2)
    {
        printf("\nEnter element in matrix A : ");
        for(i=0;i<r1;i++)
        {
            for(j=0;j<c1;j++)
            {
                printf("\n Enter element : ");
                scanf("%d",&a[i][j]);
            }
        }
        printf("\nEnter element in B : ");
        for(i=0;i<r2;i++)
        {
            for(j=0;j<c2;j++)
            {
                printf("\nEnter element : ");
                scanf("%d",&b[i][j]);
            }
        }
        for(i=0;i<r1;i++)
        {
            for(j=0;j<c2;j++)
            {
                temp=0;
                for(k=0;k<r2;k++)
                {
                    temp+=a[i][k]*b[j][k];
                }
                ab[i][j]=temp;
            }
        }
        for(i=0;i<r2;i++)
        {
            for(j=0;j<c1;j++)
            {
                temp=0;
                for(k=0;k<r1;k++)
                {
                    temp+=b[i][k]*a[k][j];
                }
                ba[i][j]=temp;
            }
        }
        printf("\nMatrix A : ");
        for(i=0;i<r1;i++)
        {
            printf("\n\t");
            for(j=0;j<c1;j++)
            {
                printf("%d",a[i][j]);
            }
            printf("\n");
        }
        printf("\nMatrix B : ");
        for(i=0;i<r2;i++)
        {
            printf("\n\t");
            for(j=0;j<c2;j++)
            {
                printf("%d",b[i][j]);
            }
        }
        printf("\nMatrix multiplication of A*B : ");
        for(i=0;i<r1;i++)
        {
            printf("\n\t");
            for(j=0;j<c2;j++)
            {
                printf("\t%d",ab[i][j]);
            }
            printf("\n");
        }
        printf("\nMatrix multiplication of B*A : ");
        for(i=0;i<r2;i++)
        {
            printf("\n\t");
            for(j=0;j<c1;j++)
            {
                printf("\t%d",ba[i][j]);
            }
            printf("\n");
        }
    }
    else
        printf("\nMatrix Multiplication is not possible...!!!");
}

您必须首先将C元素初始化为零。

If size and dependencies don't matter I would suggest using the GNU Scientific Library. See here for features: http://en.wikipedia.org/wiki/GNU_Scientific_Library

It contains optimized routines for mathematical calculations and is quite fast with some compiler optimizations.

Already used it successful for matrix operations in 3D Development.

您应该将matC初始化为全零。

You may want to dynamically allocate memory for the resultant matrix. If so, use calloc() to allocate and clear the elements. printMatrix() is called to print result, but not defined here.

/* matrix1: [rows1 x cols1];  matrix2: [rows2 x cols2]; product is
matrix3: [rows1 x cols2] if (cols1 == rows2) is true.  calloc to 
allocate / clear memory for matrix3.  Algorithm is O(n^3) */

float ** matrix3;
if (cols1 == rows2) {  // product matrix can be calculated
    // calloc product matrix3
    matrix3 = (float **)calloc(rows1, sizeof(float *));
    for (int i = 0; i < rows1; i++)
        matrix3[i] = (float *)calloc(cols2, sizeof(float));

    int i, j, k;
    float tmp;
    for (i = 0; i < rows1; i++) {
        for (j = 0; j < cols2; j++) {
            tmp = 0.0;
            for (k = 0; k < rows2; k++)
                tmp += matrix1[i][k] * matrix2[k][j];
            matrix3[i][j] = tmp;
        }
    }
    printMatrix(matrix3, rows1, cols2, 3);
    free(matrix3);
} else {   // cols1 != rows2
    puts("dimensional mismatch; can't multiply matrices");
}
//
//  main.c
//  Matrix Multiplicatiion.
//
//  Created by Devansh on 15/07/21.
// THIS WORKS FOR ANY MATRIX multiplication 
//

#include <stdio.h>

int main()
{
    int arow,acolumn,brow, bcolumn,i,j;
    int MAX=100;
    int a[MAX][MAX];
    int b[MAX][MAX];
    printf("enter rows of matrix a: ");
    scanf("%d", &arow);
    printf("enter columns of matrix a: ");
    scanf("%d", &acolumn);
    printf("enter rows of matrix b: ");
    scanf("%d", &brow);
    printf("enter columns of matrix b: ");
    scanf("%d", &bcolumn);
    if(brow != acolumn){
        printf("sorry we cannot multiply matrix a and b");
    } else {
        printf("enter the elements of matrix a:\n");
        for (i=0;i<arow;i++) {
            for(j=0;j<acolumn;j++) {
                scanf("%d", &a[i][j]);
            }
        }
        
        printf("enter the elements of matrix b:\n");
        for (i=0;i<brow;i++) {
            for (j=0;j<bcolumn;j++) {
                scanf("%d", &b[i][j]);
            }
        }
        int product[MAX][MAX];
        int sum=0;
        for (i=0;i<arow;i++) {
            for(j=0;j<bcolumn;j++){
                for(int k=0;k<brow;k++){
                    sum += a[i][k] * b[k][j];
                }
                product[i][j]= sum;
            }
        }
        for (i=0;i<arow;i++) {
            for (j=0;j<bcolumn;j++) {
                printf("%d   ", product[i][j]);
            }
            printf("\n");
        }
    }
    return 0;
}

u can find multiplication of 2 matrix of any dimension (like multiplication of 2x3 and 3x2 size matrix)using this code.

 #include <stdio.h>
     int main()
    {
    int p, q, r, s;
    printf("enter the dimension of first matrix\n");
    scanf("%dx%d", &p, &q);
    printf("enter the dimension of second matrix\n");
    scanf("%dx%d", &r, &s);
    if (q != r)
    {
        printf("multiplication is not possible\n");
    }
    else
    {
        int a[p][q], b[r][s], c[p][s];
        printf("enter the first matrix\n");
        for (int i = 0; i < p; i++)
        {
            for (int j = 0; j < q; j++)
            {
                scanf("%d", &a[i][j]);
            }
        }
        printf("enter the second matrix\n");
        for (int i = 0; i < r; i++)
        {
            for (int j = 0; j < s; j++)
            {
                scanf("%d", &b[i][j]);
            }
        }
        for (int i = 0; i < p; i++)
        {
            for (int j = 0; j < s; j++)
            {
                int sum = 0;
                for (int k = 0; k < r; k++)
                {
                    sum = sum + (a[i][k] * b[k][j]);
                }
                c[i][j] = sum;
            }
        }
        printf("resultant matrix is....\n");
        for (int i = 0; i < p; i++)
        {
            for (int j = 0; j < s; j++)
            {
                printf("%d\t", c[i][j]);
            }
            printf("\n");
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM