简体   繁体   中英

Function mimicing Excel MMULT

I wanted to create function that mimics standard Excel MMULT function for multiplying matrices. My code is:

 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 

Somehow it does not work. It should work as CSE function. Thanks for any help.

Here is a version that works. A somewhat subtle point is that if you pass it arrays which are given in ranges then you need to convert them to regular arrays. Note the two lines near the beginning of the function that do that:

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

This can be used directly in the spreadsheet and also be used directly in VBA code. It is almost definitely slower then the built-in MMULT, so I'm not quite sure how useful it is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM