在VBA中减去矩阵?

时间:2014-07-21 11:28:24

标签: vba

我希望有人可以帮我解决这个问题。我在VBA中很新,所以我的问题可能很愚蠢。我事先道歉...... :):

我写了以下函数,用于相互减去矩阵:

Option Base 1
Option Explicit

Function MatrixSubtract(matrix1 As Variant, matrix2 As Variant)

Dim row1 As Integer
Dim row2 As Integer
Dim col1 As Integer
Dim col2 As Integer
Dim m As Integer
Dim n As Integer
Dim MatrixSubtract As Variant

row1 = UBound(matrix1, 1)
col1 = UBound(matrix1, 2)
row2 = UBound(matrix2, 1)
col2 = UBound(matrix2, 2)

If (row1 <> row2) Or (col1 <> col2) Then
    MsgBox ("Dimension mismatch. Subtraction can't be performed")
Exit Function
End If

ReDim diff(1 To row1, 1 To col1)

For m = 1 To row1
     For n = 1 To col1
         diff(m, n) = matrix1(m, n) - matrix2(m, n)
     Next n
Next m

MatrixSubtract = diff

End Function

在excel中使用函数时(在所有条目中从1乘2矩阵中包含零的1到2矩阵中包含1),我得到一个带#VALUE的1乘2矩阵!在每个细胞中。

但是,如果我将相同的代码编写为sub(见下文)并给出与上面输入相同的矩阵,代码是否有效?我怀疑它与我在函数中的语法有关?谢谢。

Option Base 1
Option Explicit

Sub MatrixSubtract()

Dim matrix1(1, 2) As Variant
Dim matrix2(1, 2) As Variant

matrix1(1, 1) = 0
matrix1(1, 2) = 0
matrix2(1, 1) = 1
matrix2(1, 2) = 1

Dim row1 As Integer
Dim row2 As Integer
Dim col1 As Integer
Dim col2 As Integer
Dim m As Integer
Dim n As Integer
Dim MatrixSubtract As Variant

row1 = UBound(matrix1, 1)
col1 = UBound(matrix1, 2)
row2 = UBound(matrix2, 1)
col2 = UBound(matrix2, 2)

ReDim diff(1 To row1, 1 To col1)

If (row1 <> row2) Or (col1 <> col2) Then
    MsgBox ("Dimension mismatch. Subtraction can't be performed")
    Exit Sub
End If

For m = 1 To row1
    For n = 1 To col1
        diff(m, n) = matrix1(m, n) - matrix2(m, n)
    Next n
Next m

MatrixSubtract = diff

End Sub

1 个答案:

答案 0 :(得分:0)

这里不需要VBA代码。 Excel具有内置的矩阵操作机制。对于加法和减法,使用常规函数语法到单元格范围,并将它们作为数组公式输入。

Example 1

还可以使用TRANSPOSE()MMULT()MINVERSE()和其他内置函数进行更复杂的操作。

如果要编写函数以返回数组,请参阅以下示例:

Public Function IdentityMatrix(ByVal N As Integer) As Variant()

    Dim vals() As Variant
    ReDim vals(1 To N, 1 To N)
    Dim i As Integer, j As Integer

    For i = 1 To N
        For j = 1 To N
            If i = j Then
                vals(i, j) = 1#
            Else
                vals(i, j) = 0#
            End If
        Next j
    Next i

    IdentityMatrix = vals
End Function

用作:

Example 2

结果:

Example 3