1

I am a complete newbie of C. I am trying to write a function to multiply two matrices togheter. I will only deal with 2x2's, so I am going to enumerate them. My idea was to have a float 2x2 as a result. Currently I have this,but I don't know how to properly fix it. Any help will be very much appreciated,thank you.

float [][] product2(float A[2][2], float B[2][2]){ //works only on 2x2's!
    float C[2][2];
    C[0][0]=A[0][0]*B[0][0]+A[0][1]*B[1][0];
    C[0][1]=A[0][0]*B[0][1]+A[0][1]*B[1][1];
    C[1][0]=A[1][0]*B[0][0]+A[1][1]*B[1][0];
    C[1][1]=A[1][0]*B[0][1]+A[1][1]*B[1][1];
    return C;
}

EDIT:

I would like to avoid using an input matrix to get the output, if possible. Would this 2nd iteration work?

float* traspose(float A[]){ // Metodo 1
float B[4];
B[1]=A[2];
B[2]=A[1];
return B;

}

I don't get any error from compiler, but is it legit?

Pellicc
  • 11
  • 2
  • You can't return a `float[2][2]`, or any *local* arrays. https://stackoverflow.com/questions/29088462/why-you-cannot-return-fixed-size-const-array-in-c – unDeadHerbs Dec 01 '19 at 18:06

1 Answers1

1

I am still learning C myself but I tried the same problem before and this is my solution.

void multiply(int array1[2][2],int array2[2][2],int array3[2][2]){
    for(int i=0; i<2; i++){
        for(int j=0; j<2; j++){
            for(int k=0; k<2;k++){
                array3[i][j] += array1[i][k] * array2[k][j];
            }
        }
    }
}

Where a product of matrix multiplication as also a matrix you should use a third matrix to store the result and this would be array3, thus eliminating the need for a return type hence using void as the return type. the first 2 loops are used to loop over the array3 and the inner most loop (k) is used to loop over the multiplication points in the matrices.

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
karimkohel
  • 96
  • 1
  • 8