Link to home
Start Free TrialLog in
Avatar of 96404918
96404918

asked on

How to inverse a matrix in VBA ?

I want to inverse a matrix which is in a variable by using the Excel funcion MINVERSE().

Example :

Sub InversionMatrice()
Dim Matrice(1 to 4, 1 to 4) As Double, Inverse(1 to 4, 1 to 4) As Double, i As Integer, j As Integer
For i=1 to 4
   For j=1 to 4
      Matrice(i,j)=...
   Next
Next
Inverse=Application.Minverse(Matrice)
End Sub

But it doesn't work !!! Why ???
Avatar of rantanen
rantanen

MINVERSE is an array function and an assignment what you are trying to do is not allowed. You have to use a sheet as a "middleman" here, eg.

Sub InversionMatrice()
    Dim Matrice(1 To 4, 1 To 4) As Double, Inverse(1 To 4, 1 To 4) As Double, i As Integer, j As Integer
    For i = 1 To 4
        For j = 1 To 4
            Matrice(i, j) = Rnd ' Fill matrice with random numbers
            ActiveSheet.Cells(i, j) = Matrice(i, j)
        Next
    Next
    Range("A6:D9").Select
    Selection.FormulaArray = "=MINVERSE(R[-5]C:R[-2]C[3])"
    For i = 1 To 4
        For j = 1 To 4
            Inverse(i, j) = ActiveSheet.Cells(i + 5, j)
        Next
    Next
End Sub

Avatar of 96404918

ASKER

Thanks for your answer, but I wanted to do it by another way.
ASKER CERTIFIED SOLUTION
Avatar of rantanen
rantanen

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Dear Rantanen,

NOTHING is impossible !!!

I finally succeed in what I wanted to do : inversing a matrix
with VBA and without using an intermediate worksheet.

The solution was to declare the variable Inverse as VARIANT and then to write (as I first said) :

Inverse=Application.MInverse(Matrice)
I am ashamed (making that claim) and grateful (for you telling me). I have tried to learn never to say never, but...

I don't know how to give you back your points, because I'd really like to do that. If you ever feel like asking something and still have a little trust left in me, e-mail me at Lasse.Rantanen@sci.fi.