2019年5月29日 星期三

Deteminant of a matrix 行列式值

Deteminant of a matrix 行列式值

#include <stdio.h>
#include <math.h>

#define N 3

int determinantOfMatrix(int mat[N][N], int n);
void display(int mat[N][N], int row, int col);

int main(void)
{
int matrix[N][N] =
{
{6, 1, 1 },
{4, -2, 5},
{2, 8, 7 }
};

display(matrix, N, N);

    int determinant = determinantOfMatrix(matrix, N);

printf("Determinant of the matrix is: %d\n", determinant);

return 0;
}

int determinantOfMatrix(int mat[N][N], int n)
{
    int det=0, p, h, k, i, j, temp[N][N];

    if (n == 1)
    {
    return mat[0][0];
    }
    else if (n == 2)
    {
        det = (mat[0][0] * mat[1][1] - mat[0][1] * mat[1][0]);

        return det;
    }
else {
for (p = 0; p < n; p++) {
h = 0;
k = 0;

for (i = 1; i < n; i++) {
for (j = 0; j < n; j++) {
if (j==p) {
continue;
}

temp[h][k] = mat[i][j];
k++;

if (k == n-1) {
h++;
k = 0;
}
}
}

det = det + mat[0][p] * pow(-1, p) * determinantOfMatrix(temp, n-1);
}

return det;
}
}

void display(int mat[N][N], int row, int col)
{
    int i;
    int j;

    for (i = 0; i < row; i++)
    {
        for (j = 0; j < col; j++)
        {
        printf("%d\t", mat[i][j]);
        }

        printf("\n");
    }
}


輸出畫面
6 1 1
4 -2 5
2 8 7
Determinant of the matrix is: -306

Deteminant of a matrix 行列式值

Deteminant of a matrix 行列式值

//C program to find determinant of nxn matrix.
#include <stdio.h>
#include <math.h>

int a[20][20],m;
int determinant(int f[20][20],int a);
int main()
{
  int i,j;
  printf("\n\nEnter order of matrix : ");
  scanf("%d",&m);
  printf("\nEnter the elements of matrix\n");
  for(i=1;i<=m;i++)
  {
  for(j=1;j<=m;j++)
  {
  printf("a[%d][%d] = ",i,j);
  scanf("%d",&a[i][j]);
  }
  }
  printf("\n\n---------- Matrix A is --------------\n");   
  for(i=1;i<=m;i++)
     {
          printf("\n");
          for(j=1;j<=m;j++)
          {   
               printf("\t%d \t",a[i][j]);
          }
     }
  printf("\n \n");
  printf("\n Determinant of Matrix A is %d .",determinant(a,m));
  return 0;
}


int determinant(int f[20][20],int x)
{
  int pr,c[20],d=0,b[20][20],j,p,q,t;
  if(x==2)
  {
    d=0;
    d=(f[1][1]*f[2][2])-(f[1][2]*f[2][1]);
    return(d);
   }
  else
  {
    for(j=1;j<=x;j++)
    {       
      int r=1,s=1;
      for(p=1;p<=x;p++)
        {
          for(q=1;q<=x;q++)
            {
              if(p!=1&&q!=j)
              {
                b[r][s]=f[p][q];
                s++;
                if(s>x-1)
                 {
                   r++;
                   s=1;
                  }
               }
             }
         }
     for(t=1,pr=1;t<=(1+j);t++)
     pr=(-1)*pr;
     c[j]=pr*determinant(b,x-1);
     }
     for(j=1,d=0;j<=x;j++)
     {
       d=d+(f[1][j]*c[j]);
      }
     return(d);
   }
}

輸入資料
4
1  0  2 -1
3  0  0  5
2  1  4 -3
1  0  5  0
   

輸出畫面
Enter order of matrix :
Enter the elements of matrix
a[1][1] = a[1][2] = a[1][3] = a[1][4] = a[2][1] = a[2][2] = a[2][3] = a[2][4] = a[3][1] = a[3][2] = a[3][3] = a[3][4] = a[4][1] = a[4][2] = a[4][3] = a[4][4] =

---------- Matrix A is --------------

1 0 2 -1
3 0 0 5
2 1 4 -3
1 0 5 0


 Determinant of Matrix A is 30 .

Deteminant of a matrix 行列式值

Deteminant of a matrix 行列式值

源自於
https://www.bragitoff.com/2018/02/determinant-matrix-c-program/

