我需要你的帮助才能在VBA中乘以两个矩阵A和B. 其中A(1000000 * 3)和B(3 * 3) mmult函数不适用于乘以大矩阵。知道如何做到这一点。
提前多多感谢,
答案 0 :(得分:2)
我的猜测是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秒。
答案 1 :(得分:0)
@Marco Getrost
cases=1000000
c=3
T is a 3*3 matrix
r = Application.MMult(randn(cases, c), T)
Function randn(rows As Variant, cols As Variant) As Variant
Dim mymat() As Variant
ReDim mymat(1 To rows, 1 To cols)
Dim i, j As Variant
For i = 1 To rows
For j = 1 To cols
mymat(i, j) = Application.NormInv(Rnd(), 0, 1)
Next j
Next i
randn = mymat
End Function