问题
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...
x = WorksheetFunction.MMult(WorksheetFunction.MInverse(A), y)
Where did I get wrong? Thanks!
回答1:
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 thanVariant
). - Dimensions of
A
andy
don't match up as they need to for matrix multiplication. - In particular, won't work if
y
size 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.
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)
回答2:
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:
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.
来源:https://stackoverflow.com/questions/7302784/array-multiplication-and-matrix-inversion-with-vba