矩阵数学与 VBA(线性方程组)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23443361/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Matrix Math with VBA (System of Linear Equations)
提问by Tom Winchester
I'm looking for a little help performing some matrix mathematics in Excel's VBA. I've read a ton of replies that suggest using the Excel worksheet but I'm hoping to solve this within the VBA code itself.
我正在寻找在 Excel 的 VBA 中执行一些矩阵数学的一些帮助。我已经阅读了大量建议使用 Excel 工作表的回复,但我希望在 VBA 代码本身中解决这个问题。
Although my application is much larger, let's say I have a system of linear equations that I need to solve:
尽管我的应用程序要大得多,但假设我有一个需要求解的线性方程组:
x1 + x2 = 8
2*x1 + 4*x2 = 100
This can be solved with the simple matrix formula A*x = B or x = A^(-1) * B where,
这可以通过简单的矩阵公式 A*x = B 或 x = A^(-1) * B 来解决,其中,
A = [1, 1; 2, 4]
B = [8; 100]
If you solve this, you'll find x1 = -34 and x2 = 42. In terms of the matrix, then:
如果你解决这个问题,你会发现 x1 = -34 和 x2 = 42。就矩阵而言,则:
X = [-34; 42]
Using Excel's worksheets alongside its MMULT and MINVERSE functions makes this easy and I've gotten it to work just fine. My problem is I'm needing to do this calculation inside a VBA function. Here's what I'm trying:
将 Excel 的工作表与其 MMULT 和 MINVERSE 函数一起使用可以使这变得简单,而且我已经让它正常工作了。我的问题是我需要在 VBA 函数中进行这个计算。这是我正在尝试的:
Dim A(0 To 1, 0 To 1) As Single
Dim B(0 To 0, 0 To 1) As Single
Dim X(0 To 0, 0 To 1) As Single
A(0, 0) = 1
A(1, 0) = 1
A(0, 1) = 2
A(1, 1) = 4
B(0, 0) = 8
B(0, 1) = 100
X = Application.WorksheetFunction.MMult(Application.WorksheetFunction.MInverse(A), B)
Unfortunately, the last line yields a "Compile error: can't assign to array" message. I think it's because I have to specify each element of the array one at a time, but the worksheet functions are array functions.
不幸的是,最后一行产生了“编译错误:无法分配给数组”消息。我认为这是因为我必须一次指定一个数组的每个元素,但工作表函数是数组函数。
How do I fix this?
我该如何解决?
采纳答案by Jean-Fran?ois Corbett
Two things:
两件事情:
The same rule applies as in actual mathematics: B
must be a vertical array for matrix multiplication to be possible in your case. Declare it as
与实际数学中的规则相同:B
必须是垂直数组,才能在您的情况下进行矩阵乘法。将其声明为
Dim B(0 To 1, 0 To 0) As Single
and initialize it accordingly. Also, just declare
并相应地初始化它。另外,只需声明
Dim X As Variant
since the MMult
returns a Variant array. This is what was causing your original error.
因为MMult
返回一个 Variant 数组。这就是导致您原始错误的原因。