Deteminant of a matrix 行列式值
源自於https://www.geeksforgeeks.org/determinant-of-a-matrix/
// C program to find Deteminant of a matrix
#include<stdio.h>
#include<math.h>
// Dimension of input square matrix
#define N 4
// Function to get determinant of matrix
int determinantOfMatrix(int mat[N][N], int n)
{
int num1,num2,det = 1,index,total = 1; // Initialize result
// temporary array for storing row
int temp[n + 1];
//loop for traversing the diagonal elements
for(int i = 0; i < n; i++)
{
index = i; // intialize the index
//finding the index which has non zero value
while(mat[index][i] == 0 && index < n) {
index++;
}
if(index == n) // if there is non zero element
{
// the determinat of matrix as zero
continue;
}
if(index != i)
{
//loop for swaping the diagonal element row and index row
for(int j = 0; j < n; j++)
{
//swap(mat[index][j],mat[i][j]);
int tmp=mat[i][j];
mat[i][j]=mat[index][j];
mat[index][j]=tmp;
//determinant sign changes when we shift rows
//go through determinant properties
det = det*pow(-1,index-i);
}
}
//storing the values of diagonal row elements
for(int j = 0; j < n; j++)
{
temp[j] = mat[i][j];
}
//traversing every row below the diagonal element
for(int j = i+1; j < n; j++)
{
num1 = temp[i]; //value of diagonal element
num2 = mat[j][i]; //value of next row element
//traversing every column of row
// and multiplying to every row
for(int k = 0; k < n; k++)
{
//multiplying to make the diagonal
// element and next row element equal
mat[j][k] = (num1 * mat[j][k]) - (num2 * temp[k]);
}
total = total * num1; // Det(kA)=kDet(A);
}
}
//mulitplying the diagonal elements to get determinant
for(int i = 0; i < n; i++)
{
det = det * mat[i][i];
}
return (det/total); //Det(kA)/k=Det(A);
}
// Driver code
int main()
{
/* int mat[N][N] = {{6, 1, 1},
{4, -2, 5},
{2, 8, 7}}; */
int mat[N][N] = {{1, 0, 2, -1},
{3, 0, 0, 5},
{2, 1, 4, -3},
{1, 0, 5, 0}
};
/*int mat[N][N] = {{1, 2},
{3, 2} }; */
printf("Determinant of the matrix is : %d",
determinantOfMatrix(mat, N));
return 0;
}
輸出結果
Determinant of the matrix is : -30
訂閱:
張貼留言 (Atom)
2024_09 作業3 以Node-Red 為主
2024_09 作業3 (以Node-Red 為主 Arduino 可能需要配合修改 ) Arduino 可能需要修改的部分 1)mqtt broker 2) 主題Topic (發行 接收) 3) WIFI ssid , password const char br...
-
python pip 不是内部或外部命令 -- 解決方法 要安裝 Pyqt5 1. 首先,開啟命令提示字元。 2. 輸入 pip3 install pyqt5 好像不能執行 ! ! 錯誤顯示 : ‘ pip3 ’ 不是內部或外部命令、可執行的程式或批...
-
課程講義 下載 11/20 1) PPT 下載 + 程式下載 http://www.mediafire.com/file/cru4py7e8pptfda/106%E5%8B%A4%E7%9B%8A2-1.rar 11/27 2) PPT 下載...
-
• 認 識 PreFix、InFix、PostFix PreFix(前序式):* + 1 2 + 3 4 InFix(中序式): (1+2)*(3+4) PostFix(後序式):1 2 + 3 4 + * 後 序式的運算 例如: 運算時由 後序式的...
沒有留言:
張貼留言