# LinearAlgebra.inv! not exported, in-place inversion

Why is `inv!()` not exported from LinearAlgebra? What is the fastest and most efficient way to invert a Matrix? I have to invert (I - A) where I is the identity Matrix. In some cases A may be sparse.

``````
Imat = I(10)
Imatx = Imat - rand(10, 10);
y = copy(Imatx);
LinearAlgebra.inv!(lu!(y)) == inv(Imatx)
true

@btime inv(\$Imatx);
1.081 μs (4 allocations: 6.14 KiB)
@btime LinearAlgebra.inv!(lu!(\$y));
1.041 μs (3 allocations: 5.27 KiB)

``````

`LinearAlgebra.inv!` still allocates.

I don’t think there is any way to invert a Matrix without allocating some additional memory.

That being said, actually forming the inverse of matrix is almost never what one should do. What do you need the inverse for, if I may ask? Usually you want to apply to some other vector/matrix and then you should use `/` or `\` for better accuracy

1 Like

Thanks. Yes, I need to multiply the inverse to another (random) matrix.

Then you should just use something like

``````A = I + rand(10,10)
B = rand(10)
A\B # equivalent to inv(A)*B
A/B # equivalent to A*inv(B)
``````

If you need to apply the inverse multiple times, you can factorize the matrix beforehand:

``````Af = factorize(A)
# now use Af instead of A to apply inverse multiple times efficiently
Af\B
``````

If you wish to preallocate outputs of the application of the inverse you can use `ldiv!` and `rdiv!` instead of `\` and `/`.

``````Y = similar(B)
ldiv!(Y, Af, B) # computes Y = inv(Af)*B by overwriting Y
``````

Be careful that you don’t reuse the input matrix for output like `ldiv!(B,Af,B)`!

3 Likes

Great, thanks.

But I still do not understand why `inv!()` is not exported.