excel - 在VBA中将两个大矩阵相乘

标签 excel matrix multiplication vba

我需要你的帮助来在 VBA 中将两个矩阵 A 和 B 相乘。 其中 A(1000000*3) 和 B(3*3) mmult 函数不适用于大型矩阵的乘法。知道如何做到这一点。

提前非常感谢,

最佳答案

我的猜测是 mmult 使用 16 位整数作为索引,这不足以容纳 1,000,000 行。您可以编写自己的函数来获取包含数组的两个变体并返回包含乘积的变体。使用 Long 而不是 Integer 作为索引变量就足够了:

Function MatrixProduct(A As Variant, B As Variant) As Variant
    'Assumes that A,B are 1-based variant arrays

    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

为了测试这一点,我编写了一个函数来创建随机矩阵:

Function RandMatrix(m As Long, n As Long) As Variant
    Dim A As Variant
    Dim i As Long, j As Long
    ReDim A(1 To m, 1 To n)

    Randomize
    For i = 1 To m
        For j = 1 To n
            A(i, j) = Rnd()
        Next j
    Next i
    RandMatrix = A
End Function

然后我运行了这个:

Sub test()
    Dim start As Double
    Dim cases As Long
    Dim A As Variant, B As Variant, C As Variant

    cases = 1000000
    A = RandMatrix(cases, 3)
    B = RandMatrix(3, 3)
    start = Timer
    C = MatrixProduct(A, B)
    MsgBox (Timer - start) & " seconds to compute the product"

End Sub

在我的机器上大约需要 1.7 秒。

关于excel - 在VBA中将两个大矩阵相乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34000703/

相关文章:

javascript - 将嵌套数组连接到向量?

r - 在 R 字符串中的每 k 个位置插入字符

java - 有人可以向我解释这段使用移位将两个变量相乘的代码吗?

c++ - 在 C++ 错误中乘以 double

vba - Excel VBA 重命名错误的工作表

vba - 根据用户操作将过程附加到事件

java - 比较 excel 中的列

excel - 为什么选择范围变量时会发生变化?

c - 如何在共享内存中的矩阵上写入?

c++ - 返回类型 Vector