Doing a small program for calculating 2x2 matrix inverses. It inverts fine, however when I added an extra function to do an indentity matrix check, it goes a bit haywire, and the reason I found is due to the negative value from the main function not getting passed into the function, essentially only the value get's passed, not the sign.
Code:
//Matrix
#include<stdio.h>
void matMul(float org[4], float inv[4]);
int main (void) {
float mat[4] = {0,0,0,0}; //USER ENTERED MATRIX
float coef;
printf("Enter numbers\n");
scanf("%f %f %f %f", &mat[0], &mat[1], &mat[2], &mat[3]);
if((mat[0]*mat[3]) - (mat[1]*mat[2]) != 0){
coef = 1/((mat[0]*mat[3]) - (mat[1]*mat[2]));
}
else {
printf("Division by zero error\n");
return 0;
}
float mat2[4] = {0,0,0,0}; //CALCULATION FOR THE INVERTED MATRIX
mat2[0] = mat[3];
mat2[3]= mat[0];
mat2[2] = mat[2]*-1;
mat2[1] = mat[1]*-1;
printf("\n"); //FURTHER CALCULATION AND PRINTING THE INVERTED MATRIX
printf("Inverted Matrix is:\n");
printf("\n");
printf("|%1.2f %1.2f|\n", mat2[0]*coef, mat2[1]*coef);
printf("|%1.2f %1.2f|\n", mat2[2]*coef, mat2[3]*coef);
printf("\n");
printf("Identity check, y or n?\n");
char c;
getchar();
c = getchar();
while(( c = getchar()) != EOF ) {
if(c == 'n'){
return 0;
}
else if(c == 'y'){ //PASSING THE INVERTED MATRIX AND ORIGINAL MATRIX TO A NEW FUNCTION
matMul(mat,mat2);
}
}
return 0;
}
void matMul(float org[4], float inv[4]){
float ide[4] = {0,0,0,0};
ide[0] = (org[0]*inv[0]) + (org[1]*inv[2]);
ide[1] = (org[0]*inv[1]) + (org[1]*inv[3]);
ide[2] = (org[2]*inv[0]) + (org[3]*inv[2]);
ide[3] = (org[2]*inv[1]) + (org[3]*inv[3]);
printf("\n");
printf("|%1.2f %1.2f|\n", ide[0], ide[1]);
printf("|%1.2f %1.2f|\n", ide[2], ide[3]);
printf("\n");
}