In ILNumerics, I want to inverting a matrix A. The result is matrix B. Here is my code:
ILArray<double> data = ILSpecialData.sinc(50, 50);
ILArray<double> data2 = ILMath.zeros(50, 50);
ILMath.invert(data, data2);
The method is:
ILMath.invert Method (ILInArray<Double>, ILOutArray<Double>)
public static void invert(
ILInArray<double> A,
ILOutArray<double> outArray
)
but I get the zero matrix in matrix B (data2) instead of an inversion of matrix A (data). What should I do to fix this?
If it because I had use ILArray instead of ILInArray and ILOutArray, how to use this matrices?
How to use ILMath.invert
ILMath.invert
does not invert matrices but the elements of an array! See the solution below if you need to invert a matrix. Here is the literal answer to your question. Suppose, we have a matrix A
:
ILArray<double> A = ILMath.counter(2,3);
> A
> <Double> [2,3]
> [0]: 1 3 5
> [1]: 2 4 6
The invert
function is used internally to realize expressions like -A
, i.e. the inversion of the elements of A:
> -A
> <Double> [2,3]
> [0]: -1 -3 -5
> [1]: -2 -4 -6
If you would want to call it directy (not recommended), you could go like that:
ILArray<double> data = ILSpecialData.sinc(3, 3);
ILArray<double> data2 = 0; // just some initialization
ILMath.invert(data,data2); // invert elements of data, return in data2
> data
> <Double> [3,3]
> [0]: (:,:) 1e-002 *
> [1]: 5,7765 5,0334 5,0334
> [2]: 5,0334 6,0334 6,0334
> [3]: 5,0334 6,0334 6,0334
>
> data2
> <Double> [3,3]
> [0]: (:,:) 1e-002 *
> [1]: -5,7765 -5,0334 -5,0334
> [2]: -5,0334 -6,0334 -6,0334
> [3]: -5,0334 -6,0334 -6,0334
Solution: how to invert a matrix
For
I want to invert a matrix A
you need to use ILMath.linsolve()
instead. Linsolve is used to solve linear equation systems. The inversion of a matrix is the most expensive way of solving such an equation system. Often one can prevent from such an expensive operation. Linsolve does that for you. It first tries to use cheaper options to solve the equation system before falling back to the matrix inversion.
If you are certain, that the full inversion is needed, just provide ILMath.eye()
as 2nd argument to ILMath.linsolve
:
ILArray<double> A = ILMath.rand(5,5);
ILArray<double> B = ILMath.linsolve(A, ILMath.eye(5, 5));
In order to proove that B really is the inverse of A, you could multiply A
and B
and should get an identity matrix:
> ILMath.multiply(A, B)
> <Double> [5,5]
> [0]: 1 0,0000 0,0000 0,0000 0
> [1]: 0,0000 1,0000 0,0000 0,0000 0,0000
> [2]: 0,0000 0,0000 1,0000 0,0000 0,0000
> [3]: 0,0000 0,0000 0,0000 1 0
> [4]: 0,0000 0,0000 0,0000 0 1,0000
Note, some elements differ slightly from zero due to rounding errors. The error is small though:
> ILMath.norm(C - ILMath.eye(5,5))
> <Double> (:,:) 1e-016 *
> 5,3541