/**************************************************
******DETERMINANT FROM GAUSS ELIMINATION***********
**************************************************/
#include<stdio.h>
#include<math.h>
/*******
Function that calculates the determinant of a square matrix using Gauss-Elimination :
Pass the square matrix as a parameter, and calculate and return the dete
Parameters: order(n),matrix[n][n]
********/
double determinant(int n, double a[n][n]){
double det=1;
int i,swapCount;
swapCount=gauEl(n,n,a);
for(i=0;i<n;i++){
det =det*a[i][i];
}
return det*pow(-1,swapCount);
}
/********
Function that perform Gauss Elimination
Pass the square matrix as a parameter, and calculate and store the upperTriangular(Gauss-Eliminated Matrix) in it
Parameters: rows(m),columns(n),matrix[m][n]
********/
int gauEl(int m, int p, double a[m][p]){
int i,j,k;
int swapCount=0;
for(i=0;i<m-1;i++){
//Partial Pivoting
for(k=i+1;k<m;k++){
//If diagonal element(absolute vallue) is smaller than any of the terms below it
if(fabs(a[i][i])<fabs(a[k][i])){
//Swap the rows
swapCount++;
for(j=0;j<p;j++){
double temp;
temp=a[i][j];
a[i][j]=a[k][j];
a[k][j]=temp;
}
}
}
//Begin Gauss Elimination
for(k=i+1;k<m;k++){
double  term=a[k][i]/ a[i][i];
for(j=0;j<p;j++){
a[k][j]=a[k][j]-term*a[i][j];
}
}
}
return swapCount;
}

/*******
Function that prints the elements of a matrix row-wise
Parameters: rows(m),columns(n),matrix[m][n]
*******/
void printMatrix(int m, int n, double matrix[m][n]){
int i,j;
for(i=0;i<m;i++){
for(j=0;j<n;j++){
printf("%0.2lf\t",matrix[i][j]);
}
printf("\n");
}
}
/*******
Function that copies the elements of a matrix to another matrix
Parameters: rows(m),columns(n),matrix1[m][n] , matrix2[m][n]
*******/
void copyMatrix(int m, int n, double matrix1[m][n], double matrix2[m][n]){
int i,j;
for(i=0;i<m;i++){
for(j=0;j<n;j++){
matrix2[i][j]=matrix1[i][j];
}
}
}

int main(){
int n,i,j;
n=4;
printf("Enter the order of the matrix:\n(No. of rows/columns (n))\n");
printf("%d",n);
//Declare a matrix to store the user given matrix
/*
double a[3][3]= {{6., 1, 1},
                     {4., -2, 5},
                     {2., 8, 7}};
    */
    double a[4][4] = { {1, 0, 2, -1},
                    {3, 0, 0, 5},
                    {2, 1, 4, -3},
                    {1, 0, 5, 0}};
   
    /*double a[n][n] = {{1, 2},
                     {3, 2} }; */



printf("\nEnter the elements of matrix:\n");
    printMatrix(n,n,a);
printf("\nThe determinant using Gauss Eliminiation is:\n\n%0.2lf\n",determinant(n,a));


}

輸出畫面
Enter the order of the matrix:
(No. of rows/columns (n))
4
Enter the elements of matrix:
1.00 0.00 2.00 -1.00
3.00 0.00 0.00 5.00
2.00 1.00 4.00 -3.00
1.00 0.00 5.00 0.00

The determinant using Gauss Eliminiation is:

30.00

2019年5月28日 星期二

Deteminant of a matrix 行列式值

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

Deteminant of a matrix 行列式值

Deteminant of a matrix 

矩陣 A 是方陣(Square Matrix)時才會有行列式值,而其行列式是表為 A 或 det A,其運算之結果是一個純量(Scalar),而非一個矩陣也不是一個向量。

// C program to find Deteminant of a matrix
#include<stdio.h>
#include<math.h>
 
// Dimension of input square matrix
#define N 2
 
// Function to get cofactor of mat[p][q] in temp[][]. n is current
// dimension of mat[][]
void getCofactor(int mat[N][N], int temp[N][N], int p, int q, int n)
{
    int i = 0, j = 0;
 
    // Looping for each element of the matrix
    for (int row = 0; row < n; row++)
    {
        for (int col = 0; col < n; col++)
        {
            //  Copying into temporary matrix only those element
            //  which are not in given row and column
            if (row != p && col != q)
            {
                temp[i][j++] = mat[row][col];
 
                // Row is filled, so increase row index and
                // reset col index
                if (j == n - 1)
                {
                    j = 0;
                    i++;
                }
            }
        }
    }
}
 
/* Recursive function for finding determinant of matrix.
   n is current dimension of mat[][]. */
int determinantOfMatrix(int mat[N][N], int n)
{
    int D = 0; // Initialize result
 
    //  Base case : if matrix contains single element
    if (n == 1)
        return mat[0][0];
 
    int temp[N][N]; // To store cofactors
 
    int sign = 1;  // To store sign multiplier
 
     // Iterate for each element of first row
    for (int f = 0; f < n; f++)
    {
        // Getting Cofactor of mat[0][f]
        getCofactor(mat, temp, 0, f, n);
        D += sign * mat[0][f] * determinantOfMatrix(temp, n - 1);
 
        // terms are to be added with alternate sign
        sign = -sign;
    }
 
    return D;
}
 
