簡體   English   中英

模擬Excel MMULT的函數

[英]Function mimicing Excel MMULT

我想創建模仿標准Excel MMULT函數以求矩陣相乘的函數。 我的代碼是:

 Function MatrixMultiplication(Matrix1 As Range, Matrix2 As Range) Dim m1() As Long, m2() As Long, m3() As Long m1 = Matrix1 m2 = Matrix2 If Matrix1 Is Nothing Or Matrix2 Is Nothing Then GoTo Err1 If UBound(m1, 2) <> UBound(m2, 1) Then GoTo Err2 ReDim m3(UBound(m1, 1), UBound(m2, 2)) For i = LBound(m1) To UBound(m1, 1) For j = LBound(m2) To UBound(m1, 2) For k = 1 To UBound(m1, 2) m3(i, j) = m3(i,j)+ m1(i, k) * m2(k, i) Next k Next j Next i Dim Matrix3 As Range Set Matrix3 = Range(ActiveCell.Address, ActiveCell.Offset(UBound(m1, 1) - 1, UBound(m2, 2) - 1)) Matrix3 = m3 Set MatrixMultiplication = Matrix3 Err1: Selection.Cells(0, 0).Value = CVErr(xlErrNull) Err2: Selection.Cells(0, 0).Value = CVErr(xlErrNA) End Function 

不知何故,它不起作用。 它應作為CSE功能。 謝謝你的幫助。

這是一個有效的版本。 有點微妙的一點是,如果將范圍內給定的數組傳遞給它,則需要將它們轉換為常規數組。 請注意函數開頭附近的兩行代碼:

Function MatrixProduct(A As Variant, B As Variant) As Variant
    'Assumes that A,B are 1-based variant arrays
    'Or ranges containing such things.
    'Little error checking is done

    Dim m As Long, n As Long, p As Long, i As Long, j As Long, k As Long
    Dim C As Variant

    If TypeName(A) = "Range" Then A = A.Value
    If TypeName(B) = "Range" Then B = B.Value
    m = UBound(A, 1)
    p = UBound(A, 2)
    If UBound(B, 1) <> p Then
        MatrixProduct = "Not Defined!"
        Exit Function
    End If
    n = UBound(B, 2)

    ReDim C(1 To m, 1 To n)
    For i = 1 To m
        For j = 1 To n
            For k = 1 To p
                C(i, j) = C(i, j) + A(i, k) * B(k, j)
            Next k
        Next j
    Next i
    MatrixProduct = C
End Function

這可以直接在電子表格中使用,也可以直接在VBA代碼中使用。 幾乎肯定比內置的MMULT慢,所以我不太確定它的用處。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM