开发者

Multiplying two arrays in C

开发者 https://www.devze.com 2023-01-29 16:36 出处:网络
I\'m trying to multiply two multi开发者_如何学JAVAdimensional arrays to form a matrix. I have this function. This should work in theory. However, I am just getting 0s and large/awkward numbers. Can so

I'm trying to multiply two multi开发者_如何学JAVAdimensional arrays to form a matrix. I have this function. This should work in theory. However, I am just getting 0s and large/awkward numbers. Can someone help me with this?

int **matrix_mult( int **a, int **b, int nr1, int nc1, int nc2 )
{
    int **c;
    int i,j,k,l;
    c = malloc(sizeof(int *)*nr1);

    if (c == NULL){
        printf("Insuff memm");
    }

    for(l=0;l<nr1;l++){
        c[l] = malloc(sizeof(int)*nc1);
        if (c[l] == NULL){
            printf("Insuff memm");
        }

    }//for loop


    for (i=0;i<nr1;i++){
        for (j=0;j<nc2;j++){
            for (k=0;k<nc1;k++){

                c[i][j] = (a[i][k]) * (b[k][j]);
    }
    }
    }
        return( c );  
    }


Are you doing mathematical matrix multiplication? If so shouldn't it be:

for(i = 0; i < nr1; i++)
{
    for(j = 0; j < nc1; j++)
    {
        c[i][k] = 0;

        for(k = 0; k < nc2; k++)
        {
            c[i][k] += (a[i][j]) * (b[j][k]);
        }
    }
}

My full and final solution, tested to produce sensible results (I didn't actually do all the calculations myself manually to check them) and without any sensible niceties such as checking memory allocations work, is:

int **matrix_mult(int **a, int **b, int nr1, int nc1, int nc2)
{
    int **c;
    int i, j, k;

    c = malloc(sizeof(int *) * nr1);

    for (i = 0; i < nr1; i++)
    {
        c[i] = malloc(sizeof(int) * nc2);

        for (k = 0; k < nc2; k++)
        {
            c[i][k] = 0;

            for (j = 0; j < nc1; j++)
            {
                c[i][k] += (a[i][j]) * (b[j][k]);
            }
        }
    }

    return c;
}

There were a few typos in the core of the for loop in my original answer, mostly due to my being mislead by a different answer. These have been corrected for posterity.


If you change c[i][j] = (a[i][k]) * (b[k][j]); to c[i][j] += (a[i][k]) * (b[k][j]); in your code then it will work just fine provided that

  • nr1 is number of rows of matrix a
  • nc1 is the number of columns of the matrix a
  • nc2 is the number of columns of the matrix b

Just be sure that the matrix c is initiated with zeroes. You can just use calloc instead of malloc when allocating space, or memset the allocated array after a call to malloc.

One more tip is to avoid using the letter l when accessing array elements. when tired, you will have hard time noticing errors with l vs 1.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号