1 /* ----------------------------------------------------------------------
2  * Project:      CMSIS DSP Library
3  * Title:        arm_mat_inverse_f32.c
4  * Description:  Floating-point matrix inverse
5  *
6  * $Date:        23 April 2021
7  * $Revision:    V1.9.0
8  *
9  * Target Processor: Cortex-M and Cortex-A cores
10  * -------------------------------------------------------------------- */
11 /*
12  * Copyright (C) 2010-2021 ARM Limited or its affiliates. All rights reserved.
13  *
14  * SPDX-License-Identifier: Apache-2.0
15  *
16  * Licensed under the Apache License, Version 2.0 (the License); you may
17  * not use this file except in compliance with the License.
18  * You may obtain a copy of the License at
19  *
20  * www.apache.org/licenses/LICENSE-2.0
21  *
22  * Unless required by applicable law or agreed to in writing, software
23  * distributed under the License is distributed on an AS IS BASIS, WITHOUT
24  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
25  * See the License for the specific language governing permissions and
26  * limitations under the License.
27  */
28 
29 #include "dsp/matrix_functions.h"
30 #include "dsp/matrix_utils.h"
31 
32 
33 /**
34   @ingroup groupMatrix
35  */
36 
37 /**
38   @defgroup MatrixInv Matrix Inverse
39 
40   Computes the inverse of a matrix.
41 
42   The inverse is defined only if the input matrix is square and non-singular (the determinant is non-zero).
43   The function checks that the input and output matrices are square and of the same size.
44 
45   Matrix inversion is numerically sensitive and the CMSIS DSP library only supports matrix
46   inversion of floating-point matrices.
47 
48   @par Algorithm
49   The Gauss-Jordan method is used to find the inverse.
50   The algorithm performs a sequence of elementary row-operations until it
51   reduces the input matrix to an identity matrix. Applying the same sequence
52   of elementary row-operations to an identity matrix yields the inverse matrix.
53   If the input matrix is singular, then the algorithm terminates and returns error status
54   <code>ARM_MATH_SINGULAR</code>.
55 
56   @par Matrix Inverse of a 3 x 3 matrix using Gauss-Jordan Method
57 
58   \f[
59   \begin{pmatrix}
60    a_{1,1} & a_{1,2} & a_{1,3} & | & 1 & 0 & 0\\
61    a_{2,1} & a_{2,2} & a_{2,3} & | & 0 & 1 & 0\\
62    a_{3,1} & a_{3,2} & a_{3,3} & | & 0 & 0 & 1\\
63   \end{pmatrix}
64   \rightarrow
65   \begin{pmatrix}
66    1 & 0 & 0 & | & x_{1,1} & x_{2,1} & x_{3,1} \\
67    0 & 1 & 0 & | & x_{1,2} & x_{2,2} & x_{3,2} \\
68    0 & 0 & 1 & | & x_{1,3} & x_{2,3} & x_{3,3} \\
69   \end{pmatrix}
70   \f]
71  */
72 
73 /**
74   @addtogroup MatrixInv
75   @{
76  */
77 
78 /**
79   @brief         Floating-point matrix inverse.
80   @param[in]     pSrc      points to input matrix structure. The source matrix is modified by the function.
81   @param[out]    pDst      points to output matrix structure
82   @return        execution status
83                    - \ref ARM_MATH_SUCCESS       : Operation successful
84                    - \ref ARM_MATH_SIZE_MISMATCH : Matrix size check failed
85                    - \ref ARM_MATH_SINGULAR      : Input matrix is found to be singular (non-invertible)
86  */
arm_mat_inverse_f32(const arm_matrix_instance_f32 * pSrc,arm_matrix_instance_f32 * pDst)87 arm_status arm_mat_inverse_f32(
88   const arm_matrix_instance_f32 * pSrc,
89         arm_matrix_instance_f32 * pDst)
90 {
91   float32_t *pIn = pSrc->pData;                  /* input data matrix pointer */
92   float32_t *pOut = pDst->pData;                 /* output data matrix pointer */
93 
94   float32_t *pTmp;
95   uint32_t numRows = pSrc->numRows;              /* Number of rows in the matrix  */
96   uint32_t numCols = pSrc->numCols;              /* Number of Cols in the matrix  */
97 
98 
99   float32_t pivot = 0.0f, newPivot=0.0f;                /* Temporary input values  */
100   uint32_t selectedRow,pivotRow,i, rowNb, rowCnt, flag = 0U, j,column;      /* loop counters */
101   arm_status status;                             /* status of matrix inverse */
102 
103 #ifdef ARM_MATH_MATRIX_CHECK
104 
105   /* Check for matrix mismatch condition */
106   if ((pSrc->numRows != pSrc->numCols) ||
107       (pDst->numRows != pDst->numCols) ||
108       (pSrc->numRows != pDst->numRows)   )
109   {
110     /* Set status as ARM_MATH_SIZE_MISMATCH */
111     status = ARM_MATH_SIZE_MISMATCH;
112   }
113   else
114 
115 #endif /* #ifdef ARM_MATH_MATRIX_CHECK */
116 
117   {
118     /*--------------------------------------------------------------------------------------------------------------
119      * Matrix Inverse can be solved using elementary row operations.
120      *
121      *  Gauss-Jordan Method:
122      *
123      *      1. First combine the identity matrix and the input matrix separated by a bar to form an
124      *        augmented matrix as follows:
125      *                      _                  _         _         _
126      *                     |  a11  a12 | 1   0  |       |  X11 X12  |
127      *                     |           |        |   =   |           |
128      *                     |_ a21  a22 | 0   1 _|       |_ X21 X21 _|
129      *
130      *      2. In our implementation, pDst Matrix is used as identity matrix.
131      *
132      *      3. Begin with the first row. Let i = 1.
133      *
134      *      4. Check to see if the pivot for row i is zero.
135      *         The pivot is the element of the main diagonal that is on the current row.
136      *         For instance, if working with row i, then the pivot element is aii.
137      *         If the pivot is zero, exchange that row with a row below it that does not
138      *         contain a zero in column i. If this is not possible, then an inverse
139      *         to that matrix does not exist.
140      *
141      *      5. Divide every element of row i by the pivot.
142      *
143      *      6. For every row below and  row i, replace that row with the sum of that row and
144      *         a multiple of row i so that each new element in column i below row i is zero.
145      *
146      *      7. Move to the next row and column and repeat steps 2 through 5 until you have zeros
147      *         for every element below and above the main diagonal.
148      *
149      *      8. Now an identical matrix is formed to the left of the bar(input matrix, pSrc).
150      *         Therefore, the matrix to the right of the bar is our solution(pDst matrix, pDst).
151      *----------------------------------------------------------------------------------------------------------------*/
152 
153     /* Working pointer for destination matrix */
154     pTmp = pOut;
155 
156     /* Loop over the number of rows */
157     rowCnt = numRows;
158 
159     /* Making the destination matrix as identity matrix */
160     while (rowCnt > 0U)
161     {
162       /* Writing all zeroes in lower triangle of the destination matrix */
163       j = numRows - rowCnt;
164       while (j > 0U)
165       {
166         *pTmp++ = 0.0f;
167         j--;
168       }
169 
170       /* Writing all ones in the diagonal of the destination matrix */
171       *pTmp++ = 1.0f;
172 
173       /* Writing all zeroes in upper triangle of the destination matrix */
174       j = rowCnt - 1U;
175       while (j > 0U)
176       {
177         *pTmp++ = 0.0f;
178         j--;
179       }
180 
181       /* Decrement loop counter */
182       rowCnt--;
183     }
184 
185     /* Loop over the number of columns of the input matrix.
186        All the elements in each column are processed by the row operations */
187 
188     /* Index modifier to navigate through the columns */
189     for(column = 0U; column < numCols; column++)
190     {
191       /* Check if the pivot element is zero..
192        * If it is zero then interchange the row with non zero row below.
193        * If there is no non zero element to replace in the rows below,
194        * then the matrix is Singular. */
195 
196       pivotRow = column;
197 
198       /* Temporary variable to hold the pivot value */
199       pTmp = ELEM(pSrc,column,column) ;
200       pivot = *pTmp;
201       selectedRow = column;
202 
203       /* Find maximum pivot in column */
204 
205         /* Loop over the number rows present below */
206 
207       for (rowNb = column+1; rowNb < numRows; rowNb++)
208       {
209           /* Update the input and destination pointers */
210           pTmp = ELEM(pSrc,rowNb,column);
211           newPivot = *pTmp;
212           if (fabsf(newPivot) > fabsf(pivot))
213           {
214             selectedRow = rowNb;
215             pivot = newPivot;
216           }
217       }
218 
219       /* Check if there is a non zero pivot element to
220        * replace in the rows below */
221       if ((pivot != 0.0f) && (selectedRow != column))
222       {
223 
224             SWAP_ROWS_F32(pSrc,column, pivotRow,selectedRow);
225             SWAP_ROWS_F32(pDst,0, pivotRow,selectedRow);
226 
227 
228             /* Flag to indicate whether exchange is done or not */
229             flag = 1U;
230        }
231 
232 
233 
234 
235 
236       /* Update the status if the matrix is singular */
237       if ((flag != 1U) && (pivot == 0.0f))
238       {
239         return ARM_MATH_SINGULAR;
240       }
241 
242 
243       /* Pivot element of the row */
244       pivot = 1.0f / pivot;
245 
246       SCALE_ROW_F32(pSrc,column,pivot,pivotRow);
247       SCALE_ROW_F32(pDst,0,pivot,pivotRow);
248 
249 
250       /* Replace the rows with the sum of that row and a multiple of row i
251        * so that each new element in column i above row i is zero.*/
252 
253       rowNb = 0;
254       for (;rowNb < pivotRow; rowNb++)
255       {
256            pTmp = ELEM(pSrc,rowNb,column) ;
257            pivot = *pTmp;
258 
259            MAS_ROW_F32(column,pSrc,rowNb,pivot,pSrc,pivotRow);
260            MAS_ROW_F32(0     ,pDst,rowNb,pivot,pDst,pivotRow);
261 
262 
263       }
264 
265       for (rowNb = pivotRow + 1; rowNb < numRows; rowNb++)
266       {
267            pTmp = ELEM(pSrc,rowNb,column) ;
268            pivot = *pTmp;
269 
270            MAS_ROW_F32(column,pSrc,rowNb,pivot,pSrc,pivotRow);
271            MAS_ROW_F32(0     ,pDst,rowNb,pivot,pDst,pivotRow);
272 
273       }
274 
275     }
276 
277     /* Set status as ARM_MATH_SUCCESS */
278     status = ARM_MATH_SUCCESS;
279 
280     if ((flag != 1U) && (pivot == 0.0f))
281     {
282       pIn = pSrc->pData;
283       for (i = 0; i < numRows * numCols; i++)
284       {
285         if (pIn[i] != 0.0f)
286             break;
287       }
288 
289       if (i == numRows * numCols)
290         status = ARM_MATH_SINGULAR;
291     }
292   }
293 
294   /* Return to application */
295   return (status);
296 }
297 /**
298   @} end of MatrixInv group
299  */
300