使用 VBA 进行数组乘法和矩阵求逆

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7302784/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 11:50:20  来源:igfitidea点击:

Array multiplication and matrix inversion with VBA

vba

提问by BVFanZ

I am trying to do some calculations with arrays.

我正在尝试使用数组进行一些计算。

e.g. I want to solve Ax=y, so I use the following code to do so, where A is a square matrix and y is a col. vector. In VBA, A is an array with two dimension and y is one with one dimension. However, this code does not work...

例如,我想解决Ax=y,所以我使用以下代码来解决,其中 A 是方阵, y 是列。向量。在 VBA 中,A 是一个二维数组,y 是一个一维数组。但是,此代码不起作用...

x = WorksheetFunction.MMult(WorksheetFunction.MInverse(A), y)

Where did I get wrong? Thanks!

我哪里错了?谢谢!

回答by Jean-Fran?ois Corbett

You can be committing one or more of many mistakes:

您可能犯了许多错误中的一个或多个:

  • Arrays not defined as Variant(Most worksheetfunctions won't work if data type is something other than Variant).
  • Dimensions of Aand ydon't match up as they need to for matrix multiplication.
  • In particular, won't work if ysize is (1,2)instead of (2,1)as in example below.
  • etc... Can be anything, really. You don't tell us what error message you get.
  • 数组未定义为Variant(如果数据类型不是 ,则大多数工作表函数将不起作用Variant)。
  • 尺寸Ay他们需要为矩阵乘法不匹配。
  • 特别是,如果ysize(1,2)不是(2,1)如下例所示,则不起作用。
  • 等等......可以是任何东西,真的。您没有告诉我们您收到什么错误消息。

Here's an example that works:

这是一个有效的例子:

Dim A As Variant
Dim y As Variant
Dim x As Variant

ReDim y(1 To 2, 1 To 1)
y(1, 1) = 2
y(2, 1) = 3

ReDim A(1 To 2, 1 To 2)
A(1, 1) = 3
A(2, 1) = 1
A(1, 2) = 4
A(2, 2) = 2

x = WorksheetFunction.MMult(WorksheetFunction.MInverse(A), y)

回答by Tunk-Fey

Let matrix A(3 x 3) be an array in Range("A1:C3"), matrix y(3 x 1) be an array in Range("E1:E3"), and matrix x(3 x 1) be an array in Range("G1:G3"). Then you can try this simple program:

设矩阵A(3 x 3) 是 in 的数组Range("A1:C3"),矩阵y(3 x 1) 是 in 的数组Range("E1:E3"),矩阵x(3 x 1) 是 in 的数组Range("G1:G3")。然后你可以试试这个简单的程序:

Range("G1:G3") = WorksheetFunction.MMult(WorksheetFunction.MInverse(Range("A1:C3")), Range("E1:E3"))

By using the same procedure, you can do this to find the result of multiplication of a matrix (n x m) with a matrix (p x q). Of course for the simplification you should declare the variables first. I hope this answer can help you.

通过使用相同的过程,您可以这样做以找到矩阵 (nxm) 与矩阵 (pxq) 相乘的结果。当然,为了简化起见,您应该先声明变量。我希望这个答案可以帮助你。