/* function for displaying the matrix */
void display(int mat[N][N], int row, int col)
{
    for (int i = 0; i < row; i++)
    {
        for (int j = 0; j < col; j++)
            printf("  %d", mat[i][j]);
        printf("n");
    }
}
 
// Driver program to test above functions
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 : -4

C語言 例題6-8 LU分解法求線性代數解

C語言 例題6-8 LU分解法求線性代數解

Solve the following system of equations using LU Decomposition method:
   \begin{equation*} x_1 + x_2 + x_3 = 1 \end{equation*} \begin{equation*} 4x_1 + 3x_2 - x_3 = 6  \end{equation*} \begin{equation*} 3x_1 + 5x_2 + 3x_3 = 4 \end{equation*}


Solution: Here, we have
A = \begin{bmatrix}   1 & 1 & 1 \\   4 & 3 & -1 \\   3 & 5 & 3  \end{bmatrix} , X = \begin{bmatrix}   x_1 \\   x_2 \\   x_3  \end{bmatrix}  and  C = \begin{bmatrix}   1 \\   6 \\   4  \end{bmatrix} such that A X = C.


Mathematics | L U Decomposition of a System of Linear Equations

源自於 https://www.geeksforgeeks.org/l-u-decomposition-system-linear-equations/
Example:
Solve the following system of equations using LU Decomposition method:
   \begin{equation*} x_1 + x_2 + x_3 = 1 \end{equation*} \begin{equation*} 4x_1 + 3x_2 - x_3 = 6  \end{equation*} \begin{equation*} 3x_1 + 5x_2 + 3x_3 = 4 \end{equation*}


Solution: Here, we have
A = \begin{bmatrix}   1 & 1 & 1 \\   4 & 3 & -1 \\   3 & 5 & 3  \end{bmatrix} , X = \begin{bmatrix}   x_1 \\   x_2 \\   x_3  \end{bmatrix}  and  C = \begin{bmatrix}   1 \\   6 \\   4  \end{bmatrix} such that A X = C.
Now, we first consider \begin{bmatrix}   1 & 1 & 1 \\   4 & 3 & -1 \\   3 & 5 & 3  \end{bmatrix} and convert it to row echelon form using Gauss Elimination Method.
So, by doing
(1)  \begin{equation*} R_2 \to R_2 - 4R_1  \end{equation*}
(2)  \begin{equation*} R_3 \to R_3 - 3R_1   \end{equation*}
we get
\begin{bmatrix}   1 & 1 & 1 \\   4 & 3 & -1 \\   3 & 5 & 3  \end{bmatrix} \sim  \begin{bmatrix}  1 & 1 & 1 \\   0 & -1 & -5 \\   0 & 2 & 0  \end{bmatrix}
Now, by doing
(3)  \begin{equation*} R_3 \to R_3 - (-2)R_2 \end{equation*}


we get
 \sim \begin{bmatrix}   1 & 1 & 1 \\   0 & -1 & -5 \\   0 & 0 & -10  \end{bmatrix}
(Remember to always keep ‘ – ‘ sign in between, replace ‘ + ‘ sign by two ‘ – ‘ signs)
Hence, we get L =  \begin{bmatrix}   1 & 0 & 0 \\   4 & 1 & 0 \\   3 & -2 & 1  \end{bmatrix} and U =  \begin{bmatrix}   1 & 1 & 1 \\   0 & -1 & -5 \\   0 & 0 & -10  \end{bmatrix}
(notice that in L matrix,  l_{21} = 4  is from (1),  l_{31} = 3  is from (2) and  l_{32} = -2  is from (3))
Now, we assume Z  = \begin{bmatrix}   z_1 \\   z_2 \\   z_3   \end{bmatrix} and solve L Z = C.
 \begin{bmatrix}   1 & 0 & 0 \\   4 & 1 & 0 \\   3 & -2 & 1  \end{bmatrix}  \begin{bmatrix}   z_1 \\   z_2 \\   z_3   \end{bmatrix}  = \begin{bmatrix}   1 \\   6 \\   4  \end{bmatrix}
So, we have  z_1 = 1 ,   4z_1 + z_2 = 6 ,   3z_1 - 2z_2 + z_3 = 4  .
Solving, we get  z_1 =  1  z_2 = 2  and  z_3 = 5  .
Now, we solve U X = Z


 \begin{bmatrix}   1 & 1 & 1 \\   0 & -1 & -5 \\   0 & 0 & -10  \end{bmatrix} \begin{bmatrix}   x_1 \\   x_2 \\   x_3  \end{bmatrix}  = \begin{bmatrix}   1 \\   2 \\   5  \end{bmatrix}
Therefore, we get  x_1 + x_2 + x_3 = 1  ,  -x_2 - 5x_3 = 2 , -10x_3 = 5 .
Thus, the solution to the given system of linear equations is  x_1 = 1   x_2 = 0.5   x_3 =  -0.5  and hence the matrix X = \begin{bmatrix}   1 \\   0.5 \\   -0.5  \end{bmatrix}

/************** LU Decomposition for solving linear equations ***********/
/*
[A] = [L][U]
where, L is the lower triangular matrix and
U is the upper triangular matrix.
The elements of these three matrices row-wise are:

[A] = { a11, a12, a13,
        a21, a22, a23,
        a31, a32, a33 }

[L] = {  1,   0,  0,
       l21,   1,  0,
       l31, l32,  1}
      
[U] = {u11, u12, u13,
       0  , u22, u23,
       0  ,   0, u33}


-1.00x1    1.00x2  2.00x3  = 2.00
 3.00x1   -1.00x2  1.00x3  = 6.00
-1.00x1    3.00x2  4.00x3  = 4.00

x3 = 2.000   x2 = -1.000   x1 = 1.000
*/

#include<stdio.h>
#include<math.h>
int main()
{
    int n,i,k,j,p;
    float l[10][10]={0},u[10][10]={0},sum,z[10]={0},x[10]={0};
    n=3;
  
    printf("The order of square matrix: %2d\n",n);
    float a[3][3]= { {  1,  1,  1 },
                     {  4,  3, -1 },
                     {  3,  5,  3 } };
                    
  
    float b[3]= {1,6,4};
  
    for(i=0;i<n;i++)
    {
        printf("\nRow%1d\t",i);
        for(j=0;j<n;j++)
            printf("%0.2lf\t\t",a[i][j]);

    }
  
    printf("\n\nelements of b matrix\n");
    for(i=0;i<n;i++)
        printf("%0.2lf\t\t",b[i]);
      
    //********** LU decomposition *****//
    for(k=0;k<n;k++)
    {
        u[k][k]=1;
        for(i=k;i<n;i++)
        {
            sum=0;
            for(p=0;p<k;p++)
                sum+=l[i][p]*u[p][k];
            l[i][k]=a[i][k]-sum;
        }

        for(j=k+1;j<n;j++)
        {
            sum=0;
            for(p=0;p<k;p++)
                sum+=l[k][p]*u[p][j];
            u[k][j]=(a[k][j]-sum)/l[k][k];
        }
    }
    
    //******** Displaying LU matrix**********//
    printf("\n\nLU matrix is : \n");
    //==================L matrix===============
    for(i=0;i<n;i++)
    {
        for(j=0;j<n;j++)
            printf("%0.2lf\t",l[i][j]);
        printf("\n");
    }
    printf("\n\n");
    //==================U matrix===============
    for(i=0;i<n;i++)
    {
        for(j=0;j<n;j++)
            printf("%0.2lf\t",u[i][j]);
        printf("\n");
    }

    //***** FINDING Z; LZ=b*********//

    for(i=0;i<n;i++)
    {                                        //forward subtitution method
        sum=0;
        for(p=0;p<i;p++)
        sum+=l[i][p]*z[p];
        z[i]=(b[i]-sum)/l[i][i];
    }
    //********** FINDING X; UX=Z***********//

    for(i=n-1;i>=0;i--)
    {
        sum=0;
        for(p=n-1;p>=i;p--)
            sum+=u[i][p]*x[p];
        x[i]=(z[i]-sum)/u[i][i];
    }
    //*********** DISPLAYING SOLUTION**************//
    printf("\n\nSet of solution is\n");
    for(i=0;i<n;i++)
        printf("%0.2lf\t",x[i]);

    return 0;
}

輸出畫面
The order of square matrix:  3

Row0 1.00 1.00 1.00
Row1 4.00 3.00 -1.00
Row2 3.00 5.00 3.00

elements of b matrix
1.00 6.00 4.00

LU matrix is : 
1.00 0.00 0.00
4.00 -1.00 0.00
3.00 2.00 -10.00


1.00 1.00 1.00
0.00 1.00 5.00
0.00 0.00 1.00


Set of solution is
1.00 0.50 -0.50

2024_09 作業3 以Node-Red 為主

 2024_09 作業3  (以Node-Red 為主  Arduino 可能需要配合修改 ) Arduino 可能需要修改的部分 1)mqtt broker  2) 主題Topic (發行 接收) 3) WIFI ssid , password const char br...