简体   繁体   English

模拟Excel MMULT的函数

[英]Function mimicing Excel MMULT

I wanted to create function that mimics standard Excel MMULT function for multiplying matrices. 我想创建模仿标准Excel MMULT函数以求矩阵相乘的函数。 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. 它应作为CSE功能。 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. 这可以直接在电子表格中使用,也可以直接在VBA代码中使用。 It is almost definitely slower then the built-in MMULT, so I'm not quite sure how useful it is. 几乎肯定比内置的MMULT慢,所以我不太确定它的用处。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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