VBA:矩阵逆

时间:2016-01-20 08:32:58

标签: excel vba

我试图做一些简单的事情:在单元格A1:C3中取一个矩阵,然后将反转写入单元格E1:G3。这不起作用,我得到的错误是"类型不匹配"。为什么呢?

Sub f()
    Range("E1:G3").Value = g(Range("A1:C3"))
End Sub

Function g(m As Range) As Double()
    Dim r As Integer, c As Integer
    Dim minv() As Double
    r = m.Rows.Count
    c = m.Columns.Count
    ReDim minv(1 To r, 1 To c)
    minv = WorksheetFunction.MInverse(m)
    g = minv
End Function

2 个答案:

答案 0 :(得分:2)

WorksheetFunction.MInverse返回的Variant包含的矩阵不是Double数组。 https://msdn.microsoft.com/en-us/library/office/ff841265.aspx因此Double数组和ReDim都不是必需的。

但还有另一个问题。并非所有矩阵都是可逆的。使用不可反转的矩阵WorksheetFunction.MInverse将引发错误。最好使用Application.MInverse。这将返回#NUM!错误,因为=MINV()也会这样做。

Sub f()
    Range("E1:G3").Value = g(Range("A1:C3"))
End Sub

Function g(m As Range) As Variant
    Dim minv As Variant
    minv = Application.MInverse(m)
    g = minv
End Function

如果函数必须返回Double()数组,则必须将Variant转换为该数组。

Function g(m As Range) As Double()
 Dim vMinv As Variant
 Dim dMinv() As Double

 vMinv = Application.MInverse(m)

 If IsError(vMinv) Then Exit Function 'what shall the Double() contain if m is not invertable?

 On Error Resume Next
 d1 = UBound(vMinv, 1)
 d2 = UBound(vMinv, 2)
 On Error GoTo 0

 'vMinv is one-dimensional
 If IsEmpty(d2) Then
  ReDim dMinv(1 To d1)
  For i = 1 To d1
   dMinv(i) = vMinv(i)
  Next
  g = dMinv
  Exit Function
 End If

 'vMinv is two-dimensional
 ReDim dMinv(1 To d1, 1 To d2)
 For i = 1 To d1
  For j = 1 To d2
   dMinv(i, j) = vMinv(i, j)
  Next
 Next
 g = dMinv

End Function

但问题是:如果m不可反转,Double()包含什么?它不能包含错误值。

答案 1 :(得分:0)

VBA 函数只能返回一维数组。如果你想在两个维度上拥有它,你必须通过参考来做。这里我使用了一个 sub,byReference 在 VBA 中是默认的。

sub ret(a())
  redim A(2,2)
  A(2,2)=2
end sub


dim A() 
ret a
debug.print A(2,2)