[英]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.