I wrote a program which computes determinant of 3x3-matrix with Sarrus' Method because someone accessed my blog in order to find a program computing determinant of 3x3-matrix. This program is written in C.
Of course, we can calculate it by Cofactor Expansion, but Sarrus' Method is much easier than it. So, I use Sarrus' Method.
Function to Compute Determinant of Matrix
int det(int a[3][3]) { return a[0][0]*a[1][1]*a[2][2] + a[0][1]*a[1][2]*a[2][0] + a[0][2]*a[1][0]*a[2][1] - a[0][2]*a[1][1]*a[2][0] - a[1][2]*a[2][1]*a[0][0] - a[2][2]*a[0][1]*a[1][0]; }
Main Function for Test
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int a[3][3], i, j; if(argc == 1) { a[0][0] = 1; a[0][1] = 2; a[0][2] = 3; a[1][0] = 4; a[1][1] = 5; a[1][2] = 6; a[2][0] = 7; a[2][1] = 8; a[2][2] = 9; } else if(argc == 10) { for(i=0; i<3; i++) for(j=0; j<3; j++) a[i][j] = atoi(argv[3*i+j+1]); } else { printf("Usage:\n"); printf("./a.out\n"); printf(" or\n"); printf("./a.out a11 a12 a13 a21 a22 a23 a31 a32 a33"); } printf("a =\n"); for(i=0; i<3; i++) { for(j=0; j<3; j++) { printf("%3d", a[i][j]); } printf("\n"); } printf("\n"); printf("det(a) = %d\n", det(a)); return 0; }
Output
$ ./det a = 1 2 3 4 5 6 7 8 9 det(a) = 0
$ ./det 1 6 -2 5 -3 4 -1 -2 4 a = 1 6 -2 5 -3 4 -1 -2 4 det(a) = -122
Main Function for Test(Simple Version)
I prepare simple version of test function for beginners of programming.
#include <stdio.h> int main(int argc, char *argv[]) { int a[3][3]; a[0][0] = 1; a[0][1] = 2; a[0][2] = 3; a[1][0] = 4; a[1][1] = 5; a[1][2] = 6; a[2][0] = 7; a[2][1] = 8; a[2][2] = 9; printf("det(a) = %d\n", det(a)); return 0; }
Original Text(Japanese)
No comments:
Post a Comment