当我执行以下函数时,出现“无法分配给数组”的编译错误。
我尝试将x2()更改为x2并得到:对于我使用的任何长度或不匹配错误,“下标超出范围”。
Public Function Residual(x1() As Variant, x2() As Variant)
Dim temp1() As Variant, temp2 As Variant
Dim i As Integer, j As Integer, le As Integer
le = UBound(x1) - LBound(x1)
For i = 1 To le
temp1(i) = x2 - x1(i)
temp2 = temp2 + temp1(i)
Next i
Residual = temp2 / le
End Function
Public Function Jacobi(A() As Variant, b() As Variant, x() As Variant, err As Variant)
Dim i As Integer, j As Integer, k As Integer, le As Integer
le = UBound(A) - LBound(A)
ReDim Dia(1 To le, 1 To le)
ReDim Low(1 To le, 1 To le)
ReDim Upp(1 To le, 1 To le)
For i = 1 To le
For j = 1 To le
If i = j Then
Dia(i, j) = A(i, j)
Else: Dia(i, j) = 0
End If
Next j
For j = i + 1 To le
If i < j Then
Low(i, j) = A(i, j)
Else: Low(i, j) = 0
End If
Next j
For j = i + 1 To le
If i > j Then
Upp(i, j) = A(i, j)
Else: Upp(i, j) = 0
End If
Next j
Next i
Dim temp1() As Variant, temp2() As Variant, temp3() As Variant, x1() As Variant, x2() As Variant
x1 = x
Do While Residual(x1, x2) > err
temp1 = Application.WorksheetFunction.MMult(Application.WorksheetFunction.MInverse(Dia), Application.WorksheetFunction.Sum(Low, Upp))
temp2 = Application.WorksheetFunction.MMult(temp1, x1)
temp3 = Application.WorksheetFunction.MMult(Application.WorksheetFunction.MInverse(Dia), b)
x2 = Application.WorksheetFunction.Sum(temp2, temp3)
x1 = x2
Loop
Jacobi = x2
End Function
Sub cek()
Dim A() As Variant, b() As Variant, x() As Variant
Dim hasil As Integer
A = Range("A1:C3")
b = Range("D1:D3")
x = Range("E1:E3")
hasil = Jacobi(A, b, x, 0.0001)
End Sub
我是VBA和这个Jacobi方法程序的新手。我做错了什么?